file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial18/OgnTutorialState.cpp
// Copyright (c) 2020-2021, 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. // #include <OgnTutorialStateDatabase.h> #include <atomic> // Implementation of a C++ OmniGraph node that uses internal state information to compute outputs. class OgnTutorialState { // ------------------------------------------------------------ // The presence of these members will be detected when a node of this type is being instantiated, at which // time an instance of this node will be attached to the OmniGraph node and be made available in the // database class as the member "db.internalState<OgnTutorialState>()". // // Start all nodes with a monotinic increment value of 0 size_t mIncrementValue{ 0 }; // ------------------------------------------------------------ // You can also define node-type static data, although you are responsible for dealing with any // thread-safety issues that may arise from accessing it from multiple threads (or multiple hardware) // at the same time. In this case it is a single value that is read and incremented so an atomic // variable is sufficient. In real applications this would be a complex structure, potentially keyed off // of combinations of inputs or real time information, requiring more stringent locking. // // This value increases for each node and indicates the value from which a node's own internal state value // increments. e.g. the first instance of this node type will start its state value at 1, the second instance at 2, // and so on... static std::atomic<size_t> sStartingValue; public: // Operation of the state mechanism relies on the presence of a default constructor. If you don't have to do // any initialization you can let the compiler provide the default implementation. OgnTutorialState() { mIncrementValue = sStartingValue; // Update the per-class state information for the next node. The values go up by 100 to make it easier for // tests to compare the state information on different nodes. sStartingValue += 100; } // Helper function to update the node's internal state based on the previous values and the per-class state. // You could also do this in-place in the compute() function; pulling it out here makes the state manipulation // more explicit. void updateState() { mIncrementValue += 1; } public: // Compute the output based on inputs and internal state static bool compute(OgnTutorialStateDatabase& db) { // This illustrates how internal state and inputs can be used in conjunction. The inputs can be used // to divert to a different computation path. if (db.inputs.override()) { db.outputs.monotonic() = db.inputs.overrideValue(); } else { // OmniGraph ensures that the database contains the correct internal state information for the node // being evaluated. Beyond that it has no knowledge of the data within that state. auto& state = db.internalState<OgnTutorialState>(); db.outputs.monotonic() = state.mIncrementValue; // Update the node's internal state data for the next evaluation. state.updateState(); } return true; } }; std::atomic<size_t> OgnTutorialState::sStartingValue{ 0 }; REGISTER_OGN_NODE()
3,784
C++
44.059523
119
0.68129
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial28/OgnTutorialVectorizedPassthrough.cpp
// 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. // #include <OgnTutorialVectorizedPassthroughDatabase.h> // The method used by the computation to perform the passthrough // 0 = simple copy, no vectorization #define TUTO_PASSTHROUGH_METHOD_SIMPLE 0 // 1 = vectorized copy by moving the entire database to the next instance #define TUTO_PASSTHROUGH_METHOD_DB 1 // 2 = vectorized copy by indexing the instance directly per attribute #define TUTO_PASSTHROUGH_METHOD_ATTR 2 // 3 = vectorized copy using raw data #define TUTO_PASSTHROUGH_METHOD_RAW 3 //By default, use the most efficient method #define TUTO_PASSTHROUGH_METHOD TUTO_PASSTHROUGH_METHOD_RAW // This node perform a copy of its input to its output class OgnTutorialVectorizedPassthrough { public: #if TUTO_PASSTHROUGH_METHOD == TUTO_PASSTHROUGH_METHOD_SIMPLE // begin-regular static bool compute(OgnTutorialVectorizedPassthroughDatabase& db) { db.outputs.value() = db.inputs.value(); return true; } // end-regular #elif TUTO_PASSTHROUGH_METHOD == TUTO_PASSTHROUGH_METHOD_DB // begin-db static size_t computeVectorized(OgnTutorialVectorizedPassthroughDatabase& db, size_t count) { for(size_t idx = 0; idx < count; ++idx) { db.outputs.value() = db.inputs.value(); db.moveToNextInstance(); } return count; } // end-db #elif TUTO_PASSTHROUGH_METHOD == TUTO_PASSTHROUGH_METHOD_ATTR // begin-attr static size_t computeVectorized(OgnTutorialVectorizedPassthroughDatabase& db, size_t count) { for(size_t idx = 0; idx < count; ++idx) db.outputs.value(idx) = db.inputs.value(idx); return count; } // end-attr #elif TUTO_PASSTHROUGH_METHOD == TUTO_PASSTHROUGH_METHOD_RAW // begin-raw static size_t computeVectorized(OgnTutorialVectorizedPassthroughDatabase& db, size_t count) { auto spanIn = db.inputs.value.vectorized(count); auto spanOut = db.outputs.value.vectorized(count); memcpy(spanOut.data(), spanIn.data(), count * sizeof(float)); return count; } // end-raw #endif }; REGISTER_OGN_NODE()
2,547
C++
32.526315
95
0.708677
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial21/tutorial21.rst
.. _ogn_tutorial_bundle_add_attributes: Tutorial 21 - Adding Bundled Attributes ======================================= Sometimes instead of simply copying data from an input or input bundle into an output bundle you might want to construct a bundle from some other criteria. For example a bundle construction node could take in an array of names and attribute types and output a bundle consisting of those attributes with some default values. The bundle accessor provides a simple method that can accomplish this task. Adding a new attribute is as simple as providing those two values to the bundle for every attribute you wish to add. There is also a complementary function to remove named bundle attributes. OgnTutorialBundleAddAttributes.ogn ---------------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.BundleData", which has one input bundle and one output bundle. .. literalinclude:: OgnTutorialBundleAddAttributes.ogn :linenos: :language: json OgnTutorialBundleAddAttributes.cpp ---------------------------------- The *cpp* file contains the implementation of the compute method. It accesses the attribute descriptions on the inputs and creates a bundle with attributes matching those descriptions as its output. .. literalinclude:: OgnTutorialBundleAddAttributes.cpp :linenos: :language: c++ OgnTutorialBundleAddAttributesPy.py ----------------------------------- The *py* file contains the same algorithm as the C++ node, with only the implementation language being different. .. literalinclude:: OgnTutorialBundleAddAttributesPy.py :linenos: :language: python
1,656
reStructuredText
40.424999
125
0.733092
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial21/OgnTutorialBundleAddAttributesPy.py
""" Implementation of the Python node adding attributes with a given description to an output bundle. """ import omni.graph.core as og class OgnTutorialBundleAddAttributesPy: """Exercise the bundled data types through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Implements the same algorithm as the C++ node OgnTutorialBundleAddAttributes.cpp using the Python bindings to the bundle method """ # Start with an empty output bundle. output_bundle = db.outputs.bundle output_bundle.clear() if db.inputs.useBatchedAPI: attr_types = [og.AttributeType.type_from_ogn_type_name(type_name) for type_name in db.inputs.typesToAdd] output_bundle.add_attributes(attr_types, db.inputs.addedAttributeNames) output_bundle.remove_attributes(db.inputs.removedAttributeNames) else: for attribute_type_name, attribute_name in zip(db.inputs.typesToAdd, db.inputs.addedAttributeNames): attribute_type = og.AttributeType.type_from_ogn_type_name(attribute_type_name) output_bundle.insert((attribute_type, attribute_name)) # Remove attributes from the bundle that were already added. This is a somewhat contrived operation that # allows testing of both adding and removal within a simple environment. for attribute_name in db.inputs.removedAttributeNames: output_bundle.remove(attribute_name) return True
1,529
Python
41.499999
116
0.689993
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial21/OgnTutorialBundleAddAttributes.cpp
// Copyright (c) 2021, 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. // #include <OgnTutorialBundleAddAttributesDatabase.h> #include <omni/graph/core/IAttributeType.h> using omni::graph::core::Type; class OgnTutorialBundleAddAttributes { public: static bool compute(OgnTutorialBundleAddAttributesDatabase& db) { const auto& attributeTypeNames = db.inputs.typesToAdd(); const auto& attributeNames = db.inputs.addedAttributeNames(); const auto& useBatchedAPI = db.inputs.useBatchedAPI(); auto& outputBundle = db.outputs.bundle(); // The usual error checking. Being diligent about checking the data ensures you will have an easier time // debugging the graph if anything goes wrong. if (attributeTypeNames.size() != attributeNames.size()) { db.logWarning( "Number of attribute types (%zu) does not match number of attribute names (%zu)", attributeTypeNames.size(), attributeNames.size() ); return false; } // Make sure the bundle is starting from empty outputBundle.clear(); if (useBatchedAPI) { // // unfortunately we need to build a vector of the types // auto typeNameIt = std::begin(attributeTypeNames); std::vector<Type> types; types.reserve(attributeTypeNames.size()); for (; typeNameIt != std::end(attributeTypeNames); ++typeNameIt) { auto typeName = *typeNameIt; types.emplace_back(db.typeFromName(typeName)); } outputBundle.addAttributes(attributeTypeNames.size(), attributeNames.data(), types.data()); // Remove attributes from the bundle that were already added. This is a somewhat contrived operation that // allows testing of both adding and removal within a simple environment. if (db.inputs.removedAttributeNames().size()) { outputBundle.removeAttributes(db.inputs.removedAttributeNames().size(), db.inputs.removedAttributeNames().data()); } } else { // Since the two arrays are the same size a dual loop can be used to walk them in pairs auto typeNameIt = std::begin(attributeTypeNames); auto attributeNameIt = std::begin(attributeNames); for (; typeNameIt != std::end(attributeTypeNames) && attributeNameIt != std::end(attributeNames); ++typeNameIt, ++attributeNameIt) { auto typeName = *typeNameIt; auto attributeName = *attributeNameIt; auto typeNameString = db.tokenToString(typeName); Type newType = db.typeFromName(typeName); // Ignore the output since for this example there will not be any values set on the new attribute (void)outputBundle.addAttribute(attributeName, newType); } // Remove attributes from the bundle that were already added. This is a somewhat contrived operation that // allows testing of both adding and removal within a simple environment. for (const auto& toRemove : db.inputs.removedAttributeNames()) { outputBundle.removeAttribute(toRemove); } } return true; } }; REGISTER_OGN_NODE()
3,786
C++
42.03409
142
0.637612
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial8/tutorial8.rst
.. _ogn_tutorial_cudaData: Tutorial 8 - GPU Data Node ========================== The GPU data node creates various attributes for use in a CUDA-based GPU compute. Several representative types are used, though the list of potential attribute types is not exhaustive. See :ref:`ogn_attribute_types` for the full list. This node also introduces the notion of attribute typedefs; a useful concept when passing data around in functions. OgnTutorialCudaData.ogn ----------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CudaData", which has inputs and outputs of various types to use in various computations. Three different CUDA methods are created to show how each of the types is passed through to the GPU and used by CUDA. .. literalinclude:: OgnTutorialCudaData.ogn :linenos: :language: json OgnTutorialCudaData.cpp ----------------------- The *cpp* file contains the implementation of the compute method, which in turn calls the three CUDA algorithms. .. literalinclude:: OgnTutorialCudaData.cpp :linenos: :language: c++ OgnTutorialCudaData_CUDA.cu --------------------------- The *cu* file contains the implementation of the algorithms on the GPU using CUDA. .. literalinclude:: OgnTutorialCudaData_CUDA.cu :linenos: :language: c++ GPU Attribute Access -------------------- Here is the set of generated attributes from the database. The attributes living on the GPU return pointers to memory as the CPU side cannot dereference it into its actual type (e.g. a `float` value, which would be returned as a `float&` on the CPU side is returned instead as a `float*` on the GPU side.) In addition, when calling into CUDA code the data changes type as it crosses the GPU boundary. On the CUDA side it uses the CUDA native data types when it can, which are bytewise compatible with their CPU counterparts. Note that in the case of the CPU attribute *multiplier* the data is passed to the CUDA code by value, since it has to be copied from CPU to GPU. +---------------------+---------+--------------------+-----------------+ | Database Function | Is GPU? | CPU Type | CUDA Type | +=====================+=========+====================+=================+ | inputs.a() | Yes | const float* | const float* | +---------------------+---------+--------------------+-----------------+ | inputs.b() | Yes | const float* | const float* | +---------------------+---------+--------------------+-----------------+ | outputs.sum() | Yes | float* | float* | +---------------------+---------+--------------------+-----------------+ | inputs.half() | Yes | const pxr::GfHalf* | __half* | +---------------------+---------+--------------------+-----------------+ | outputs.half() | Yes | pxr::GfHalf* | __half* | +---------------------+---------+--------------------+-----------------+ | inputs.color() | Yes | const GfVec3d* | const double3* | +---------------------+---------+--------------------+-----------------+ | outputs.color() | Yes | GfVec3d* | double3* | +---------------------+---------+--------------------+-----------------+ | inputs.matrix() | Yes | const GfMatrix4d* | const Matrix4d* | +---------------------+---------+--------------------+-----------------+ | outputs.matrix() | Yes | GfMatrix4d* | Matrix4d* | +---------------------+---------+--------------------+-----------------+ | inputs.multiplier() | No | const GfVec3f& | const float3 | +---------------------+---------+--------------------+-----------------+ | inputs.points() | Yes | const GfVec3f* | const float3** | +---------------------+---------+--------------------+-----------------+ | outputs.points() | Yes | GfVec3f* | float3** | +---------------------+---------+--------------------+-----------------+ The array attribute *points* does not have an array-like wrapper as the CUDA code would rather deal with raw pointers. In order to provide the size information, when calling the CUDA code the value ``inputs.points.size()`` should also be passed in. Notice the subtle difference in types on the CPU side for GPU-based data. Instead of references to data there are pointers, necessary since the data lives in a different memory-space, and all pointers have an extra level of indirection for the same reason. There is also a section of this generated file dedicated to information relevant to the CUDA code. In this section the CUDA attribute data types are defined. It is protected with ``#ifdef __CUDACC__`` so that it is only processed when included through the CUDA compiler (and vice versa, so none of the other setup code will be processed on the CUDA side). .. code-block:: c++ #include <cuda_fp16.h> #include <omni/graph/core/cuda/CUDAUtils.h> #include <omni/graph/core/cuda/Matrix4d.h> namespace OgnTutorialCudaDataCudaTypes { namespace inputs { using a_t = const float*; using b_t = const float*; using points_t = const float3**; using multiplier_t = const float3*; using half_t = const __half*; using color_t = const double3*; using matrix_t = const Matrix4d*; } namespace outputs { using sum_t = float*; using points_t = float3**; using half_t = __half*; using color_t = double3*; using matrix_t = Matrix4d*; } } using namespace OgnTutorialCudaDataCudaTypes; Notice the inclusion of the file *cuda_fp16.h*, needed due to the use of the CUDA type *__half*, and the files *omni/graph/core/cuda/CUDAUtils.h* and *omni/graph/core/cuda/Matrix4d.h*, which provide support functions for CUDA math. The data types used by CUDA are compatible with their equivalents on the C++ side, so you can specify passing arguments into CUDA from C++ by using a declaration such as this on the C++ side: .. code-block:: c++ // In this code "inputs::points_t" is the type "GfVec3f*". // The size of that array must be passed in as well since it is not implicit in the data type. extern "C" void cudaCompute( inputs::points_t*, size_t pointSize, inputs::multiplier_t*, outputs::points_t* ); which corresponds to this function defined in the .cu file: .. code-block:: c++ // In this code "inputs::points_t" is the type "float3*" extern "C" void cudaCompute( inputs::points_t* inPoints, size_t pointSize, inputs::multiplier_t* multiplier, outputs::points_t* outPoints ) {...} Pointers are used in the calls rather than being part of the type definitions in order to emphasize the fact that the values passed through are pointers to the real data in the flatcache, which in this case is data in GPU memory.
6,896
reStructuredText
44.375
120
0.571491
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial8/OgnTutorialCudaData.cpp
// Copyright (c) 2020, 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. // #include <omni/graph/core/GpuArray.h> #include <OgnTutorialCudaDataDatabase.h> // This function exercises referencing simple data types on the GPU, something you normally wouldn't do as // there is no efficiency gain in doing that versus just passing in the CPU value. extern "C" void applyAddGPU(outputs::sum_t sum, inputs::a_t a, inputs::b_t b); // This function exercises referencing of array data on the GPU. // The CUDA code takes its own "float3" data types, which are castable equivalents to the generated GfVec3f. // The GpuArray/ConstGpuArray wrappers isolate the GPU pointers from the CPU code. extern "C" void applyDeformationGPU(outputs::points_t outputPoints, inputs::points_t inputPoints, inputs::multiplier_t multiplier, size_t numberOfPoints); // This function exercises referencing non-standard data types on the GPU to illustrate how data of different // types are passed to the GPU. extern "C" void applyDataTypes(outputs::half_t halfOutput, outputs::color_t colorOutput, outputs::matrix_t matrixOutput, inputs::half_t halfInput, inputs::color_t colorInput, inputs::matrix_t matrixInput); // This node runs a couple of algorithms on the GPU, while accessing parameters from the CPU class OgnTutorialCudaData { public: static bool compute(OgnTutorialCudaDataDatabase& db) { // ================ algorithm 1 ========================================================= // It's an important distinction here that GPU data is always returned as raw pointers since the CPU code // in the node cannot directly access it. The raw pointers are passed into the GPU code for dereferencing. applyAddGPU(db.outputs.sum(), db.inputs.a(), db.inputs.b()); // ================ algorithm 2 ========================================================= size_t numberOfPoints = db.inputs.points.size(); db.outputs.points.resize(numberOfPoints); const auto& multiplier = db.inputs.multiplier(); if (numberOfPoints > 0) { applyDeformationGPU(db.outputs.points(), db.inputs.points(), db.inputs.multiplier(), numberOfPoints); } // ================ algorithm 3 ========================================================= applyDataTypes(db.outputs.half(), db.outputs.color(), db.outputs.matrix(), db.inputs.half(), db.inputs.color(), db.inputs.matrix()); return true; } }; REGISTER_OGN_NODE()
3,142
C++
49.693548
114
0.614895
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial10/OgnTutorialSimpleDataPy.py
""" Implementation of the Python node accessing all of the simple data types. This class exercises access to the DataModel through the generated database class for all simple data types. It implements the same algorithm as the C++ node OgnTutorialSimpleData.cpp """ import omni.graph.tools.ogn as ogn class OgnTutorialSimpleDataPy: """Exercise the simple data types through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Perform a trivial computation on all of the simple data types to make testing easy""" # Inside the database the contained object "inputs" holds the data references for all input attributes and the # contained object "outputs" holds the data references for all output attributes. # Each of the attribute accessors are named for the name of the attribute, with the ":" replaced by "_". # The colon is used in USD as a convention for creating namespaces so it's safe to replace it without # modifying the meaning. The "inputs:" and "outputs:" prefixes in the generated attributes are matched # by the container names. # For example attribute "inputs:translate:x" would be accessible as "db.inputs.translate_x" and attribute # "outputs:matrix" would be accessible as "db.outputs.matrix". # The "compute" of this method modifies each attribute in a subtle way so that a test can be written # to verify the operation of the node. See the .ogn file for a description of tests. db.outputs.a_bool = not db.inputs.a_bool db.outputs.a_half = 1.0 + db.inputs.a_half db.outputs.a_int = 1 + db.inputs.a_int db.outputs.a_int64 = 1 + db.inputs.a_int64 db.outputs.a_double = 1.0 + db.inputs.a_double db.outputs.a_float = 1.0 + db.inputs.a_float db.outputs.a_uchar = 1 + db.inputs.a_uchar db.outputs.a_uint = 1 + db.inputs.a_uint db.outputs.a_uint64 = 1 + db.inputs.a_uint64 db.outputs.a_string = db.inputs.a_string.replace("hello", "world") db.outputs.a_objectId = 1 + db.inputs.a_objectId # The token interface is made available in the database as well, for convenience. # By calling "db.token" you can look up the token ID of a given string. if db.inputs.a_token == "helloToken": db.outputs.a_token = "worldToken" # Path just gets a new child named "Child". # In the implementation the string is manipulated directly, as it does not care if the SdfPath is valid or # not. If you want to manipulate it using the pxr.Sdf.Path API this is how you could do it: # # from pxr import Sdf # input_path Sdf.Path(db.inputs.a_path) # if input_path.IsValid(): # db.outputs.a_path() = input_path.AppendChild("/Child").GetString(); # db.outputs.a_path = db.inputs.a_path + "/Child" # To access the metadata you have to go out to the ABI, though the hardcoded metadata tags are in the # OmniGraph Python namespace assert db.node.get_attribute("inputs:a_bool").get_metadata(ogn.MetadataKeys.UI_NAME) == "Simple Boolean Input" # You can also use the database interface to get the same data db.outputs.a_nodeTypeUiName = db.get_metadata(ogn.MetadataKeys.UI_NAME) db.outputs.a_a_boolUiName = db.get_metadata(ogn.MetadataKeys.UI_NAME, db.attributes.inputs.a_bool) return True
3,475
Python
52.476922
118
0.671655
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial10/tutorial10.rst
.. _ogn_tutorial_simpleDataPy: Tutorial 10 - Simple Data Node in Python ======================================== The simple data node creates one input attribute and one output attribute of each of the simple types, where "simple" refers to data types that have a single component and are not arrays. (e.g. "float" is simple, "float[3]" is not, nor is "float[]"). See also :ref:`ogn_tutorial_simpleData` for a similar example in C++. Automatic Python Node Registration ---------------------------------- By implementing the standard Carbonite extension interfact in Python, OmniGraph will know to scan your Python import path for to recursively scan the directory, import all Python node files it finds, and register those nodes. It will also deregister those nodes when the extension shuts down. Here is an example of the directory structure for an extension with a single node in it. (For extensions that have a `premake5.lua` build script this will be in the build directory. For standalone extensions it is in your source directory.) .. code-block:: text omni.my.extension/ omni/ my/ extension/ nodes/ OgnMyNode.ogn OgnMyNode.py OgnTutorialSimpleDataPy.ogn --------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.SimpleDataPy", which has one input and one output attribute of each simple type. .. literalinclude:: OgnTutorialSimpleDataPy.ogn :linenos: :language: json OgnTutorialSimpleDataPy.py -------------------------- The *py* file contains the implementation of the compute method, which modifies each of the inputs in a simple way to create outputs that have different values. .. literalinclude:: OgnTutorialSimpleDataPy.py :linenos: :language: python Note how the attribute values are available through the ``OgnTutorialSimpleDataPyDatabase`` class. The generated interface creates access methods for every attribute, named for the attribute itself. They are all implemented as Python properties, where inputs only have get methods and outputs have both get and set methods. Pythonic Attribute Data ----------------------- Three subsections are creating in the generated database class. The main section implements the node type ABI methods and uses introspection on your node class to call any versions of the ABI methods you have defined (see later tutorials for examples of how this works). The other two subsections are classes containing attribute access properties for inputs and outputs. For naming consistency the class members are called *inputs* and *outputs*. For example, you can access the value of the input attribute named *foo* by referencing ``OgnTutorialSimpleDataPyDatabase.inputs.foo``. For the curious, here is an example of how the boolean attribute access is set up on the simple tutorial node: .. code-block:: python class OgnTutorialSimpleDataPyDatabase: class InputAttributes: def __init__(self, context_helper, node): self.context_helper = context_helper self.node = node # A lock is used to prevent inputs from inadvertently being modified during a compute. # This is equivalent to the "const" approach used in C++. self.setting_locked = False # Caching the Attribute object lets future data access run faster self._a_bool = node.get_attribute('inputs:a_bool') @property def a_bool(self): return self.context_helper.get_attr_value(self._a_bool) @a_bool.setter def a_bool(self, value): if self.setting_locked: raise AttributeError('inputs:a_bool') self.context_helper.set_attr_value(value, self._a_bool) class OutputAttributes: def __init__(self, context_helper, node): self.context_helper = context_helper self.node = node self._a_bool = node.get_attribute('outputs:a_bool') @property def a_bool(self): return self.context_helper.get_attr_value(self._a_bool) @a_bool.setter def a_bool(self, value): self.context_helper.set_attr_value(value, self._a_bool) def __init__(self, context, node): self.context = context self.node = node self.context_helper = ContextHelper(context) self.inputs = OgnTutorialSimpleDataPyDatabase.InputAttributes(self.context_helper, node) self.outputs = OgnTutorialSimpleDataPyDatabase.OutputAttributes(self.context_helper, node) Pythonic Attribute Access ------------------------- In the USD file the attribute names are automatically namespaced as *inputs:FOO* or *outputs:BAR*. In the Python interface the colon is illegal so the contained classes above are used to make use of the dot-separated equivalent, as *inputs.FOO* or *outputs.BAR*. While the underlying data types are stored in their exact form there is conversion when they are passed back to Python as Python has a more limited set of data types, though they all have compatible ranges. For this class, these are the types the properties provide: +-------------------+---------------+ | Database Property | Returned Type | +===================+===============+ | inputs.a_bool | bool | +-------------------+---------------+ | inputs.a_half | float | +-------------------+---------------+ | inputs.a_int | int | +-------------------+---------------+ | inputs.a_int64 | int | +-------------------+---------------+ | inputs.a_float | float | +-------------------+---------------+ | inputs.a_double | float | +-------------------+---------------+ | inputs.a_token | str | +-------------------+---------------+ | outputs.a_bool | bool | +-------------------+---------------+ | outputs.a_half | float | +-------------------+---------------+ | outputs.a_int | int | +-------------------+---------------+ | outputs.a_int64 | int | +-------------------+---------------+ | outputs.a_float | float | +-------------------+---------------+ | outputs.a_double | float | +-------------------+---------------+ | outputs.a_token | str | +-------------------+---------------+ The data returned are all references to the real data in the FlatCache, our managed memory store, pointed to the correct location at evaluation time. Python Helpers -------------- A few helpers are provided in the database class definition to help make coding with it more natural. Python logging ++++++++++++++ Two helper functions are providing in the database class to help provide more information when the compute method of a node has failed. Two methods are provided, both taking a formatted string describing the problem. ``log_error(message)`` is used when the compute has run into some inconsistent or unexpected data, such as two input arrays that are supposed to have the same size but do not, like the normals and vertexes on a mesh. ``log_warning(message)`` can be used when the compute has hit an unusual case but can still provide a consistent output for it, for example the deformation of an empty mesh would result in an empty mesh and a warning since that is not a typical use for the node. Direct Pythonic ABI Access ++++++++++++++++++++++++++ All of the generated database classes provide access to the underlying *INodeType* ABI for those rare situations where you want to access the ABI directly. There are two members provided, which correspond to the objects passed in to the ABI compute method. There is the graph evaluation context member, ``context: Py_GraphContext``, for accessing the underlying OmniGraph evaluation context and its interface. There is also the OmniGraph node member, ``node: Py_Node``, for accessing the underlying OmniGraph node object and its interface.
8,133
reStructuredText
44.188889
120
0.628673
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial13/OgnTutorialStatePy.py
""" Implementation of a Python node that uses internal state information to compute outputs. There are two types of state information in use here: - OgnTutorialStatePy.step (per-class state information) This is inherently dangerous in a multi-threaded multi-hardware evaluation so it must be used with care. In this case the value is only used when a node is created, which for now is a safe single-threaded operation - per-node state information. """ class OgnTutorialStatePyInternalState: """Convenience class for maintaining per-node state information""" def __init__(self): """Instantiate the per-node state information. Note: For convenience, per-node state data is maintained as members of this class, imposing the minor restriction of having no parameters allowed in this constructor. The presence of the "state" section in the .ogn node has flagged to omnigraph the fact that this node will be managing some per-node state data. """ # Start all nodes with a monotinic increment value of 0 self.increment_value = 0 # Get this node's internal step value from the per-class state information self.node_step = OgnTutorialStatePy.step # Update the per-class state information for the next node OgnTutorialStatePy.step += 1 def update_state(self): """Helper function to update the node's internal state based on the previous values and the per-class state""" self.increment_value += self.node_step class OgnTutorialStatePy: """Use internal node state information in addition to inputs""" # This is a simplified bit of internal per-class state information. In real applications this would be a complex # structure, potentially keyed off of combinations of inputs or real time information. # # This value increases for each node and indicates the value at which a node's own internal state value increments. # e.g. the first instance of this node type will increment its state value by 1, the second instance of it by 2, # and so on... step = 1 # Defining this method, in conjunction with adding the "state" section in the .ogn file, tells OmniGraph that you # intend to maintain opaque internal state information on your node. OmniGraph will ensure that your node is not # scheduled for evaluation in such a way that it would compromise the thread-safety of your node due to this state # information, however you are responsible for updating the values and/or maintaining your own dirty bits when # required. @staticmethod def internal_state(): """Returns an object that will contain per-node state information""" return OgnTutorialStatePyInternalState() @staticmethod def compute(db) -> bool: """Compute the output based on inputs and internal state""" # This illustrates how internal state and inputs can be used in conjunction. The inputs can be used # to divert to a different computation path. if db.inputs.override: db.outputs.monotonic = db.inputs.overrideValue else: # OmniGraph ensures that the database contains the correct internal state information for the node # being evaluated. Beyond that it has no knowledge of the data within that state. db.outputs.monotonic = db.internal_state.increment_value # Update the node's internal state data for the next evaluation. db.internal_state.update_state() return True
3,600
Python
46.381578
119
0.709167
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial13/tutorial13.rst
.. _ogn_tutorial_state_py: Tutorial 13 - Python State Node =============================== This node illustrates how you can use internal state information, so long as you inform OmniGraph that you are doing so in order for it to make more intelligent execution scheduling decisions. OgnTutorialStatePy.ogn ---------------------- The *.ogn* file containing the implementation of a node named "omni.graph.tutorials.StatePy", with an empty state set to inform OmniGraph of its intention to compute using internal state information. .. literalinclude:: OgnTutorialStatePy.ogn :linenos: :language: json OgnTutorialStatePy.py --------------------- The *.py* file contains the compute method and the internal state information used to run the algorithm. By overriding the special method ``internal_state`` you can define an object that will contain per-node data that you can manage yourself. It will not be visible to OmniGraph. .. literalinclude:: OgnTutorialStatePy.py :linenos: :language: python
1,017
reStructuredText
35.357142
120
0.725664
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial19/OgnTutorialExtendedTypesPy.py
""" Implementation of the Python node accessing attributes whose type is determined at runtime. This class exercises access to the DataModel through the generated database class for all simple data types. """ import omni.graph.core as og # Hardcode each of the expected types for easy comparison FLOAT_TYPE = og.Type(og.BaseDataType.FLOAT) TOKEN_TYPE = og.Type(og.BaseDataType.TOKEN) BOOL_ARRAY_TYPE = og.Type(og.BaseDataType.BOOL, array_depth=1) FLOAT_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, array_depth=1) FLOAT3_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3) INT2_TYPE = og.Type(og.BaseDataType.INT, tuple_count=2) FLOAT3_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1) class OgnTutorialExtendedTypesPy: """Exercise the runtime data types through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Implements the same algorithm as the C++ node OgnTutorialExtendedTypes.cpp. It follows the same code pattern for easier comparison, though in practice you would probably code Python nodes differently from C++ nodes to take advantage of the strengths of each language. """ def __compare_resolved_types(input_attribute, output_attribute) -> og.Type: """Returns the resolved type if they are the same, outputs a warning and returns None otherwise""" resolved_input_type = input_attribute.type resolved_output_type = output_attribute.type if resolved_input_type != resolved_output_type: db.log_warn(f"Resolved types do not match {resolved_input_type} -> {resolved_output_type}") return None return resolved_input_type if resolved_input_type.base_type != og.BaseDataType.UNKNOWN else None # --------------------------------------------------------------------------------------------------- def _compute_simple_values(): """Perform the first algorithm on the simple input data types""" # Unlike C++ code the Python types are flexible so you must check the data types to do the right thing. # This works out better when the operation is the same as you don't even have to check the data type. In # this case the "doubling" operation is slightly different for floats and tokens. resolved_type = __compare_resolved_types(db.inputs.floatOrToken, db.outputs.doubledResult) if resolved_type == FLOAT_TYPE: db.outputs.doubledResult.value = db.inputs.floatOrToken.value * 2.0 elif resolved_type == TOKEN_TYPE: db.outputs.doubledResult.value = db.inputs.floatOrToken.value + db.inputs.floatOrToken.value # A Pythonic way to do the same thing by just applying an operation and checking for compatibility is: # try: # db.outputs.doubledResult = db.inputs.floatOrToken * 2.0 # except TypeError: # # Gets in here for token types since multiplying string by float is not legal # db.outputs.doubledResult = db.inputs.floatOrToken + db.inputs.floatOrToken return True # --------------------------------------------------------------------------------------------------- def _compute_array_values(): """Perform the second algorithm on the array input data types""" resolved_type = __compare_resolved_types(db.inputs.toNegate, db.outputs.negatedResult) if resolved_type == BOOL_ARRAY_TYPE: db.outputs.negatedResult.value = [not value for value in db.inputs.toNegate.value] elif resolved_type == FLOAT_ARRAY_TYPE: db.outputs.negatedResult.value = [-value for value in db.inputs.toNegate.value] return True # --------------------------------------------------------------------------------------------------- def _compute_tuple_values(): """Perform the third algorithm on the 'any' data types""" resolved_type = __compare_resolved_types(db.inputs.tuple, db.outputs.tuple) # Notice how, since the operation is applied the same for both recognized types, the # same code can handle both of them. if resolved_type in (FLOAT3_TYPE, INT2_TYPE): db.outputs.tuple.value = tuple(-x for x in db.inputs.tuple.value) # An unresolved type is a temporary state and okay, resolving to unsupported types means the graph is in # an unsupported configuration that needs to be corrected. elif resolved_type is not None: type_name = resolved_type.get_type_name() db.log_error(f"Only float[3] and int[2] types are supported by this node, not {type_name}") return False return True # --------------------------------------------------------------------------------------------------- def _compute_flexible_values(): """Perform the fourth algorithm on the multi-shape data types""" resolved_type = __compare_resolved_types(db.inputs.flexible, db.outputs.flexible) if resolved_type == FLOAT3_ARRAY_TYPE: db.outputs.flexible.value = [(-x, -y, -z) for (x, y, z) in db.inputs.flexible.value] elif resolved_type == TOKEN_TYPE: db.outputs.flexible.value = db.inputs.flexible.value[::-1] return True # --------------------------------------------------------------------------------------------------- compute_success = _compute_simple_values() compute_success = _compute_array_values() and compute_success compute_success = _compute_tuple_values() and compute_success compute_success = _compute_flexible_values() and compute_success # --------------------------------------------------------------------------------------------------- # As Python has a much more flexible typing system it can do things in a few lines that require a lot # more in C++. One such example is the ability to add two arbitrary data types. Here is an example of # how, using "any" type inputs "a", and "b", with an "any" type output "result" you can generically # add two elements without explicitly checking the type, failing only when Python cannot support # the operation. # # try: # db.outputs.result = db.inputs.a + db.inputs.b # return True # except TypeError: # a_type = inputs.a.type().get_type_name() # b_type = inputs.b.type().get_type_name() # db.log_error(f"Cannot add attributes of type {a_type} and {b_type}") # return False return True @staticmethod def on_connection_type_resolve(node) -> None: # There are 4 sets of type-coupled attributes in this node, meaning that the base_type of the attributes # must be the same for the node to function as designed. # 1. floatOrToken <-> doubledResult # 2. toNegate <-> negatedResult # 3. tuple <-> tuple # 4. flexible <-> flexible # # The following code uses a helper function to resolve the attribute types of the coupled pairs. Note that # without this logic a chain of extended-attribute connections may result in a non-functional graph, due to # the requirement that types be resolved before graph evaluation, and the ambiguity of the graph without knowing # how the types are related. og.resolve_fully_coupled( [node.get_attribute("inputs:floatOrToken"), node.get_attribute("outputs:doubledResult")] ) og.resolve_fully_coupled([node.get_attribute("inputs:toNegate"), node.get_attribute("outputs:negatedResult")]) og.resolve_fully_coupled([node.get_attribute("inputs:tuple"), node.get_attribute("outputs:tuple")]) og.resolve_fully_coupled([node.get_attribute("inputs:flexible"), node.get_attribute("outputs:flexible")])
8,136
Python
55.506944
120
0.599435
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial19/OgnTutorialExtendedTypes.cpp
// Copyright (c) 2021, 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. // #include <OgnTutorialExtendedTypesDatabase.h> #include <algorithm> // // Attributes whose data types resolve at runtime ("any" or "union" types) are resolved by having connections made // to them of a resolved type. Say you have a chain of A->B->C where B has inputs and outputs of these types. The // connection from A->B will determine the type of data at B's input and the connection B->C will determine the type // of data at B's output (assuming A's outputs and C's inputs are well-defined types). // // For this reason it is the node's responsibility to verify the type resolution of the attributes as part of the // compute method. Any unresolved types (db.Xputs.attrName().resolved() == false) that are required by the compute // should result in a warning and compute failure. Any attributes resolved to incompatible types, for example an input // that resolves to a string where a number is needed, should also result in a warning and compute failure. // // It is up to the node to decide how flexible the resolution requirements are to be. In the string/number case above // the node may choose to parse the string as a number instead of failing, or using the length of the string as the // input number. The only requirement from OmniGraph is that the node handle all of the resolution types it has // claimed it will handle in the .ogn file. "any" attributes must handle all data types, even if some types result in // warnings or errors. "union" attributes must handle all types specified in the union. // class OgnTutorialExtendedTypes { public: static bool compute(OgnTutorialExtendedTypesDatabase& db) { bool computedOne = false; auto typeWarning = [&](const char* message, const Type& type1, const Type& type2) { db.logWarning("%s (%s -> %s)", message, getOgnTypeName(type1).c_str(), getOgnTypeName(type2).c_str()); }; auto typeError = [&](const char* message, const Type& type1, const Type& type2) { db.logError("%s (%s -> %s)", message, getOgnTypeName(type1).c_str(), getOgnTypeName(type2).c_str()); }; auto computeSimpleValues = [&]() { // ==================================================================================================== // Compute for the union types that resolve to simple values. // Accepted value types are floats and tokens. As these were the only types specified in the union definition // the node does not have to worry about other numeric types, such as int or double. // The node can decide what the meaning of an attempt to compute with unresolved types is. // For this particular node they are treated as silent success. const auto& floatOrToken = db.inputs.floatOrToken(); auto& doubledResult = db.outputs.doubledResult(); if (floatOrToken.resolved() && doubledResult.resolved()) { // Check for an exact type match for the input and output if (floatOrToken.type() != doubledResult.type()) { // Mismatched types are possible, and result in no compute typeWarning("Simple resolved types do not match", floatOrToken.type(), doubledResult.type()); return false; } // When extracting extended types the templated get<> method returns an object that contains the cast data. // It can be cast to a boolean for quick checks for matching types. // // Note: The single "=" in these if statements is intentional. It facilitates one-line set-and-test of the // typed values. // if (auto floatValue = floatOrToken.get<float>()) { // Once the existence of the cast type is verified it can be dereferenced to get at the raw data, // whose types are described in the tutorial on bundled data. if (auto doubledValue = doubledResult.get<float>()) { *doubledValue = *floatValue * 2.0f; } else { // This could be an assert because it should never happen. The types were confirmed above to match, // so they should have cast to the same types without incident. typeError("Simple types were matched as bool then failed to cast properly", floatOrToken.type(), doubledResult.type()); return false; } } else if (auto tokenValue = floatOrToken.get<OgnToken>()) { if (auto doubledValue = doubledResult.get<OgnToken>()) { std::string inputString{ db.tokenToString(*tokenValue) }; inputString += inputString; *doubledValue = db.stringToToken(inputString.c_str()); } else { // This could be an assert because it should never happen. The types were confirmed above to match, // so they should have cast to the same types without incident. typeError("Simple types were matched as token then failed to cast properly", floatOrToken.type(), doubledResult.type()); return false; } } else { // As Union types are supposed to restrict the data types being passed in to the declared types // any unrecognized types are an error, not a warning. typeError("Simple types resolved to unknown types", floatOrToken.type(), doubledResult.type()); return false; } } else { // Unresolved types are reasonable, resulting in no compute return true; } return true; }; auto computeArrayValues = [&]() { // ==================================================================================================== // Compute for the union types that resolve to arrays. // Accepted value types are arrays of bool or arrays of float, which are extracted as interfaces to // those values so that resizing can happen transparently through the fabric. // // These interfaces are similar to what you've seen in regular array attributes - they support resize(), // operator[], and range-based for loops. // const auto& toNegate = db.inputs.toNegate(); auto& negatedResult = db.outputs.negatedResult(); if (toNegate.resolved() && negatedResult.resolved()) { // Check for an exact type match for the input and output if (toNegate.type() != negatedResult.type()) { // Mismatched types are possible, and result in no compute typeWarning("Array resolved types do not match", toNegate.type(), negatedResult.type()); return false; } // Extended types can be any legal attribute type. Here the types in the extended attribute can be either // an array of booleans or an array of integers. if (auto boolArray = toNegate.get<bool[]>()) { auto valueAsBoolArray = negatedResult.get<bool[]>(); if (valueAsBoolArray) { valueAsBoolArray.resize( boolArray->size() ); size_t index{ 0 }; for (auto& value : *boolArray) { (*valueAsBoolArray)[index++] = ! value; } } else { // This could be an assert because it should never happen. The types were confirmed above to match, // so they should have cast to the same types without incident. typeError("Array types were matched as bool[] then failed to cast properly", toNegate.type(), negatedResult.type()); return false; } } else if (auto floatArray = toNegate.get<float[]>()) { auto valueAsFloatArray = negatedResult.get<float[]>(); if (valueAsFloatArray) { valueAsFloatArray.resize( floatArray->size() ); size_t index{ 0 }; for (auto& value : *floatArray) { (*valueAsFloatArray)[index++] = - value; } } else { // This could be an assert because it should never happen. The types were confirmed above to match, // so they should have cast to the same types without incident. typeError("Array types were matched as float[] then failed to cast properly", toNegate.type(), negatedResult.type()); return false; } } else { // As Union types are supposed to restrict the data types being passed in to the declared types // any unrecognized types are an error, not a warning. typeError("Array type not recognized", toNegate.type(), negatedResult.type()); return false; } } else { // Unresolved types are reasonable, resulting in no compute return true; } return true; }; auto computeTupleValues = [&]() { // ==================================================================================================== // Compute for the "any" types that only handle tuple values. In practice you'd only use "any" when the // type of data you handle is unrestricted. This is more an illustration to show how in practical use the // two types of attribute are accessed exactly the same way, the only difference is restrictions that the // OmniGraph system will put on potential connections. // // For simplicity this node will treat unrecognized type as a warning with success. // Full commentary and error checking is elided as it will be the same as for the above examples. // The algorithm for tuple values is a component-wise negation. const auto& tupleInput = db.inputs.tuple(); auto& tupleOutput = db.outputs.tuple(); if (tupleInput.resolved() && tupleOutput.resolved()) { if (tupleInput.type() != tupleOutput.type()) { typeWarning("Tuple resolved types do not match", tupleInput.type(), tupleOutput.type()); return false; } // This node will only recognize the float[3] and int[2] cases, to illustrate that tuple count and // base type are both flexible. if (auto float3Input = tupleInput.get<float[3]>()) { if (auto float3Output = tupleOutput.get<float[3]>()) { (*float3Output)[0] = -(*float3Input)[0]; (*float3Output)[1] = -(*float3Input)[1]; (*float3Output)[2] = -(*float3Input)[2]; } } else if (auto int2Input = tupleInput.get<int[2]>()) { if (auto int2Output = tupleOutput.get<int[2]>()) { (*int2Output)[0] = -(*int2Input)[0]; (*int2Output)[1] = -(*int2Input)[1]; } } else { // As "any" types are not restricted in their data types but this node is only handling two of // them an unrecognized type is just unimplemented code. typeWarning("Unimplemented type combination", tupleInput.type(), tupleOutput.type()); return true; } } else { // Unresolved types are reasonable, resulting in no compute return true; } return true; }; auto computeFlexibleValues = [&]() { // ==================================================================================================== // Complex union type that handles both simple values and an array of tuples. It illustrates how the // data types in a union do not have to be related in any way. // // Full commentary and error checking is elided as it will be the same as for the above examples. // The algorithm for tuple array values is to negate everything in the float3 array values, and to reverse // the string for string values. const auto& flexibleInput = db.inputs.flexible(); auto& flexibleOutput = db.outputs.flexible(); if (flexibleInput.resolved() && flexibleOutput.resolved()) { if (flexibleInput.type() != flexibleOutput.type()) { typeWarning("Flexible resolved types do not match", flexibleInput.type(), flexibleOutput.type()); return false; } // Arrays of tuples are handled with the same interface as with normal attributes. if (auto float3ArrayInput = flexibleInput.get<float[][3]>()) { if (auto float3ArrayOutput = flexibleOutput.get<float[][3]>()) { float3ArrayOutput.resize( float3ArrayInput.size() ); size_t index{ 0 }; for (auto& value : *float3ArrayInput) { (*float3ArrayOutput)[index][0] = - value[0]; (*float3ArrayOutput)[index][1] = - value[1]; (*float3ArrayOutput)[index][2] = - value[2]; index++; } } } else if (auto tokenInput = flexibleInput.get<OgnToken>()) { if (auto tokenOutput = flexibleOutput.get<OgnToken>()) { std::string toReverse{ db.tokenToString(*tokenInput) }; std::reverse( toReverse.begin(), toReverse.end() ); *tokenOutput = db.stringToToken(toReverse.c_str()); } } else { typeError("Unrecognized type combination", flexibleInput.type(), flexibleOutput.type()); return false; } } else { // Unresolved types are reasonable, resulting in no compute return true; } return true; }; // This approach lets either section fail while still computing the other. computedOne = computeSimpleValues(); computedOne = computeArrayValues() || computedOne; computedOne = computeTupleValues() || computedOne; computedOne = computeFlexibleValues() || computedOne; if (! computedOne) { db.logWarning("None of the inputs had resolved type, resulting in no compute"); } return ! computedOne; } static void onConnectionTypeResolve(const NodeObj& nodeObj) { // The attribute types resolve in pairs AttributeObj pairs[][2] { { nodeObj.iNode->getAttributeByToken(nodeObj, inputs::floatOrToken.token()), nodeObj.iNode->getAttributeByToken(nodeObj, outputs::doubledResult.token()) }, { nodeObj.iNode->getAttributeByToken(nodeObj, inputs::toNegate.token()), nodeObj.iNode->getAttributeByToken(nodeObj, outputs::negatedResult.token()) }, { nodeObj.iNode->getAttributeByToken(nodeObj, inputs::tuple.token()), nodeObj.iNode->getAttributeByToken(nodeObj, outputs::tuple.token()) }, { nodeObj.iNode->getAttributeByToken(nodeObj, inputs::flexible.token()), nodeObj.iNode->getAttributeByToken(nodeObj, outputs::flexible.token()) } }; for (auto& pair : pairs) { nodeObj.iNode->resolveCoupledAttributes(nodeObj, &pair[0], 2); } } }; REGISTER_OGN_NODE()
17,881
C++
49.230337
144
0.523125
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial19/tutorial19.rst
.. _ogn_tutorial_extended_types: Tutorial 19 - Extended Attribute Types ====================================== Extended attribute types are so-named because they extend the types of data an attribute can accept from one type to several types. Extended attributes come in two flavours. The _any_ type is the most flexible. It allows a connection with any other attribute type: .. code-block:: json :emphasize-lines: 4 "inputs": { "myAnyAttribute": { "description": "Accepts an incoming connection from any type of attribute", "type": "any", } } The union type, represented as an array of type names, allows a connection from a limited subset of attribute types. Here's one that can connect to attributes of type _float[3]_ and _double[3]_: .. code-block:: json :emphasize-lines: 4 "inputs": { "myUnionAttribute": { "description": "Accepts an incoming connection from attributes with a vector of a 3-tuple of numbers", "type": ["float[3]", "double[3]"], } } .. note:: "union" is not an actual type name, as the type names are specified by a list. It is just the nomenclature used for the set of all attributes that can be specified in this way. More details about union types can be found in :ref:`ogn_attribute_types`. As you will see in the code examples, the value extracted from the database for such attributes has to be checked for the actual resolved data type. Until an extended attribute is connected its data type will be unresolved and it will not have a value. For this reason _"default"_ values are not allowed on extended attributes. OgnTutorialExtendedTypes.ogn ---------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.ExtendedTypes", which has inputs and outputs with the extended attribute types. .. literalinclude:: OgnTutorialExtendedTypes.ogn :linenos: :language: json OgnTutorialExtendedTypes.cpp ---------------------------- The *cpp* file contains the implementation of the compute method. It illustrates how to determine and set the data types on extended attribute types. .. literalinclude:: OgnTutorialExtendedTypes.cpp :linenos: :language: c++ Information on the raw types extracted from the extended type values can be seen in :ref:`ogn_tutorial_bundle_data`. OgnTutorialExtendedTypesPy.py ----------------------------- This is a Python version of the above C++ node with exactly the same set of attributes and the same algorithm. It shows the parallels between manipulating extended attribute types in both languages. (The .ogn file is omitted for brevity, being identical to the previous one save for the addition of a ``"language": "python"`` property. .. literalinclude:: OgnTutorialExtendedTypesPy.py :linenos: :language: python
2,868
reStructuredText
38.301369
122
0.702232
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial23/tutorial23.rst
.. _ogn_tutorial_cpu_gpu_extended: Tutorial 23 - Extended Attributes On The GPU ============================================ Extended attributes are no different from other types of attributes with respect to where their memory will be located. The difference is that there is a slightly different API for accessing their data, illustrating by these examples. This node also illustrates the new concept of having a node create an ABI function override that handles the runtime type resolution of extended attribute types. In this case when any of the two input attributes or one output attribute become resolved then the other two attributes are resolved to the same type, if possible. OgnTutorialCpuGpuExtended.ogn ----------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CpuGpuExtended" with an input **'any'** attribute on the CPU, an input **'any'** attribute on the GPU, and an output whose memory location is decided at runtime by a boolean. .. literalinclude:: OgnTutorialCpuGpuExtended.ogn :linenos: :language: json OgnTutorialCpuGpuExtended.cpp ----------------------------- The *cpp* file contains the implementation of the compute method. It sums two inputs on either the CPU or GPU based on the input boolean. For simplicity only the **float[3][]** attribute type is processed, with all others resulting in a compute failure. .. literalinclude:: OgnTutorialCpuGpuExtended.cpp :linenos: :language: c++ OgnTutorialCpuGpuExtendedPy.py ------------------------------ The *py* file contains the same algorithm as the C++ node, with the node implementation language being different. .. literalinclude:: OgnTutorialCpuGpuExtendedPy.py :linenos: :language: python
1,752
reStructuredText
42.824999
120
0.726027
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial23/OgnTutorialCpuGpuExtended.cpp
// Copyright (c) 2021, 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. // #include <OgnTutorialCpuGpuExtendedDatabase.h> extern "C" void cpuGpuSumCPU(float const(*p1)[3], float const(*p2)[3], float(*sums)[3], size_t); extern "C" void cpuGpuSumGPU(float const (**p1)[3], float const (**p2)[3], float(**sums)[3]); namespace omni { namespace graph { namespace tutorials { // Only the pointf[3][] type is accepted. Make a shortcut to the type information describing it for comparison core::Type acceptedType(core::BaseDataType::eFloat, 3, 1, core::AttributeRole::ePosition); // Template for reporting type inconsistencies. The data types are different for the attributes but the checks are // the same so this avoids duplication template <typename P1, typename P2, typename P3> bool verifyDataTypes(OgnTutorialCpuGpuExtendedDatabase& db, const P1& points1, const P2& points2, P3& sums, const char* type) { if (! points1) { db.logWarning("Skipping compute - The %s attribute was not a valid pointf[3][]", type); } else if (! points2) { db.logWarning("Skipping compute - The %s attribute was not a valid pointf[3][]", type); } else if (! sums) { db.logWarning("Skipping compute - The %s output attribute was not a valid pointf[3][]", type); } else if (points1.size() != points2.size()) { db.logWarning("Skipping compute - Point arrays are different sizes (%zu and %zu)", points1.size(), points2.size()); } else { sums.resize(points1.size()); return true; } return false; } class OgnTutorialCpuGpuExtended { bool m_allAttributesResolved{ false }; public: static bool compute(OgnTutorialCpuGpuExtendedDatabase& db) { if (! db.sharedState<OgnTutorialCpuGpuExtended>().m_allAttributesResolved) { db.logWarning("All types are not yet resolved. Cannot run the compute."); return false; } const auto& gpu = db.inputs.gpu(); const auto cpuData = db.inputs.cpuData(); const auto gpuData = db.inputs.gpuData(); auto cpuGpuSum = db.outputs.cpuGpuSum(); if ((cpuData.type() != acceptedType) || (gpuData.type() != acceptedType) || (cpuGpuSum.type() != acceptedType)) { db.logWarning("Skipping compute - All of the attributes do not have the accepted resolved type pointf[3][]"); return false; } if (gpu) { // Computation on the GPU has been requested so get the GPU versions of the attribute data const auto points1 = cpuData.getGpu<float[][3]>(); const auto points2 = gpuData.get<float[][3]>(); auto sums = cpuGpuSum.getGpu<float[][3]>(); if (!verifyDataTypes(db, points1, points2, sums, "GPU")) { return false; } cpuGpuSumGPU(points1(), points2(), sums()); } else { // Computation on the CPU has been requested so get the CPU versions of the attribute data const auto points1 = cpuData.get<float[][3]>(); const auto points2 = gpuData.getCpu<float[][3]>(); auto sums = cpuGpuSum.getCpu<float[][3]>(); if (!verifyDataTypes(db, points1, points2, sums, "CPU")) { return false; } cpuGpuSumCPU(points1->data(), points2->data(), sums->data(), points1.size()); } return true; } static void onConnectionTypeResolve(const NodeObj& nodeObj) { // If any one type is resolved the others should resolve to the same type. Calling this helper function // makes that happen automatically. If it returns false then the resolution failed for some reason. The // node's user data, which is just a copy of this class, is used to keep track of the resolution state so // that the compute method can quickly exit when the types are not resolved. AttributeObj attributes[3] { nodeObj.iNode->getAttributeByToken(nodeObj, inputs::cpuData.token()), nodeObj.iNode->getAttributeByToken(nodeObj, inputs::gpuData.token()), nodeObj.iNode->getAttributeByToken(nodeObj, outputs::cpuGpuSum.token()) }; auto& state = OgnTutorialCpuGpuExtendedDatabase::sInternalState<OgnTutorialCpuGpuExtended>(nodeObj); state.m_allAttributesResolved = nodeObj.iNode->resolveCoupledAttributes(nodeObj, attributes, 3); } }; REGISTER_OGN_NODE() } // namespace tutorials } // namespace graph } // namespace omni
4,959
C++
40.333333
125
0.647308
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial23/OgnTutorialCpuGpuExtendedPy.py
""" Implementation of the Python node accessing extended attributes whose memory location is determined at runtime. """ import omni.graph.core as og # Only one type of data is handled by the compute - pointf[3][] POINT_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1, role=og.AttributeRole.POSITION) class OgnTutorialCpuGpuExtendedPy: """Exercise GPU access for extended attributes through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Implements the same algorithm as the C++ node OgnTutorialCpuGpuExtended.cpp. It follows the same code pattern for easier comparison, though in practice you would probably code Python nodes differently from C++ nodes to take advantage of the strengths of each language. """ # Find and verify the attributes containing the points if db.attributes.inputs.cpuData.get_resolved_type() != POINT_ARRAY_TYPE: db.log_warning("Skipping compute - CPU attribute type did not resolve to pointf[3][]") return False if db.attributes.inputs.gpuData.get_resolved_type() != POINT_ARRAY_TYPE: db.log_warning("Skipping compute - GPU attribute type did not resolve to pointf[3][]") return False if db.attributes.outputs.cpuGpuSum.get_resolved_type() != POINT_ARRAY_TYPE: db.log_warning("Skipping compute - Sum attribute type did not resolve to pointf[3][]") return False # Put accessors into local variables for convenience gpu_data = db.inputs.gpuData cpu_data = db.inputs.cpuData sums = db.outputs.cpuGpuSum # Mismatched sizes cannot be computed if gpu_data.size != cpu_data.size: db.log_warning(f"Skipping compute - Point arrays are different sizes ({gpu_data.size} and {cpu_data.size})") # Set the size to what is required for the dot product calculation sums.size = cpu_data.size # Use the correct data access based on whether the output is supposed to be on the GPU or not if db.inputs.gpu: # The second line is how the values would be extracted if Python supported GPU data extraction. # When it does this tutorial will be updated sums.cpu_value = cpu_data.value + gpu_data.cpu_value # sums.gpu_value = cpu_data.gpu_value + gpu_data.value else: sums.cpu_value = cpu_data.value + gpu_data.cpu_value return True @staticmethod def on_connection_type_resolve(node: og.Node) -> None: """Whenever any of the inputs or the output get a resolved type the others should get the same resolution""" attribs = [ node.get_attribute("inputs:cpuData"), node.get_attribute("inputs:gpuData"), node.get_attribute("outputs:cpuGpuSum"), ] og.resolve_fully_coupled(attribs)
2,925
Python
46.193548
120
0.666667
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial22/OgnTutorialCpuGpuBundlesPy.py
""" Implementation of the Python node accessing attributes whose memory location is determined at runtime. """ import numpy as np import omni.graph.core as og # Types to check on bundled attributes FLOAT_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, array_depth=1) FLOAT3_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1, role=og.AttributeRole.POSITION) class OgnTutorialCpuGpuBundlesPy: """Exercise bundle members through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Implements the same algorithm as the C++ node OgnTutorialCpuGpuBundles.cpp. It follows the same code pattern for easier comparison, though in practice you would probably code Python nodes differently from C++ nodes to take advantage of the strengths of each language. """ if db.inputs.gpu: # Invalid data yields no compute if not db.inputs.gpuBundle.valid: return True db.outputs.cpuGpuBundle = db.inputs.gpuBundle else: if not db.inputs.cpuBundle.valid: return True db.outputs.cpuGpuBundle = db.inputs.cpuBundle # Find and verify the attributes containing the points cpu_points = db.inputs.cpuBundle.attribute_by_name(db.tokens.points) if cpu_points.type != FLOAT3_ARRAY_TYPE: db.log_warning( f"Skipping compute - No valid float[3][] attribute named '{db.tokens.points}' on the CPU bundle" ) return False gpu_points = db.inputs.gpuBundle.attribute_by_name(db.tokens.points) if gpu_points.type != FLOAT3_ARRAY_TYPE: db.log_warning( f"Skipping compute - No valid float[3][] attribute named '{db.tokens.points}' on the GPU bundle" ) return False # If the attribute is not already on the output bundle then add it dot_product = db.outputs.cpuGpuBundle.attribute_by_name(db.tokens.dotProducts) if dot_product is None: dot_product = db.outputs.cpuGpuBundle.insert((og.Type(og.BaseDataType.FLOAT, array_depth=1), "dotProducts")) elif dot_product.type != FLOAT_ARRAY_TYPE: # Python types do not use a cast to find out if they are the correct type so explicitly check it instead db.log_warning( f"Skipping compute - No valid float[] attribute named '{db.tokens.dotProducts}' on the output bundle" ) return False # Set the size to what is required for the dot product calculation dot_product.size = cpu_points.size # Use the correct data access based on whether the output is supposed to be on the GPU or not if db.inputs.gpu: # The second line is how the values would be extracted if Python supported GPU data extraction. # When it does this tutorial will be updated dot_product.cpu_value = np.einsum("ij,ij->i", cpu_points.value, gpu_points.cpu_value) # dot_product.gpu_value = np.einsum("ij,ij->i", cpu_points.gpu_value, gpu_points.value) else: dot_product.cpu_value = np.einsum("ij,ij->i", cpu_points.value, gpu_points.cpu_value) return True
3,273
Python
45.771428
120
0.651085
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial22/OgnTutorialCpuGpuBundles.cpp
// Copyright (c) 2021, 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. // #include <OgnTutorialCpuGpuBundlesDatabase.h> extern "C" void cpuGpuDotProductCPU(float const(*p1)[3], float const(*p2)[3], float*, size_t); extern "C" void cpuGpuDotProductGPU(float const (**p1)[3], float const (**p2)[3], float**, size_t); namespace omni { namespace graph { namespace tutorials { class OgnTutorialCpuGpuBundles { public: static bool compute(OgnTutorialCpuGpuBundlesDatabase& db) { const auto& gpu = db.inputs.gpu(); // Bundles are merely abstract representations of a collection of attributes so you don't have to do anything // different when they are marked for GPU, or ANY memory location. const auto& cpuBundle = db.inputs.cpuBundle(); const auto& gpuBundle = db.inputs.gpuBundle(); auto& outputBundle = db.outputs.cpuGpuBundle(); // Assign the correct destination bundle to the output based on the gpu flag if (gpu) { outputBundle = gpuBundle; } else { outputBundle = cpuBundle; } // Get the attribute references. They're the same whether the bundles are on the CPU or GPU const auto pointsCpuAttribute = cpuBundle.attributeByName(db.tokens.points); const auto pointsGpuAttribute = gpuBundle.attributeByName(db.tokens.points); auto dotProductAttribute = outputBundle.attributeByName(db.tokens.dotProducts); if (! dotProductAttribute.isValid()) { dotProductAttribute = outputBundle.addAttribute(db.tokens.dotProducts, Type(BaseDataType::eFloat, 1, 1)); } // Find the bundle contents to be processed if (gpu) { const auto points1 = pointsCpuAttribute.getGpu<float[][3]>(); const auto points2 = pointsGpuAttribute.get<float[][3]>(); auto dotProducts = dotProductAttribute.getGpu<float[]>(); if (! points1) { db.logWarning("Skipping compute - No valid float[3][] attribute named '%s' on the CPU bundle", db.tokenToString(db.tokens.points)); return false; } if (! points2) { db.logWarning("Skipping compute - No valid float[3][] attribute named '%s' on the GPU bundle", db.tokenToString(db.tokens.points)); return false; } if (points1.size() != points2.size()) { db.logWarning("Skipping compute - Point arrays are different sizes (%zu and %zu)", points1.size(), points2.size()); return false; } dotProducts.resize(points1.size()); if (! dotProducts) { db.logWarning("Skipping compute - No valid float[] attribute named '%s' on the output bundle", db.tokenToString(db.tokens.dotProducts)); return false; } cpuGpuDotProductGPU(points1(), points2(), dotProducts(), points1.size()); } else { const auto points1 = pointsCpuAttribute.get<float[][3]>(); const auto points2 = pointsGpuAttribute.getCpu<float[][3]>(); auto dotProducts = dotProductAttribute.getCpu<float[]>(); if (! points1) { db.logWarning("Skipping compute - No valid float[3][] attribute named '%s' on the CPU bundle", db.tokenToString(db.tokens.points)); return false; } if (! points2) { db.logWarning("Skipping compute - No valid float[3][] attribute named '%s' on the GPU bundle", db.tokenToString(db.tokens.points)); return false; } if (points1.size() != points2.size()) { db.logWarning("Skipping compute - Point arrays are different sizes (%zu and %zu)", points1.size(), points2.size()); return false; } dotProducts.resize(points1.size()); if (! dotProducts) { db.logWarning("Skipping compute - No valid dot product attribute on the output bundle"); return false; } cpuGpuDotProductCPU(points1->data(), points2->data(), dotProducts->data(), points1.size()); } return true; } }; REGISTER_OGN_NODE() } // namespace tutorials } // namespace graph } // namespace omni
4,825
C++
41.333333
152
0.602487
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial22/tutorial22.rst
.. _ogn_tutorial_cpu_gpu_bundles: Tutorial 22 - Bundles On The GPU ================================ Bundles are not exactly data themselves, they are a representation of a collection of attributes whose composition is determined at runtime. As such, they will always live on the CPU. However the attributes they are encapsulating have the same flexibility as other attributes to live on the CPU, GPU, or have their location decided at runtime. For that reason it's convenient to use the same "cpu", "cuda", and "any" memory types for the bundle attributes, with a slightly different interpretation. - **cpu** all attributes in the bundle will be on the CPU - **gpu** all attributes in the bundle will be on the GPU - **any** either some attributes in the bundle are on the CPU and some are on the GPU, or that decision will be made at runtime For example if you had a bundle of attributes consisting of a large array of points and a boolean that controls the type of operation you will perform on them it makes sense to leave the boolean on the CPU and move the points to the GPU for more efficient processing. OgnTutorialCpuGpuBundles.ogn ---------------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CpuGpuBundles" with an input bundle on the CPU, an input bundle on the GPU, and an output bundle whose memory location is decided at runtime by a boolean. .. literalinclude:: OgnTutorialCpuGpuBundles.ogn :linenos: :language: json OgnTutorialCpuGpuBundles.cpp ---------------------------------- The *cpp* file contains the implementation of the compute method. It creates a merged bundle in either the CPU or GPU based on the input boolean and runs an algorithm on the output location. .. literalinclude:: OgnTutorialCpuGpuBundles.cpp :linenos: :language: c++ OgnTutorialCpuGpuBundlesPy.py ----------------------------------- The *py* file contains the same algorithm as the C++ node, with the node implementation language being different. .. literalinclude:: OgnTutorialCpuGpuBundlesPy.py :linenos: :language: python
2,106
reStructuredText
43.829786
127
0.728395
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial16/OgnTutorialBundleDataPy.py
""" Implementation of the Python node accessing attributes through the bundle in which they are contained. """ import numpy as np import omni.graph.core as og # Types recognized by the integer filter _INTEGER_TYPES = [og.BaseDataType.INT, og.BaseDataType.UINT, og.BaseDataType.INT64, og.BaseDataType.UINT64] class OgnTutorialBundleDataPy: """Exercise the bundled data types through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Implements the same algorithm as the C++ node OgnTutorialBundleData.cpp As Python is so much more flexible it doubles values on any attribute type that can handle it, unlike the C++ node which only operates on integer types """ input_bundle = db.inputs.bundle output_bundle = db.outputs.bundle # This does a copy of the full bundle contents from the input bundle to the output bundle so that the # output data can be modified directly. output_bundle.bundle = input_bundle # The "attributes" member is a list that can be iterated. The members of the list do not contain real # og.Attribute objects, which must always exist, they are wrappers on og.AttributeData objects, which can # come and go at runtime. for bundled_attribute in output_bundle.attributes: attribute_type = bundled_attribute.type # Only integer types are recognized for this node's operation (doubling all integral values). # It does operate on tuples and arrays though so that part does not need to be set. # if attribute_type.base_type not in _INTEGER_TYPES: # continue # This operation does the right thing on all compatible types, unlike the C++ equivalent where it # requires special handling for each variation of the data types it can handle. if attribute_type.base_type == og.BaseDataType.TOKEN: if attribute_type.array_depth > 0: bundled_attribute.value = [f"{element}{element}" for element in bundled_attribute.value] else: bundled_attribute.value = f"{bundled_attribute.value}{bundled_attribute.value}" elif attribute_type.role in [og.AttributeRole.TEXT, og.AttributeRole.PATH]: bundled_attribute.value = f"{bundled_attribute.value}{bundled_attribute.value}" else: try: bundled_attribute.value = np.multiply(bundled_attribute.value, 2) except TypeError: db.log_error(f"This node does not handle data of type {attribute_type.get_type_name()}") return True
2,702
Python
48.145454
113
0.663583
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial16/tutorial16.rst
.. _ogn_tutorial_bundle_data: Tutorial 16 - Bundle Data ========================= Attribute bundles are a construct that packages up groups of attributes into a single entity that can be passed around the graph. These attributes have all of the same properties as a regular attribute, you just have to go through an extra step to access their values. This node illustrates how to break open a bundle to access and modify values in the bundled attributes. OgnTutorialBundleData.ogn ------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.BundleData", which has one input bundle and one output bundle. .. literalinclude:: OgnTutorialBundleData.ogn :linenos: :language: json OgnTutorialBundleData.cpp ------------------------- The *cpp* file contains the implementation of the compute method. It accesses any attributes in the bundle that have integral base types and doubles the values of those attributes. .. literalinclude:: OgnTutorialBundleData.cpp :linenos: :language: c++ Bundled Attribute Data Manipulation Methods ------------------------------------------- These are the methods for accessing the data that the bundled attributes encapsulate. In regular attributes the code generated from the .ogn file provides accessors with predetermined data types. The data types of attributes within bundles are unknown until compute time so it is up to the node writer to explicitly cast to the correct data type. Extracting Bundled Attribute Data - Simple Types ++++++++++++++++++++++++++++++++++++++++++++++++ For reference, simple types, tuple types, array types, tuple array types, and role types are all described in :ref:`ogn_attribute_types`. However, unlike normal attributes the bundled attributes are always accessed as their raw native data types. For example instead of ``pxr::GfVec3f`` you will access with ``float[3]``, which can always be cast to the explicit types if desired. .. note:: One exception to the type casting is tokens. In normal attributes you retrieve tokens as ``NameToken``. Due to certain compiler restrictions the bundled attributes will be retrieved as the helper type ``OgnToken``, which is castable to ``NameToken`` for subsequent use. .. code-block:: cpp :emphasize-lines: 5 // As the attribute data types are only known at runtime you must perform a type-specific cast // to get the data out in its native form. const auto& inputBundle = db.inputs.bundle(); // Note the "const" here, to ensure we are not inadvertently modifying the input data. const auto weight = inputBundle.attributeByName(weightToken); const float* weightValue = weight.value<float>(); // nullptr return means the data is not of the requested type asssert( nullptr == weight.value<int>() ); Extracting Bundled Attribute Data - Tuple Types +++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: cpp :emphasize-lines: 4 // The tuple data types can be accessed in exactly the same way as simple data types, with the proper cast. const auto& inputBundle = db.inputs.bundle(); const auto weight3 = inputBundle.attributeByName(weight3Token); const auto weight3Value = weight3.value<float[3]>(); // type of weight3Value == const float[3]* // If you have a preferred library for manipulating complex types you can cast to them if they are compatible. static_assert( std::is_convertible(pxr::GfVec3f, float[3]) ); const pxr::GfVec3f* usdWeight = reinterpret_cast<const pxr::GfVec3f*>(weight3Value); Extracting Bundled Attribute Data - Array Types +++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: cpp :emphasize-lines: 4,11 // As with tuple types, the array types are extracted directly with the native array cast const auto& inputBundle = db.inputs.bundle(); const auto weights = inputBundle.attributeByName(weightsToken); const auto weightsValue = weights.value<float[]>(); // type == const float[]* auto& outputBundle = db.outputs.bundle(); // As this is an output, the const is omitted so that the data can be modified auto nWeights = outputBundle.attributeByName(nWeightsToken); // As with regular attributes, bundled array outputs must be resized to allocate space before filling them. // These array types also have the normal array capabilities, with a size() method and range-based for loops. nWeights.resize( weights.size() ); size_t index = 0; for (const auto& weightValue : *weightsValue) { nWeights[index++] = weightValue / 256.0f; } Extracting Bundled Attribute Data - Tuple Array Types +++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: cpp :emphasize-lines: 4 // Tuple-arrays behave as you would expect, using the native tuple-array as the cast type const auto& inputBundle = db.inputs.bundle(); const auto weights3 = inputBundle.attributeByName(weights3Token); const auto weights3Value = weights.value<float[][3]>(); // type == const float[][3]* OgnTutorialBundleDataPy.py -------------------------- This is a Python version of the above C++ node with exactly the same set of attributes and a similar algorithm. The main difference is that for the Python version the type definitions are much more flexible so the algorithm can be applied to every type of bundled attribute with minimal code. (The .ogn file is omitted for brevity, being identical to the previous one save for the addition of a ``"language": "python"`` property.) .. literalinclude:: OgnTutorialBundleDataPy.py :linenos: :language: python
5,639
reStructuredText
45.229508
125
0.700656
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial16/OgnTutorialBundleData.cpp
// Copyright (c) 2021, 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. // #include <OgnTutorialBundleDataDatabase.h> using omni::graph::core::Type; using omni::graph::core::NameToken; using omni::graph::core::BaseDataType; namespace { // The function of this node is to double the values for all bundled attributes // with integral types, including tuples and arrays. // // The parameter is a ogn::RuntimeAttribute<kOgnOutput, ogn::kCpu>, which is the type of data returned when iterating // over an output bundle on the CPU. // It contains a description of the attribute within the bundle and access to the attribute's data. // BundledInput is a similar type, which is what you get when iterating over an input bundle. The main difference // between the two is the ability to modify the attribute or its data. template <typename POD> bool doubleSimple(ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& bundledAttribute) { // When an attribute is cast to the wrong type (e.g. an integer attribute is extracted with a float // template parameter on the get<,>() method) a nullptr is returned. That can be used to determine // the attribute type. You can also use the bundledAttribute.type() method to access the full type // information and select a code path using that. auto podValue = bundledAttribute.get<POD>(); if (podValue) { *podValue *= 2; return true; } return false; }; // Array and tuple data has iterator capabilities for easy access to individual elements template <typename CppType> bool doubleArray(ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& bundledAttribute) { // Strings and paths look like uint8_t[] but are not, so don't process them if ((bundledAttribute.type().role == AttributeRole::eText) || (bundledAttribute.type().role == AttributeRole::ePath)) { return false; } auto arrayValue = bundledAttribute.get<CppType>(); if (arrayValue) { for (auto& arrayElement : *arrayValue) { arrayElement *= 2; } return true; } return false; }; // Tuple arrays must have nested iteration template <typename CppType> bool doubleTupleArray(ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& bundledAttribute) { auto tupleSize = bundledAttribute.type().componentCount; auto tupleArrayValue = bundledAttribute.get<CppType>(); if (tupleArrayValue) { for (auto& arrayElement : *tupleArrayValue) { for (size_t i=0; i<tupleSize; ++i) { arrayElement[i] *= 2; } } return true; } return false; }; } class OgnTutorialBundleData { public: static bool compute(OgnTutorialBundleDataDatabase& db) { // Bundle attributes are extracted from the database in the same way as any other attribute. // The only difference is that a different interface class is provided, suited to bundle manipulation. const auto& inputBundle = db.inputs.bundle(); auto& outputBundle = db.outputs.bundle(); for (const auto& bundledAttribute : inputBundle) { auto podValue = bundledAttribute.get<int>(); } // Copying the entire bundle is more efficient than adding one member at a time. As the output bundle // will have the same attributes as the input, even though the values will be different, this is the best // approach. If the attribute lists were different then you would copy or create the individual attributes // as required. outputBundle = inputBundle; // Now walk the bundle to look for types to be modified for (auto& bundledAttribute : outputBundle) { // This shows how using a templated function can simplify handling of several different bundled // attribute types. The data types for each of the POD attributes is fully explained in the documentation // page titled "Attribute Data Types". The list of available POD data types is: // // bool // double // float // pxr::GfHalf // int // int64_t // NameToken // uint8_t // uint32_t // uint64_t // if (doubleSimple<int>(bundledAttribute)) continue; if (doubleSimple<int64_t>(bundledAttribute)) continue; if (doubleSimple<uint8_t>(bundledAttribute)) continue; if (doubleSimple<uint32_t>(bundledAttribute)) continue; if (doubleSimple<uint64_t>(bundledAttribute)) continue; // Plain ints are the only integral types supporting tuples. Double those here if (doubleArray<int[2]>(bundledAttribute)) continue; if (doubleArray<int[3]>(bundledAttribute)) continue; if (doubleArray<int[4]>(bundledAttribute)) continue; // Arrays are looped differently than tupls so they are also handled differently if (doubleArray<int[]>(bundledAttribute)) continue; if (doubleArray<int64_t[]>(bundledAttribute)) continue; if (doubleArray<uint8_t[]>(bundledAttribute)) continue; if (doubleArray<uint32_t[]>(bundledAttribute)) continue; if (doubleArray<uint64_t[]>(bundledAttribute)) continue; // Tuple arrays require a two level iteration if (doubleTupleArray<int[][2]>(bundledAttribute)) continue; if (doubleTupleArray<int[][3]>(bundledAttribute)) continue; if (doubleTupleArray<int[][4]>(bundledAttribute)) continue; // Any attributes not passing the above tests are not integral and therefore not handled by this node. } return true; } }; REGISTER_OGN_NODE()
6,228
C++
40.251655
121
0.657354
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial9/OgnTutorialCpuGpuData.cpp
// Copyright (c) 2020, 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. // #include <OgnTutorialCpuGpuDataDatabase.h> // This helper file keeps the GPU and CPU functions organized for easy access. // It's only for illustration purposes; you can choose to organize your functions any way you wish. // The first algorithm is a simple add, to illustrate passing non-array types. extern "C" void cpuGpuAddCPU(outputs::sum_t_cpu, inputs::a_t_cpu, inputs::b_t_cpu, size_t); extern "C" void cpuGpuAddGPU(outputs::sum_t_gpu, inputs::a_t_gpu, inputs::b_t_gpu); // The second algorithm shows the more common case of accessing array data. extern "C" void cpuGpuMultiplierCPU(outputs::points_t_gpu, inputs::multiplier_t_gpu, inputs::points_t_gpu, size_t); extern "C" void cpuGpuMultiplierGPU(outputs::points_t_gpu, inputs::multiplier_t_gpu, inputs::points_t_gpu, size_t); class OgnTutorialCpuGpuData { public: static bool compute(OgnTutorialCpuGpuDataDatabase& db) { // Computing the size of the output is independent of CPU/GPU as the size update is lazy and will happen // when the data is requested from the fabric. size_t numberOfPoints = db.inputs.points.size(); db.outputs.points.resize(numberOfPoints); // Use the runtime input to determine where the calculation should take place. // // Another helpful use of this technique is to first measure the size of data being evaluated and // if it meets a certain minimum threshold move the calculation to the GPU. if (db.inputs.is_gpu()) { cpuGpuAddGPU(db.outputs.sum.gpu(), db.inputs.a.gpu(), db.inputs.b.gpu()); // GPU data is just raw pointers so the size must be passed down to the algorithm cpuGpuMultiplierGPU( db.outputs.points.gpu(), db.inputs.multiplier.gpu(), db.inputs.points.gpu(), numberOfPoints); } else { // CPU version calls the shared CPU/GPU algorithm directly. This could also be implemented in the // CUDA file as an extern "C" function but it is so simple that this is easier. cpuGpuAddCPU(db.outputs.sum.cpu(), db.inputs.a.cpu(), db.inputs.b.cpu(), 0); // Extract the CPU data and iterate over all of the points, calling the shared deformation algorithm. // The data is passed through as raw CUDA-compatible bytes so that the deformation algorithm can live // all in one file. If the code were all on the CPU side then the data types could be used as regular // arrays, as showing in the tutorial on array data types. auto rawOutputPoints = db.outputs.points.cpu().data(); auto rawInputPoints = db.inputs.points.cpu().data(); cpuGpuMultiplierCPU(&rawOutputPoints, &db.inputs.multiplier.cpu(), &rawInputPoints, numberOfPoints); } return true; } }; REGISTER_OGN_NODE()
3,302
C++
50.609374
115
0.694428
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial9/tutorial9.rst
.. _ogn_tutorial_cpuGpuData: Tutorial 9 - Runtime CPU/GPU Decision ===================================== The CPU/GPU data node creates various attributes for use in a CUDA-based GPU compute or a CPU-based compute, where the decision of which to use is made at runtime rather than compile time. A few representative types are used, though the list of potential attribute types is not exhaustive. See :ref:`ogn_attribute_types` for the full list. OgnTutorialCpuGpuData.ogn ------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CpuGpuData", which has attributes whose memory type is determined at runtime by the input named *isGPU*. The algorithm of the node is implemented in CUDA, but in such a way that it can run on either the CPU or the GPU, depending on where the attribute data lives. .. literalinclude:: OgnTutorialCpuGpuData.ogn :linenos: :language: json OgnTutorialCpuGpuData.cpp ------------------------- The *cpp* file contains the implementation of the compute method, which checks the value of the *isGPU* attribute and then extracts the data of the specified type to pass to the algorithm in the .cu file. .. literalinclude:: OgnTutorialCpuGpuData.cpp :linenos: :language: c++ OgnTutorialCpuGpuData_CUDA.cu ----------------------------- The *cu* file contains the implementation of the deformation on the CPU and GPU using CUDA. .. literalinclude:: OgnTutorialCpuGpuData_CUDA.cu :linenos: :language: c++ CPU/GPU Attribute Access ------------------------ Here is how the attribute values are returned from the database. Up until now the attribute name has sufficed as the database member that accesses the value through its *operator()*. The addition of the runtime switch of memory locations is facilitated by the addition of the *gpu()* and *cpu()* members. +-------------------------+----------------+-------------------------+-----------------+----------------+ | CPU Function | CPU Type | GPU Function | GPU Type | CUDA Type | +=========================+================+=========================+=================+================+ | inputs.a.cpu() | const float& | inputs.a_t_gpu | const float* | const float* | +-------------------------+----------------+-------------------------+-----------------+----------------+ | inputs.b.cpu() | const float& | inputs.b.gpu() | const float* | const float* | +-------------------------+----------------+-------------------------+-----------------+----------------+ | outputs.sum.cpu() | float& | outputs.sum.gpu() | float* | float* | +-------------------------+----------------+-------------------------+-----------------+----------------+ | inputs.multiplier.cpu() | const GfVec3f& | inputs.multiplier.gpu() | const GfVec3f* | const float3 | +-------------------------+----------------+-------------------------+-----------------+----------------+ | inputs.points.cpu() | const GfVec3f* | inputs.points.gpu() | const GfVec3f** | const float3** | +-------------------------+----------------+-------------------------+-----------------+----------------+ | outputs.points.cpu() | GfVec3f* | outputs.points.gpu() | const GfVec3f** | float3** | +-------------------------+----------------+-------------------------+-----------------+----------------+ Type Information ++++++++++++++++ As there are three different potential types for each attribute when it varies location at runtime (CPU, CPU being passed to GPU, and GPU) there are extra types introduced in order to handle each of them. The CUDA types are handled as before, but on the CPU side there are extra types for the data being passed from the CPU to the GPU. +----------------------+----------------+--------------------------+-----------------+ | CPU Type Method | CPU Data Type | GPU Type Method | GPU Data Type | +======================+================+==========================+=================+ | inputs::a_t | const float& | inputs::a_t_gpu | const float* | +----------------------+----------------+--------------------------+-----------------+ | inputs::b_t | const float& | inputs::b_t_gpu | const float* | +----------------------+----------------+--------------------------+-----------------+ | outputs::sum_t | float& | outputs::sum_t_gpu | float* | +----------------------+----------------+--------------------------+-----------------+ | inputs::multiplier_t | const GfVec3f& | inputs::multiplier_t_gpu | const GfVec3f* | +----------------------+----------------+--------------------------+-----------------+ | inputs::points_t | const GfVec3f* | inputs::points_t_gpu | const GfVec3f** | +----------------------+----------------+--------------------------+-----------------+ | outputs::points_t | GfVec3f* | outputs::points_t_gpu | const GfVec3f** | +----------------------+----------------+--------------------------+-----------------+ On the C++ side the functions defined in the CUDA file are declared as: .. code-block:: c++ extern "C" void cpuGpuMultiplierCPU(outputs::points_t, inputs::multiplier_t, inputs::points_t, size_t); extern "C" void cpuGpuMultiplierGPU(outputs::points_t_gpu, inputs::multiplier_t_gpu, inputs::points_t_gpu, size_t); The addition of the **_gpu** suffix mostly adds an extra layer of indirection to the values, since they exist in the GPU memory namespace. Care must be taken to call the correct version with the correctly extracted data: .. code-block:: c++ if (db.inputs.is_gpu()) { cpuGpuMultiplierGPU( db.outputs.points.gpu(), db.inputs.multiplier.gpu(), db.inputs.points.gpu(), numberOfPoints ); } else { // Note how array data is extracted in its raw form for passing to the function on the CUDA side. // This would be unnecessary if the implementation were entirely on the CPU side. cpuGpuMultiplierCPU( db.outputs.points.cpu().data(), db.inputs.multiplier.cpu(), db.inputs.points.cpu().data(), numberOfPoints ); } On the CUDA side the function definitions use the existing CUDA types, so their signatures are: .. code-block:: c++ extern "C" void cpuGpuMultiplierCPU(outputs::points_t, inputs::multiplier_t, inputs::points_t, size_t); extern "C" void cpuGpuMultiplierGPU(outputs::points_t, inputs::multiplier_t, inputs::points_t, size_t);
6,658
reStructuredText
53.138211
124
0.499549
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial27/OgnTutorialCudaDataCpuPy.py
""" Implementation of the Python node accessing CUDA attributes in a way that accesses the GPU arrays with a CPU pointer. No actual computation is done here as the tutorial nodes are not set up to handle GPU computation. """ import ctypes import omni.graph.core as og # Only one type of data is handled by the compute - pointf[3][] POINT_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1, role=og.AttributeRole.POSITION) def get_address(attr: og.Attribute) -> int: """Returns the contents of the memory the attribute points to""" ptr_type = ctypes.POINTER(ctypes.c_size_t) ptr = ctypes.cast(attr.memory, ptr_type) return ptr.contents.value class OgnTutorialCudaDataCpuPy: """Exercise GPU access for extended attributes through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Accesses the CUDA data, which for arrays exists as wrappers around CPU memory pointers to GPU pointer arrays. No compute is done here. """ # Put accessors into local variables for convenience input_points = db.inputs.points multiplier = db.inputs.multiplier # Set the size to what is required for the multiplication - this can be done without accessing GPU data. # Notice that since this is CPU pointers to GPU data the size has to be taken from the data type description # rather than the usual method of taking len(input_points). db.outputs.points_size = input_points.dtype.size # After changing the size the memory isn't allocated immediately (when necessary). It is delayed until you # request access to it, which is what this line will do. output_points = db.outputs.points # This is a separate test to add a points attribute to the output bundle to show how when a bundle has # CPU pointers to the GPU data that information propagates to its children # Start with an empty output bundle. output_bundle = db.outputs.outBundle output_bundle.clear() output_bundle.add_attributes([og.Type(og.BaseDataType.FLOAT, 3, 1)], ["points"]) bundle_attr = output_bundle.attribute_by_name("points") # As for the main attributes, setting the bundle member size readies the buffer of the given size on the GPU bundle_attr.size = input_points.dtype.size # The output cannot be written to here through the normal assignment mechanisms, e.g. the typical step of # copying input points to the output points, as the data is not accessible on the GPU through Python directly. # Instead you can access the GPU memory pointers through the attribute values and send it to CUDA code, either # generated from the Python code or accessed through something like pybind wrappers. print("Locations in CUDA() should be in GPU memory space") print(f" CPU Location for reference = {hex(id(db))}", flush=True) print(f" Input points are {input_points} at CUDA({hex(get_address(input_points))})", flush=True) print(f" Multiplier is CUDA({multiplier})", flush=True) print(f" Output points are {output_points} at CUDA({hex(get_address(output_points))})", flush=True) print(f" Bundle {bundle_attr.gpu_value} at CUDA({hex(get_address(bundle_attr.gpu_value))})", flush=True) return True
3,391
Python
50.393939
120
0.699204
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial27/OgnTutorialCudaDataCpu.cpp
// Copyright (c) 2020, 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. // #include <omni/graph/core/GpuArray.h> #include <OgnTutorialCudaDataCpuDatabase.h> // This function exercises referencing of array data on the GPU. // The CUDA code takes its own "float3" data types, which are castable equivalents to the generated GfVec3f. // The GpuArray/ConstGpuArray wrappers isolate the GPU pointers from the CPU code. extern "C" void applyDeformationCpuToGpu(pxr::GfVec3f* outputPoints, const pxr::GfVec3f* inputPoints, const pxr::GfVec3f* multiplier, size_t numberOfPoints); // This node runs a couple of algorithms on the GPU, while accessing parameters from the CPU class OgnTutorialCudaDataCpu { public: static bool compute(OgnTutorialCudaDataCpuDatabase& db) { size_t numberOfPoints = db.inputs.points.size(); db.outputs.points.resize(numberOfPoints); if (numberOfPoints > 0) { // The main point to note here is how the pointer can be dereferenced on the CPU side, whereas normally // you would have to send it to the GPU for dereferencing. (The long term purpose of the latter is to make // it more efficient to handle arrays-of-arrays on the GPU, however since that is not yet implemented // we can get away with a single dereference here.) applyDeformationCpuToGpu(*db.outputs.points(), *db.inputs.points.gpu(), db.inputs.multiplier(), numberOfPoints); // Just as a test now also reference the points as CPU data to ensure the value casts correctly const float* pointsAsCpu = reinterpret_cast<const float*>(db.inputs.points.cpu().data()); } return true; } }; REGISTER_OGN_NODE()
2,216
C++
47.195651
124
0.686823
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial27/tutorial27.rst
.. _ogn_tutorial_cudaDataOnCpu: Tutorial 27 - GPU Data Node with CPU Array Pointers =================================================== The GPU data node illustrates the alternative method of extracting array data from the GPU by returning a CPU pointer to the GPU array. Normally the data returns a GPU pointer to an array of GPU pointers, optimized for future use in parallel processing of GPU array data. By returning a CPU pointer to the array you can use host-side processing to dereference the pointers. OgnTutorialCudaDataCpu.ogn -------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CudaCpuArrays", which has an input and an output of type `float[3][]`, along with the special keyword to indicate that the pointer to the CUDA arrays should be in CPU space. .. literalinclude:: OgnTutorialCudaDataCpu.ogn :linenos: :language: json :emphasize-lines: 5 OgnTutorialCudaDataCpu.cpp -------------------------- The *cpp* file contains the implementation of the compute method, which in turn calls the CUDA algorithm. .. literalinclude:: OgnTutorialCudaDataCpu.cpp :linenos: :language: c++ :emphasize-lines: 31-35 OgnTutorialCudaDataCpu_CUDA.cu ------------------------------ The *cu* file contains the implementation of the algorithm on the GPU using CUDA. .. literalinclude:: OgnTutorialCudaDataCpu_CUDA.cu :linenos: :language: c++ OgnTutorialCudaDataCpuPy.py --------------------------- The *py* file contains the implementation of the compute method, which for this example doesn't actually compute as extra extension support is required for Python to run on the GPU (e.g. a Python -> CUDA compiler). .. literalinclude:: OgnTutorialCudaDataCpuPy.py :linenos: :language: python :emphasize-lines: 31-35
1,811
reStructuredText
35.979591
117
0.70127
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial30/OgnTutorialSIMDAdd.cpp
// 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. // #if !defined(__arm__) && !defined(__aarch64__) #define SIMD_AVAILABLE #endif #include <OgnTutorialSIMDAddDatabase.h> #ifdef SIMD_AVAILABLE #include <immintrin.h> #endif // This node perform a sum using SIMD instruction set class OgnTutorialSIMDAdd { public: static size_t computeVectorized(OgnTutorialSIMDAddDatabase& db, size_t count) { // Constants static size_t constexpr kSIMDSize = 4 * sizeof(float); static size_t constexpr kMask = kSIMDSize - 1; // Retrieve data auto opA = db.inputs.a.vectorized(count); auto opB = db.inputs.b.vectorized(count); auto res = db.outputs.result.vectorized(count); //Regular loop definition auto regularLoop = [&](size_t const begin, size_t const end) -> size_t const { for (size_t idx = begin; idx < end; ++idx) res[idx] = opA[idx] + opB[idx]; return end; }; #ifdef SIMD_AVAILABLE //Alignment must be identical bool const correctlyAligned = ((size_t(opA.data()) & kMask) == (size_t(opB.data()) & kMask)) && ((size_t(opA.data()) & kMask) == (size_t(res.data()) & kMask)); if (!correctlyAligned) { regularLoop(0, count); } else { // Unaligned elements size_t const maskedAdress = (size_t(opA.data()) & kMask); size_t const unalignedCount = maskedAdress ? regularLoop(0, (kSIMDSize - maskedAdress) / sizeof(float)) : 0; // Vectorized elements size_t const vectorizedCount = (count - unalignedCount) & (~kMask); size_t const vectorizedLoop = vectorizedCount / (kSIMDSize / sizeof(float)); __m128* aSIMD = (__m128*)(opA.data() + unalignedCount); __m128* bSIMD = (__m128*)(opB.data() + unalignedCount); __m128* resSIMD = (__m128*)(res.data() + unalignedCount); for (size_t idx = 0; idx < vectorizedLoop; ++idx) resSIMD[idx] = _mm_add_ps(aSIMD[idx], bSIMD[idx]); // Remaining elements regularLoop(unalignedCount + vectorizedCount, count); } #else regularLoop(0, count); #endif return count; } }; REGISTER_OGN_NODE()
2,795
C++
31.511628
104
0.589982
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/extensionTutorial/extensionTutorial.rst
.. _ogn_extension_tutorial: Example Setup - Creating An OGN-enabled Extension ================================================= This document assumes familiarity with the extension 2.0 implementation described in the Extensions doc. Implementation details that relate to the extension system but not to .ogn files in particular will not be described in detail. Refer to the above document for more information. .. only:: internal Internal: link to Extensions / exts-main-doc broken until kit_repo_docs migration completed (bidirectional dependency bad) For the purposes of illustration an extension names `omni.my.extension` will be created, with a single node `OgnMyNode`. .. contents:: .. _ogn_recommended_directory_structure: Recommended Directory Structure ------------------------------- The OGN helper scripts presume a certain directory structure, setting up helper variables that default to values supporting that structure. You're free to use any other structure, you will just have more work to do in your build file to support them. To start with are the directories. .. code-block:: text :emphasize-lines: 1,2,4,6,8,12,15,19,21,23,26 omni.my.extension/ ├── bindings/ | └── BindingsPython.cpp ├── config/ | └── extension.toml ├── data/ | └── preview.png ├── docs/ | ├── README.md | ├── CHANGELOG.md | └── index.rst ├── nodes/ | ├── OgnMyNode.cpp | └── OgnMyNode.ogn ├── plugins/ | ├── PluginInterface.cpp | └── IMyExtension.h ├── premake5.lua └── python/ ├── __init__.py ├── _impl/ | extension.py | └── nodes/ | ├── OgnMyPythonNode.py | └── OgnMyPythonNode.ogn └── tests/ └── test_my_extension.py **omni.my.extension** is the top level directory for the extension, keeping all related files together. **config** is the common location for the extension configuration file. **data** is the common location for data files used by your extension. **docs** is the common location for published documentation for your extension. **nodes** is a directory you can put all of your node files. If there is a large number of nodes for a single extension then this directory can be subdivided (e.g. **nodes/math**, **nodes/core**, **nodes/vectors**...) **plugins** is for the common C++ code. In particular the files connecting to the Carbonite plugin ABI, but also other files used by the plugin that aren't specifically node files. **python** contains just the __init__.py script used to load the extension. The main feature of this file is that it is used to import everything in the **python/_impl** subdirectory that will be exposed as the public API. Although this is just a convention, as every function will always be accessible for the user that digs deep enough, setting up your intended API in this way makes it more clear exactly what parts of your module are intended for public use, and hence expected to be more stable. **python/_impl** contains all of the Python scripts. At the top level this can be UI files, commands, and helper scripts. **python/_impl/nodes** contains all of your nodes implemented in Python. Separating them into their own directory makes it easier for the OGN processor to find them. **python/tests** is for the scripts used to test the functionality in your extension. These are your armour, keeping your extension safe from changes others make, and providing confidence when you refactor. premake5.lua ------------ The *.lua* file containing an extension 2.0 implementation of an extension. The OGN-specific additions are commented. (Other lines would normally be commented as well in good build code; omitted here for clarity.) .. literalinclude:: premake5.lua :linenos: :language: lua Here is that same file with appropriate comments that can be used as a starting template. .. literalinclude:: premake5-template.lua :linenos: :language: lua Changing Type Definitions +++++++++++++++++++++++++ By default the code generator uses certain C++, CUDA, and Python data types for the code it produces. Sometimes you may wish to use alternative types, e.g. your favourite math library's types. This information can be modified through a type definition file. To modify the type definitions for an entire project you add an extra parameter to the call to `get_ogn_project_information()` in your ``premake5.lua`` file, with details described in :ref:`ogn_type_definition_overrides`. bindings/BindingsPython.cpp --------------------------- This file is set up as per the regular extension set up you can find in the Extensions doc with no OGN-specific changes required. .. only:: internal Internal: link to Extensions / exts-main-doc broken until kit_repo_docs migration completed (bidirectional dependency bad) config/extension.toml --------------------- In addition to the other required dependencies, the OmniGraph dependencies need to be added for the extension loading to work properly. These are the OmniGraph core, and the Kit async engine used for running tests. .. code-block:: toml :linenos: :emphasize-lines: 8-11,15-16 [package] title = "My Feature" # Main module for the Python interface [[python.module]] name = "omni.my.feature" # Watch the .ogn files for hot reloading (only works for Python files) [fswatcher.patterns] include = ["*.ogn", "*.py"] exclude = ["Ogn*Database.py"] # Other extensions that need to load before this one [dependencies] "omni.graph" = {} "omni.graph.tools" = {} [[native.plugin]] path = "bin/${platform}/${config}/*.plugin" recursive = false data/preview.png ---------------- This file is an image that will be displayed in the extension manager. Nothing extra needs to be done to make that happen; just create the file and ensure that the **data/** directory is installed into the extension's destination directory. docs/README.md -------------- Markdown format documentation for your extension that will appear in the extension manager. It should be a short description of what the extension does. Here is a minimal version of a readme. .. code-block:: md # My Extension [omni.my.extension] My extension can cook your breakfast, mow your lawn, and fix the clog in your kitchen sink. docs/CHANGELOG.md ----------------- Markdown format documentation for your extension changes that will appear in the extension manager. Here is a simple template that uses a standard approach to maintaining change logs. .. code-block:: md # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [1.0.0] - 2021-03-01 ### Initial Version docs/index.rst -------------- ReStructuredText format documentation for your extension. The node's documentation will be generated automatically by the OGN processor. nodes/OgnMyNode.cpp,OgnMyNode.ogn --------------------------------- These files contain the description and implementation of your node. See the detailed examples in :ref:`ogn_tutorial_nodes` for information on what can go into these files. The naming of the files is important. They must both have the same base name (``OgnMyNode`` in this case). It is also a good idea to have the common prefix `Ogn` as that makes nodes easier to locate. plugins/PluginInterface.cpp --------------------------- This file sets up your plugin. The OGN processing requires a couple of small additions to enable the automatic registration and deregistration of nodes when your plugin starts up and shuts down. .. code-block:: c++ :linenos: :emphasize-lines: 6,7,16-18,28,33 #include "IOmniMyFeature.h" #include <carb/Framework.h> #include <carb/PluginUtils.h> #include <omni/graph/core/iComputeGraph.h> #include <omni/graph/core/ogn/Registration.h> #include <omni/kit/IEditor.h> #include <omni/kit/IMinimal.h> const struct carb::PluginImplDesc pluginDesc = { "omni.my.feature.plugin", "My Feature", "NVIDIA", carb::PluginHotReload::eEnabled, "dev" }; CARB_PLUGIN_IMPL(pluginDesc, omni::my::feature::IOmniMyFeature) CARB_PLUGIN_IMPL_DEPS(omni::kit::IEditor, omni::graph::core::IGraphRegistry, carb::flatcache::IToken) DECLARE_OGN_NODES() // carbonite interface for this plugin (may contain multiple compute nodes) void fillInterface(omni::my::feature::IOmniMyFeature& iface) { iface = {}; } CARB_EXPORT void carbOnPluginStartup() { INITIALIZE_OGN_NODES() } CARB_EXPORT void carbOnPluginShutdown() { RELEASE_OGN_NODES() } plugins/IMyExtension.h ---------------------- This file is set up as per the extension description with no OGN-specific changes required. python/__init__.py ------------------ This file initializes the extension's Python module as per the extension model. This will import your intended Python API for general use. .. code-block:: python from ._impl.utilities import useful_utility from ._impl.utilities import other_utility from ._impl.commands import cmds With this setup the extension user can access your Python API through the main module (similarly to how popular public packages such as `numpy` and `pandas` are structured). .. code-block:: python import omni.my.feature as mf mf.useful_utility(["Bart", "Lisa", "Maggie", "Marge", "Homer"]) python/tests/__init__.py ------------------------ This file may contain setup code for your manually written test scripts that appear in this directory. It should contain the snippet below, which will enable automatic registration of your tests at runtime. .. code-block:: python """ Presence of this file allows the tests directory to be imported as a module so that all of its contents can be scanned to automatically add tests that are placed into this directory. """ scan_for_test_modules = True Test files should all have a PEP8-compliant name of the form ``test_my_good_test_file.py``. The `test` prefix ensures that the files will be automatically recognized as containing Python unit tests. Sample Skeleton Test -------------------- Here's an example of a simple test that does nothing more than run a graph evaluation on a graph consisting of two nodes with a connection between them, verifying the output of a node. While .ogn files have the ability to specify their own automated test configurations, it is very limited and you'll want to use something like this for more complex testing. .. literalinclude:: test_example.py :linenos: :language: python
10,947
reStructuredText
36.365188
136
0.698273
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/extensionTutorial/test_example.py
"""Tests for my simple math nodes""" # To make code more concise use a shortform in the import, much as you would for numpy -> np import omni.graph.core as og # This module contains some useful testing utilities import omni.graph.core.tests as ogts # By using the standard test case base class you get scene setUp() and tearDown(), and the current set of default # OmniGraph settings. If you wish to use any non-standard settings, leave the scene in place after the test completes, # or add your own scoped setting variables see the set of classes that derive from ogts.OmniGraphTestCase and look at # the test configuration factory function ogts.test_case_class(). class TestMySimpleNodes(ogts.OmniGraphTestCase): """Class containing tests for my simple nodes. The base class allows the tests to be run asynchronously""" # ---------------------------------------------------------------------- async def test_math(self): """Run a node network with the math operation (A + 6) * 10 = B Exercises the math nodes for addition (my.node.add) and multiplication (my.node.multiply) """ # The Controller class is useful for manipulating the OmniGraph. See the Python help on it for details. # Using this shortcut keeps the graph configuration specification more readable. keys = og.Controller.Keys # This sets up the graph in the configuration required for the math operation to work (graph, (plus_node, times_node), _, _) = og.Controller.edit( "/mathGraph", { keys.CREATE_NODES: [("plus", "my.extension.addInts"), ("times", "my.extension.multiplyInts")], keys.CONNECT: [("plus.outputs:result", "times.inputs:a")], keys.SET_VALUES: [("plus.inputs:a", 6), ("times.inputs:b", 10)], }, ) # This contains pairs of (A, B) values that should satisfy the math equation. test_data = [(1, 70), (0, 60), (-6, 0)] # Creating specific controllers tied to the attributes that will be accessed multiple times in the loop # makes the access a little bit faster. in_controller = og.Controller(og.Controller.attribute("inputs:b", plus_node)) out_controller = og.Controller(og.Controller.attribute("outputs:result", times_node)) # Loop through the operation to set the input and test the output for (value_a, value_b) in test_data: # Set the test input on the node in_controller.set(value_a) # This has to be done to ensure the nodes do their computation before testing the results await og.Controller.evaluate(graph) # Compare the expected value from the test data against the computed value from the node self.assertEqual(value_b, out_controller.get())
2,843
Python
52.660376
118
0.65459
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial14/OgnTutorialDefaults.cpp
// Copyright (c) 2020, 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. // #include <OgnTutorialDefaultsDatabase.h> class OgnTutorialDefaults { public: static bool compute(OgnTutorialDefaultsDatabase& db) { // Simple values db.outputs.a_bool() = db.inputs.a_bool(); db.outputs.a_half() = db.inputs.a_half(); db.outputs.a_int() = db.inputs.a_int(); db.outputs.a_int64() = db.inputs.a_int64(); db.outputs.a_double() = db.inputs.a_double(); db.outputs.a_float() = db.inputs.a_float(); db.outputs.a_uchar() = db.inputs.a_uchar(); db.outputs.a_uint() = db.inputs.a_uint(); db.outputs.a_uint64() = db.inputs.a_uint64(); db.outputs.a_token() = db.inputs.a_token(); db.outputs.a_string() = db.inputs.a_string(); // A few representative tuples db.outputs.a_int2() = db.inputs.a_int2(); db.outputs.a_matrix() = db.inputs.a_matrix(); // And an array db.outputs.a_array().resize(db.inputs.a_array().size()); db.outputs.a_array() = db.inputs.a_array(); return true; } }; REGISTER_OGN_NODE()
1,507
C++
34.904761
77
0.642999
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial14/tutorial14.rst
.. _ogn_tutorial_defaults: Tutorial 14 - Defaults ====================== While most inputs are required to have default values it's not strictly necessary to provide explicit values for those defaults. If a default is required and not specified then it will get a default value equal to an empty value. See the table at the bottom for what is considered an "empty" value for each type of attribute. OgnTutorialDefaults.ogn ------------------------ The *ogn* file shows the implementation of a node named "omni.graph.tutorials.Defaults", which has sample inputs of several types without default values and matching outputs. .. literalinclude:: OgnTutorialDefaults.ogn :linenos: :language: json OgnTutorialDefaults.cpp ------------------------ The *cpp* file contains the implementation of the compute method, which copies the input values over to the corresponding outputs. All values should be the empty defaults. .. literalinclude:: OgnTutorialDefaults.cpp :linenos: :language: c++ Empty Values For Attribute Types -------------------------------- The empty values for each of the attribute types is defined below. Having no default specified in the .ogn file for any of them is equivalent to defining a default of the given value. +-----------+---------------+ | Type Name | Empty Default | +===========+===============+ | bool | False | +-----------+---------------+ | double | 0.0 | +-----------+---------------+ | float | 0.0 | +-----------+---------------+ | half | 0.0 | +-----------+---------------+ | int | 0 | +-----------+---------------+ | int64 | 0 | +-----------+---------------+ | string | "" | +-----------+---------------+ | token | "" | +-----------+---------------+ | uchar | 0 | +-----------+---------------+ | uint | 0 | +-----------+---------------+ | uint64 | 0 | +-----------+---------------+ .. note:: All attributes that are array types have empty defaults equal to the empty array [] .. note:: All tuple types have empty defaults equal to a tuple of the correct count, each member containing the empty value for the base type. e.g. a float[2] will have empty default [0.0, 0.0], and a matrix[2] will have empty default [[0.0, 0.0], [0.0, 0.0]]
2,381
reStructuredText
34.029411
118
0.524989
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial26/OgnTutorialGenericMathNode.py
import numpy as np import omni.graph.core as og # Mappings of possible numpy dtypes from the result data type and back dtype_from_basetype = { og.BaseDataType.INT: np.int32, og.BaseDataType.INT64: np.int64, og.BaseDataType.HALF: np.float16, og.BaseDataType.FLOAT: np.float32, og.BaseDataType.DOUBLE: np.float64, } supported_basetypes = [ og.BaseDataType.INT, og.BaseDataType.INT64, og.BaseDataType.HALF, og.BaseDataType.FLOAT, og.BaseDataType.DOUBLE, ] basetype_resolution_table = [ [0, 1, 3, 3, 4], # Int [1, 1, 4, 4, 4], # Int64 [3, 4, 2, 3, 4], # Half [3, 4, 3, 3, 4], # Float [4, 4, 4, 4, 4], # Double ] class OgnTutorialGenericMathNode: """Node to multiple two values of any type""" @staticmethod def compute(db) -> bool: """Compute the product of two values, if the types are all resolved. When the types are not compatible for multiplication, or the result type is not compatible with the resolved output type, the method will log an error and fail """ try: # To support multiplying array of vectors by array of scalars we need to broadcast the scalars to match the # shape of the vector array, and we will convert the result to whatever the result is resolved to atype = db.inputs.a.type btype = db.inputs.b.type rtype = db.outputs.product.type result_dtype = dtype_from_basetype.get(rtype.base_type, None) # Use numpy to perform the multiplication in order to automatically handle both scalar and array types # and automatically convert to the resolved output type if atype.array_depth > 0 and btype.array_depth > 0 and btype.tuple_count < atype.tuple_count: r = np.multiply(db.inputs.a.value, db.inputs.b.value[:, np.newaxis], dtype=result_dtype) else: r = np.multiply(db.inputs.a.value, db.inputs.b.value, dtype=result_dtype) db.outputs.product.value = r except TypeError as error: db.log_error(f"Multiplication could not be performed: {error}") return False return True @staticmethod def on_connection_type_resolve(node) -> None: # Resolves the type of the output based on the types of inputs atype = node.get_attribute("inputs:a").get_resolved_type() btype = node.get_attribute("inputs:b").get_resolved_type() productattr = node.get_attribute("outputs:product") producttype = productattr.get_resolved_type() # The output types can be only inferred when both inputs types are resolved. if ( atype.base_type != og.BaseDataType.UNKNOWN and btype.base_type != og.BaseDataType.UNKNOWN and producttype.base_type == og.BaseDataType.UNKNOWN ): # Resolve the base type using the lookup table base_type = og.BaseDataType.DOUBLE a_index = supported_basetypes.index(atype.base_type) b_index = supported_basetypes.index(btype.base_type) if a_index >= 0 and b_index >= 0: base_type = supported_basetypes[basetype_resolution_table[a_index][b_index]] productattr.set_resolved_type( og.Type(base_type, max(atype.tuple_count, btype.tuple_count), max(atype.array_depth, btype.array_depth)) )
3,448
Python
37.322222
120
0.633991
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial26/tutorial26.rst
.. _ogn_tutorial_generic_math_node: Tutorial 26 - Generic Math Node ================================ This tutorial demonstrates how to compose nodes that perform mathematical operations in python using numpy. Using numpy has the advantage that it is api-compatible to cuNumeric. As demonstrated in the Extended Attributes tutorial, generic math nodes use extended attributes to allow inputs and outputs of arbitrary numeric types, specified using the "numerics" keyword. .. code-block:: json "inputs": { "myNumbericAttribute": { "description": "Accepts an incoming connection from any type of numeric value", "type": ["numerics"] } } OgnTutorialGenericMathNode.ogn -------------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.GenericMathNode", which takes inputs of any numeric types and performs a multiplication. .. literalinclude:: OgnTutorialGenericMathNode.ogn :linenos: :language: json OgnTutorialGenericMathNode.py --------------------------------- The *py* file contains the implementation of the node. It takes two numeric inputs and performs a multiplication, demonstrating how to handle cases where the inputs are both numeric types but vary in precision, format or dimension. .. literalinclude:: OgnTutorialGenericMathNode.py :linenos: :language: python
1,393
reStructuredText
36.675675
130
0.703518
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialTupleData.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'outputs': [ ['outputs:a_double2', [2.1, 3.2], False], ['outputs:a_float2', [5.4, 6.5], False], ['outputs:a_half2', [8.0, 9.0], False], ['outputs:a_int2', [11, 12], False], ['outputs:a_float3', [7.6, 8.7, 9.8], False], ['outputs:a_double3', [2.1, 3.2, 4.3], False], ], }, { 'inputs': [ ['inputs:a_double2', [2.1, 3.2], False], ['inputs:a_float2', [5.1, 6.2], False], ['inputs:a_half2', [8.0, 9.0], False], ['inputs:a_int2', [11, 12], False], ['inputs:a_float3', [7.1, 8.2, 9.3], False], ['inputs:a_double3', [10.1, 11.2, 12.3], False], ], 'outputs': [ ['outputs:a_double2', [3.1, 4.2], False], ['outputs:a_float2', [6.1, 7.2], False], ['outputs:a_half2', [9.0, 10.0], False], ['outputs:a_int2', [12, 13], False], ['outputs:a_float3', [8.1, 9.2, 10.3], False], ['outputs:a_double3', [11.1, 12.2, 13.3], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_tutorials_TupleData", "omni.tutorials.TupleData", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.tutorials.TupleData User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_tutorials_TupleData","omni.tutorials.TupleData", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.tutorials.TupleData User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_tutorials_TupleData", "omni.tutorials.TupleData", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.tutorials.TupleData User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialTupleDataDatabase import OgnTutorialTupleDataDatabase test_file_name = "OgnTutorialTupleDataTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_tutorials_TupleData") database = OgnTutorialTupleDataDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a_double2")) attribute = test_node.get_attribute("inputs:a_double2") db_value = database.inputs.a_double2 expected_value = [1.1, 2.2] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_double3")) attribute = test_node.get_attribute("inputs:a_double3") db_value = database.inputs.a_double3 expected_value = [1.1, 2.2, 3.3] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_float2")) attribute = test_node.get_attribute("inputs:a_float2") db_value = database.inputs.a_float2 expected_value = [4.4, 5.5] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_float3")) attribute = test_node.get_attribute("inputs:a_float3") db_value = database.inputs.a_float3 expected_value = [6.6, 7.7, 8.8] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_half2")) attribute = test_node.get_attribute("inputs:a_half2") db_value = database.inputs.a_half2 expected_value = [7.0, 8.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_int2")) attribute = test_node.get_attribute("inputs:a_int2") db_value = database.inputs.a_int2 expected_value = [10, 11] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:a_double2")) attribute = test_node.get_attribute("outputs:a_double2") db_value = database.outputs.a_double2 self.assertTrue(test_node.get_attribute_exists("outputs:a_double3")) attribute = test_node.get_attribute("outputs:a_double3") db_value = database.outputs.a_double3 self.assertTrue(test_node.get_attribute_exists("outputs:a_float2")) attribute = test_node.get_attribute("outputs:a_float2") db_value = database.outputs.a_float2 self.assertTrue(test_node.get_attribute_exists("outputs:a_float3")) attribute = test_node.get_attribute("outputs:a_float3") db_value = database.outputs.a_float3 self.assertTrue(test_node.get_attribute_exists("outputs:a_half2")) attribute = test_node.get_attribute("outputs:a_half2") db_value = database.outputs.a_half2 self.assertTrue(test_node.get_attribute_exists("outputs:a_int2")) attribute = test_node.get_attribute("outputs:a_int2") db_value = database.outputs.a_int2
8,539
Python
48.364162
187
0.65031
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCpuGpuBundlesPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCpuGpuBundlesPyDatabase import OgnTutorialCpuGpuBundlesPyDatabase test_file_name = "OgnTutorialCpuGpuBundlesPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CpuGpuBundlesPy") database = OgnTutorialCpuGpuBundlesPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:cpuBundle")) attribute = test_node.get_attribute("inputs:cpuBundle") db_value = database.inputs.cpuBundle self.assertTrue(test_node.get_attribute_exists("inputs:gpu")) attribute = test_node.get_attribute("inputs:gpu") db_value = database.inputs.gpu expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:gpuBundle")) attribute = test_node.get_attribute("inputs:gpuBundle") self.assertTrue(test_node.get_attribute_exists("outputs_cpuGpuBundle")) attribute = test_node.get_attribute("outputs_cpuGpuBundle") db_value = database.outputs.cpuGpuBundle
2,504
Python
49.099999
114
0.70647
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCpuGpuExtended.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:cpuData', {'type': 'pointf[3][]', 'value': [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]}, False], ['inputs:gpuData', {'type': 'pointf[3][]', 'value': [[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]]}, True], ['inputs:gpu', False, False], ], 'outputs': [ ['outputs:cpuGpuSum', {'type': 'pointf[3][]', 'value': [[8.0, 10.0, 12.0], [14.0, 16.0, 18.0]]}, False], ], }, { 'inputs': [ ['inputs:cpuData', {'type': 'pointf[3][]', 'value': [[4.0, 5.0, 6.0]]}, False], ['inputs:gpuData', {'type': 'pointf[3][]', 'value': [[7.0, 8.0, 9.0]]}, True], ['inputs:gpu', True, False], ], 'outputs': [ ['outputs:cpuGpuSum', {'type': 'pointf[3][]', 'value': [[11.0, 13.0, 15.0]]}, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CpuGpuExtended", "omni.graph.tutorials.CpuGpuExtended", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CpuGpuExtended User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CpuGpuExtended","omni.graph.tutorials.CpuGpuExtended", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CpuGpuExtended User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCpuGpuExtendedDatabase import OgnTutorialCpuGpuExtendedDatabase test_file_name = "OgnTutorialCpuGpuExtendedTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CpuGpuExtended") database = OgnTutorialCpuGpuExtendedDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:gpu")) attribute = test_node.get_attribute("inputs:gpu") db_value = database.inputs.gpu expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
4,140
Python
50.762499
190
0.616184
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialDynamicAttributes.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialDynamicAttributesDatabase import OgnTutorialDynamicAttributesDatabase test_file_name = "OgnTutorialDynamicAttributesTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_DynamicAttributes") database = OgnTutorialDynamicAttributesDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:value")) attribute = test_node.get_attribute("inputs:value") db_value = database.inputs.value expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:result")) attribute = test_node.get_attribute("outputs:result") db_value = database.outputs.result
2,171
Python
49.511627
118
0.707047
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCpuGpuBundles.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCpuGpuBundlesDatabase import OgnTutorialCpuGpuBundlesDatabase test_file_name = "OgnTutorialCpuGpuBundlesTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CpuGpuBundles") database = OgnTutorialCpuGpuBundlesDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:cpuBundle")) attribute = test_node.get_attribute("inputs:cpuBundle") db_value = database.inputs.cpuBundle self.assertTrue(test_node.get_attribute_exists("inputs:gpu")) attribute = test_node.get_attribute("inputs:gpu") db_value = database.inputs.gpu expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:gpuBundle")) attribute = test_node.get_attribute("inputs:gpuBundle") self.assertTrue(test_node.get_attribute_exists("outputs_cpuGpuBundle")) attribute = test_node.get_attribute("outputs_cpuGpuBundle") db_value = database.outputs.cpuGpuBundle
2,494
Python
48.899999
110
0.705293
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCudaDataCpu.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:multiplier', [1.0, 2.0, 3.0], True], ['inputs:points', [[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]], True], ], 'outputs': [ ['outputs:points', [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [3.0, 6.0, 9.0]], True], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CudaCpuArrays", "omni.graph.tutorials.CudaCpuArrays", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CudaCpuArrays User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CudaCpuArrays","omni.graph.tutorials.CudaCpuArrays", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CudaCpuArrays User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCudaDataCpuDatabase import OgnTutorialCudaDataCpuDatabase test_file_name = "OgnTutorialCudaDataCpuTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CudaCpuArrays") database = OgnTutorialCudaDataCpuDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:multiplier")) attribute = test_node.get_attribute("inputs:multiplier") expected_value = [1.0, 1.0, 1.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:points")) attribute = test_node.get_attribute("inputs:points") db_value = database.inputs.points.cpu expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points")
4,009
Python
50.410256
188
0.654278
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCudaDataCpuPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCudaDataCpuPyDatabase import OgnTutorialCudaDataCpuPyDatabase test_file_name = "OgnTutorialCudaDataCpuPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CudaCpuArraysPy") database = OgnTutorialCudaDataCpuPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:multiplier")) attribute = test_node.get_attribute("inputs:multiplier") expected_value = [1.0, 1.0, 1.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:points")) attribute = test_node.get_attribute("inputs:points") expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("outputs_outBundle")) attribute = test_node.get_attribute("outputs_outBundle") db_value = database.outputs.outBundle self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points")
2,500
Python
49.019999
110
0.7016
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialDynamicAttributesPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialDynamicAttributesPyDatabase import OgnTutorialDynamicAttributesPyDatabase test_file_name = "OgnTutorialDynamicAttributesPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_DynamicAttributesPy") database = OgnTutorialDynamicAttributesPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:value")) attribute = test_node.get_attribute("inputs:value") db_value = database.inputs.value expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:result")) attribute = test_node.get_attribute("outputs:result") db_value = database.outputs.result
2,181
Python
49.744185
122
0.708391
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialSIMDAdd.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialSIMDAddDatabase import OgnTutorialSIMDAddDatabase test_file_name = "OgnTutorialSIMDAddTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_TutorialSIMDFloatAdd") database = OgnTutorialSIMDAddDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a")) attribute = test_node.get_attribute("inputs:a") db_value = database.inputs.a expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:b")) attribute = test_node.get_attribute("inputs:b") db_value = database.inputs.b expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:result")) attribute = test_node.get_attribute("outputs:result") db_value = database.outputs.result
2,538
Python
48.784313
103
0.694641
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialStateAttributesPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'state_set': [ ['state:monotonic', 7, False], ], 'state_get': [ ['state:reset', False, False], ['state:monotonic', 8, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_StateAttributesPy", "omni.graph.tutorials.StateAttributesPy", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.StateAttributesPy User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_StateAttributesPy","omni.graph.tutorials.StateAttributesPy", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.StateAttributesPy User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialStateAttributesPyDatabase import OgnTutorialStateAttributesPyDatabase test_file_name = "OgnTutorialStateAttributesPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_StateAttributesPy") database = OgnTutorialStateAttributesPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:ignored")) attribute = test_node.get_attribute("inputs:ignored") db_value = database.inputs.ignored expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("state:monotonic")) attribute = test_node.get_attribute("state:monotonic") db_value = database.state.monotonic self.assertTrue(test_node.get_attribute_exists("state:reset")) attribute = test_node.get_attribute("state:reset") db_value = database.state.reset
3,852
Python
49.03896
196
0.668744
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialArrayData.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:original', [1.0, 2.0, 3.0], False], ['inputs:gates', [True, False, True], False], ['inputs:multiplier', 2.0, False], ], 'outputs': [ ['outputs:result', [2.0, 2.0, 6.0], False], ['outputs:negativeValues', [False, False, False], False], ['outputs:infoSize', 13, False], ], }, { 'inputs': [ ['inputs:original', [10.0, -20.0, 30.0], False], ['inputs:gates', [True, False, True], False], ], 'outputs': [ ['outputs:result', [10.0, -20.0, 30.0], False], ['outputs:negativeValues', [False, True, False], False], ], }, { 'inputs': [ ['inputs:info', ["Hello", "lamp\"post", "what'cha", "knowing"], False], ], 'outputs': [ ['outputs:infoSize', 29, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_ArrayData", "omni.graph.tutorials.ArrayData", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.ArrayData User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_ArrayData","omni.graph.tutorials.ArrayData", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.ArrayData User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_ArrayData", "omni.graph.tutorials.ArrayData", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.ArrayData User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialArrayDataDatabase import OgnTutorialArrayDataDatabase test_file_name = "OgnTutorialArrayDataTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_ArrayData") database = OgnTutorialArrayDataDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:gates")) attribute = test_node.get_attribute("inputs:gates") db_value = database.inputs.gates expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:info")) attribute = test_node.get_attribute("inputs:info") db_value = database.inputs.info expected_value = ['There', 'is', 'no', 'data'] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:multiplier")) attribute = test_node.get_attribute("inputs:multiplier") db_value = database.inputs.multiplier expected_value = 1.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:original")) attribute = test_node.get_attribute("inputs:original") db_value = database.inputs.original expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:infoSize")) attribute = test_node.get_attribute("outputs:infoSize") db_value = database.outputs.infoSize self.assertTrue(test_node.get_attribute_exists("outputs:negativeValues")) attribute = test_node.get_attribute("outputs:negativeValues") db_value = database.outputs.negativeValues self.assertTrue(test_node.get_attribute_exists("outputs:result")) attribute = test_node.get_attribute("outputs:result") db_value = database.outputs.result
7,088
Python
47.224489
199
0.648702
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialBundlesPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialBundlesPyDatabase import OgnTutorialBundlesPyDatabase test_file_name = "OgnTutorialBundlesPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_BundleManipulationPy") database = OgnTutorialBundlesPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:filteredBundle")) attribute = test_node.get_attribute("inputs:filteredBundle") db_value = database.inputs.filteredBundle self.assertTrue(test_node.get_attribute_exists("inputs:filters")) attribute = test_node.get_attribute("inputs:filters") db_value = database.inputs.filters expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:fullBundle")) attribute = test_node.get_attribute("inputs:fullBundle") db_value = database.inputs.fullBundle self.assertTrue(test_node.get_attribute_exists("outputs_combinedBundle")) attribute = test_node.get_attribute("outputs_combinedBundle") db_value = database.outputs.combinedBundle
2,563
Python
49.274509
103
0.706594
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialTokens.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:valuesToCheck', ["red", "Red", "magenta", "green", "cyan", "blue", "yellow"], False], ], 'outputs': [ ['outputs:isColor', [True, False, False, True, False, True, False], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_Tokens", "omni.graph.tutorials.Tokens", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.Tokens User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_Tokens","omni.graph.tutorials.Tokens", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.Tokens User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_Tokens", "omni.graph.tutorials.Tokens", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.Tokens User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialTokensDatabase import OgnTutorialTokensDatabase test_file_name = "OgnTutorialTokensTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_Tokens") database = OgnTutorialTokensDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:valuesToCheck")) attribute = test_node.get_attribute("inputs:valuesToCheck") db_value = database.inputs.valuesToCheck expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:isColor")) attribute = test_node.get_attribute("outputs:isColor") db_value = database.outputs.isColor
4,712
Python
49.677419
193
0.666808
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialVectorizedABIPassthrough.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:value', 1, False], ], 'outputs': [ ['outputs:value', 1, False], ], }, { 'inputs': [ ['inputs:value', 2, False], ], 'outputs': [ ['outputs:value', 2, False], ], }, { 'inputs': [ ['inputs:value', 3, False], ], 'outputs': [ ['outputs:value', 3, False], ], }, { 'inputs': [ ['inputs:value', 4, False], ], 'outputs': [ ['outputs:value', 4, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TutorialVectorizedABIPassThrough", "omni.graph.tutorials.TutorialVectorizedABIPassThrough", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TutorialVectorizedABIPassThrough User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TutorialVectorizedABIPassThrough","omni.graph.tutorials.TutorialVectorizedABIPassThrough", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TutorialVectorizedABIPassThrough User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialVectorizedABIPassthroughDatabase import OgnTutorialVectorizedABIPassthroughDatabase test_file_name = "OgnTutorialVectorizedABIPassthroughTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_TutorialVectorizedABIPassThrough") database = OgnTutorialVectorizedABIPassthroughDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:value")) attribute = test_node.get_attribute("inputs:value") db_value = database.inputs.value expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:value")) attribute = test_node.get_attribute("outputs:value") db_value = database.outputs.value
4,310
Python
43.90625
226
0.625522
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialABIPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:color', [0.2, 0.4, 0.4], False], ], 'outputs': [ ['outputs:h', 0.5, False], ['outputs:s', 0.5, False], ['outputs:v', 0.4, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_AbiPy", "omni.graph.tutorials.AbiPy", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.AbiPy User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_AbiPy","omni.graph.tutorials.AbiPy", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.AbiPy User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialABIPyDatabase import OgnTutorialABIPyDatabase test_file_name = "OgnTutorialABIPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_AbiPy") database = OgnTutorialABIPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:color")) attribute = test_node.get_attribute("inputs:color") db_value = database.inputs.color expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:h")) attribute = test_node.get_attribute("outputs:h") db_value = database.outputs.h self.assertTrue(test_node.get_attribute_exists("outputs:s")) attribute = test_node.get_attribute("outputs:s") db_value = database.outputs.s self.assertTrue(test_node.get_attribute_exists("outputs:v")) attribute = test_node.get_attribute("outputs:v") db_value = database.outputs.v
3,906
Python
46.646341
172
0.646953
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCpuGpuData.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:is_gpu', False, False], ['inputs:a', 1.0, True], ['inputs:b', 2.0, True], ], 'outputs': [ ['outputs:sum', 3.0, False], ], }, { 'inputs': [ ['inputs:is_gpu', False, False], ['inputs:a', 5.0, True], ['inputs:b', 3.0, True], ], 'outputs': [ ['outputs:sum', 8.0, False], ], }, { 'inputs': [ ['inputs:is_gpu', False, False], ['inputs:points', [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], True], ['inputs:multiplier', [2.0, 3.0, 4.0], True], ], 'outputs': [ ['outputs:points', [[2.0, 6.0, 12.0], [4.0, 9.0, 16.0]], False], ], }, { 'inputs': [ ['inputs:is_gpu', True, False], ['inputs:a', 1.0, True], ['inputs:b', 2.0, True], ['inputs:points', [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], True], ['inputs:multiplier', [2.0, 3.0, 4.0], True], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CpuGpuData", "omni.graph.tutorials.CpuGpuData", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CpuGpuData User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CpuGpuData","omni.graph.tutorials.CpuGpuData", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CpuGpuData User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCpuGpuDataDatabase import OgnTutorialCpuGpuDataDatabase test_file_name = "OgnTutorialCpuGpuDataTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CpuGpuData") database = OgnTutorialCpuGpuDataDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a")) attribute = test_node.get_attribute("inputs:a") db_value = database.inputs.a.cpu expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:b")) attribute = test_node.get_attribute("inputs:b") db_value = database.inputs.b.cpu expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:is_gpu")) attribute = test_node.get_attribute("inputs:is_gpu") db_value = database.inputs.is_gpu expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:multiplier")) attribute = test_node.get_attribute("inputs:multiplier") db_value = database.inputs.multiplier.cpu expected_value = [1.0, 1.0, 1.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:points")) attribute = test_node.get_attribute("inputs:points") db_value = database.inputs.points.cpu expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points.cpu self.assertTrue(test_node.get_attribute_exists("outputs:sum")) attribute = test_node.get_attribute("outputs:sum") db_value = database.outputs.sum.cpu
6,506
Python
45.812949
182
0.608669
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialBundleDataPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialBundleDataPyDatabase import OgnTutorialBundleDataPyDatabase test_file_name = "OgnTutorialBundleDataPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_BundleDataPy") database = OgnTutorialBundleDataPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:bundle")) attribute = test_node.get_attribute("inputs:bundle") db_value = database.inputs.bundle self.assertTrue(test_node.get_attribute_exists("outputs_bundle")) attribute = test_node.get_attribute("outputs_bundle") db_value = database.outputs.bundle
1,899
Python
47.717947
108
0.707214
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCudaData.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:a', 1.0, True], ['inputs:b', 2.0, True], ['inputs:half', 1.0, True], ['inputs:color', [0.5, 0.6, 0.7], True], ['inputs:matrix', [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], True], ['inputs:points', [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], True], ['inputs:multiplier', [2.0, 3.0, 4.0], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CudaData", "omni.graph.tutorials.CudaData", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CudaData User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CudaData","omni.graph.tutorials.CudaData", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CudaData User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_CudaData", "omni.graph.tutorials.CudaData", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.CudaData User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCudaDataDatabase import OgnTutorialCudaDataDatabase test_file_name = "OgnTutorialCudaDataTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CudaData") database = OgnTutorialCudaDataDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a")) attribute = test_node.get_attribute("inputs:a") expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:b")) attribute = test_node.get_attribute("inputs:b") expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:color")) attribute = test_node.get_attribute("inputs:color") expected_value = [1.0, 0.5, 1.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:half")) attribute = test_node.get_attribute("inputs:half") expected_value = 1.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:matrix")) attribute = test_node.get_attribute("inputs:matrix") expected_value = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:multiplier")) attribute = test_node.get_attribute("inputs:multiplier") db_value = database.inputs.multiplier expected_value = [1.0, 1.0, 1.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:points")) attribute = test_node.get_attribute("inputs:points") expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("outputs:color")) attribute = test_node.get_attribute("outputs:color") self.assertTrue(test_node.get_attribute_exists("outputs:half")) attribute = test_node.get_attribute("outputs:half") self.assertTrue(test_node.get_attribute_exists("outputs:matrix")) attribute = test_node.get_attribute("outputs:matrix") self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") self.assertTrue(test_node.get_attribute_exists("outputs:sum")) attribute = test_node.get_attribute("outputs:sum")
7,177
Python
49.195804
197
0.667688
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialGenericMathNode.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:a', {'type': 'int', 'value': 2}, False], ['inputs:b', {'type': 'int', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'int', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int', 'value': 2}, False], ['inputs:b', {'type': 'int64', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'int64', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int', 'value': 2}, False], ['inputs:b', {'type': 'half', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'float', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int', 'value': 2}, False], ['inputs:b', {'type': 'float', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'float', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int', 'value': 2}, False], ['inputs:b', {'type': 'double', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int64', 'value': 2}, False], ['inputs:b', {'type': 'int64', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'int64', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int64', 'value': 2}, False], ['inputs:b', {'type': 'half', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int64', 'value': 2}, False], ['inputs:b', {'type': 'float', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int64', 'value': 2}, False], ['inputs:b', {'type': 'double', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'half', 'value': 2}, False], ['inputs:b', {'type': 'half', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'half', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'half', 'value': 2}, False], ['inputs:b', {'type': 'float', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'float', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'half', 'value': 2}, False], ['inputs:b', {'type': 'double', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'float', 'value': 2}, False], ['inputs:b', {'type': 'float', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'float', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'float', 'value': 2}, False], ['inputs:b', {'type': 'double', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'double', 'value': 2}, False], ['inputs:b', {'type': 'double', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'double[2]', 'value': [1.0, 42.0]}, False], ['inputs:b', {'type': 'double[2]', 'value': [2.0, 1.0]}, False], ], 'outputs': [ ['outputs:product', {'type': 'double[2]', 'value': [2.0, 42.0]}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'double[]', 'value': [1.0, 42.0]}, False], ['inputs:b', {'type': 'double', 'value': 2.0}, False], ], 'outputs': [ ['outputs:product', {'type': 'double[]', 'value': [2.0, 84.0]}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'double[2][]', 'value': [[10, 5], [1, 1]]}, False], ['inputs:b', {'type': 'double[2]', 'value': [5, 5]}, False], ], 'outputs': [ ['outputs:product', {'type': 'double[2][]', 'value': [[50, 25], [5, 5]]}, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_GenericMathNode", "omni.graph.tutorials.GenericMathNode", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.GenericMathNode User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_GenericMathNode","omni.graph.tutorials.GenericMathNode", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.GenericMathNode User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialGenericMathNodeDatabase import OgnTutorialGenericMathNodeDatabase test_file_name = "OgnTutorialGenericMathNodeTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_GenericMathNode") database = OgnTutorialGenericMathNodeDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
8,510
Python
38.771028
192
0.446063
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/__init__.py
"""====== GENERATED BY omni.graph.tools - DO NOT EDIT ======""" import omni.graph.tools._internal as ogi ogi.import_tests_in_directory(__file__, __name__)
155
Python
37.999991
63
0.645161
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialSimpleDataPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:a_bool', False, False], ], 'outputs': [ ['outputs:a_bool', True, False], ], }, { 'inputs': [ ['inputs:a_bool', True, False], ], 'outputs': [ ['outputs:a_bool', False, False], ['outputs:a_a_boolUiName', "Simple Boolean Input", False], ['outputs:a_nodeTypeUiName', "Tutorial Python Node: Attributes With Simple Data", False], ], }, { 'inputs': [ ['inputs:a_path', "/World/Domination", False], ], 'outputs': [ ['outputs:a_path', "/World/Domination/Child", False], ], }, { 'inputs': [ ['inputs:a_bool', False, False], ['inputs:a_double', 1.1, False], ['inputs:a_float', 3.3, False], ['inputs:a_half', 5.0, False], ['inputs:a_int', 7, False], ['inputs:a_int64', 9, False], ['inputs:a_token', "helloToken", False], ['inputs:a_string', "helloString", False], ['inputs:a_objectId', 10, False], ['inputs:a_uchar', 11, False], ['inputs:a_uint', 13, False], ['inputs:a_uint64', 15, False], ], 'outputs': [ ['outputs:a_bool', True, False], ['outputs:a_double', 2.1, False], ['outputs:a_float', 4.3, False], ['outputs:a_half', 6.0, False], ['outputs:a_int', 8, False], ['outputs:a_int64', 10, False], ['outputs:a_token', "worldToken", False], ['outputs:a_string', "worldString", False], ['outputs:a_objectId', 11, False], ['outputs:a_uchar', 12, False], ['outputs:a_uint', 14, False], ['outputs:a_uint64', 16, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_SimpleDataPy", "omni.graph.tutorials.SimpleDataPy", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.SimpleDataPy User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_SimpleDataPy","omni.graph.tutorials.SimpleDataPy", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.SimpleDataPy User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialSimpleDataPyDatabase import OgnTutorialSimpleDataPyDatabase test_file_name = "OgnTutorialSimpleDataPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_SimpleDataPy") database = OgnTutorialSimpleDataPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a_constant_input")) attribute = test_node.get_attribute("inputs:a_constant_input") db_value = database.inputs.a_constant_input expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_double")) attribute = test_node.get_attribute("inputs:a_double") db_value = database.inputs.a_double expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_float")) attribute = test_node.get_attribute("inputs:a_float") db_value = database.inputs.a_float expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_half")) attribute = test_node.get_attribute("inputs:a_half") db_value = database.inputs.a_half expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_int")) attribute = test_node.get_attribute("inputs:a_int") db_value = database.inputs.a_int expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_int64")) attribute = test_node.get_attribute("inputs:a_int64") db_value = database.inputs.a_int64 expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_objectId")) attribute = test_node.get_attribute("inputs:a_objectId") db_value = database.inputs.a_objectId expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_path")) attribute = test_node.get_attribute("inputs:a_path") db_value = database.inputs.a_path expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_string")) attribute = test_node.get_attribute("inputs:a_string") db_value = database.inputs.a_string expected_value = "helloString" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_token")) attribute = test_node.get_attribute("inputs:a_token") db_value = database.inputs.a_token expected_value = "helloToken" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_uchar")) attribute = test_node.get_attribute("inputs:a_uchar") db_value = database.inputs.a_uchar expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_uint")) attribute = test_node.get_attribute("inputs:a_uint") db_value = database.inputs.a_uint expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_uint64")) attribute = test_node.get_attribute("inputs:a_uint64") db_value = database.inputs.a_uint64 expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:a_a_boolUiName")) attribute = test_node.get_attribute("outputs:a_a_boolUiName") db_value = database.outputs.a_a_boolUiName self.assertTrue(test_node.get_attribute_exists("outputs:a_bool")) attribute = test_node.get_attribute("outputs:a_bool") db_value = database.outputs.a_bool self.assertTrue(test_node.get_attribute_exists("outputs:a_double")) attribute = test_node.get_attribute("outputs:a_double") db_value = database.outputs.a_double self.assertTrue(test_node.get_attribute_exists("outputs:a_float")) attribute = test_node.get_attribute("outputs:a_float") db_value = database.outputs.a_float self.assertTrue(test_node.get_attribute_exists("outputs:a_half")) attribute = test_node.get_attribute("outputs:a_half") db_value = database.outputs.a_half self.assertTrue(test_node.get_attribute_exists("outputs:a_int")) attribute = test_node.get_attribute("outputs:a_int") db_value = database.outputs.a_int self.assertTrue(test_node.get_attribute_exists("outputs:a_int64")) attribute = test_node.get_attribute("outputs:a_int64") db_value = database.outputs.a_int64 self.assertTrue(test_node.get_attribute_exists("outputs:a_nodeTypeUiName")) attribute = test_node.get_attribute("outputs:a_nodeTypeUiName") db_value = database.outputs.a_nodeTypeUiName self.assertTrue(test_node.get_attribute_exists("outputs:a_objectId")) attribute = test_node.get_attribute("outputs:a_objectId") db_value = database.outputs.a_objectId self.assertTrue(test_node.get_attribute_exists("outputs:a_path")) attribute = test_node.get_attribute("outputs:a_path") db_value = database.outputs.a_path self.assertTrue(test_node.get_attribute_exists("outputs:a_string")) attribute = test_node.get_attribute("outputs:a_string") db_value = database.outputs.a_string self.assertTrue(test_node.get_attribute_exists("outputs:a_token")) attribute = test_node.get_attribute("outputs:a_token") db_value = database.outputs.a_token self.assertTrue(test_node.get_attribute_exists("outputs:a_uchar")) attribute = test_node.get_attribute("outputs:a_uchar") db_value = database.outputs.a_uchar self.assertTrue(test_node.get_attribute_exists("outputs:a_uint")) attribute = test_node.get_attribute("outputs:a_uint") db_value = database.outputs.a_uint self.assertTrue(test_node.get_attribute_exists("outputs:a_uint64")) attribute = test_node.get_attribute("outputs:a_uint64") db_value = database.outputs.a_uint64
13,304
Python
47.915441
186
0.63402
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialSimpleData.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:a_bool', False, False], ], 'outputs': [ ['outputs:a_bool', True, False], ], }, { 'inputs': [ ['inputs:a_bool', True, False], ], 'outputs': [ ['outputs:a_bool', False, False], ], }, { 'inputs': [ ['inputs:a_bool', False, False], ['inputs:a_double', 1.1, False], ['inputs:a_float', 3.3, False], ['inputs:a_half', 5.0, False], ['inputs:a_int', 7, False], ['inputs:a_int64', 9, False], ['inputs:a_token', "helloToken", False], ['inputs:a_string', "helloString", False], ['inputs:a_objectId', 5, False], ['inputs:unsigned:a_uchar', 11, False], ['inputs:unsigned:a_uint', 13, False], ['inputs:unsigned:a_uint64', 15, False], ], 'outputs': [ ['outputs:a_bool', True, False], ['outputs:a_double', 2.1, False], ['outputs:a_float', 4.3, False], ['outputs:a_half', 6.0, False], ['outputs:a_int', 8, False], ['outputs:a_int64', 10, False], ['outputs:a_token', "worldToken", False], ['outputs:a_string', "worldString", False], ['outputs:a_objectId', 6, False], ['outputs:unsigned:a_uchar', 12, False], ['outputs:unsigned:a_uint', 14, False], ['outputs:unsigned:a_uint64', 16, False], ], }, { 'inputs': [ ['inputs:a_token', "hello'Token", False], ['inputs:a_string', "hello\"String", False], ], 'outputs': [ ['outputs:a_token', "world'Token", False], ['outputs:a_string', "world\"String", False], ], }, { 'inputs': [ ['inputs:a_path', "/World/Domination", False], ], 'outputs': [ ['outputs:a_path', "/World/Domination/Child", False], ], }, { 'outputs': [ ['outputs:a_token', "worldToken", False], ['outputs:a_string', "worldString", False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_SimpleData", "omni.graph.tutorials.SimpleData", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.SimpleData User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_SimpleData","omni.graph.tutorials.SimpleData", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.SimpleData User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_SimpleData", "omni.graph.tutorials.SimpleData", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.SimpleData User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialSimpleDataDatabase import OgnTutorialSimpleDataDatabase test_file_name = "OgnTutorialSimpleDataTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_SimpleData") database = OgnTutorialSimpleDataDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a_bool")) attribute = test_node.get_attribute("inputs:a_bool") db_value = database.inputs.a_bool expected_value = True actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_constant_input")) attribute = test_node.get_attribute("inputs:a_constant_input") db_value = database.inputs.a_constant_input expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_double")) attribute = test_node.get_attribute("inputs:a_double") db_value = database.inputs.a_double expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_float")) attribute = test_node.get_attribute("inputs:a_float") db_value = database.inputs.a_float expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_half")) attribute = test_node.get_attribute("inputs:a_half") db_value = database.inputs.a_half expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_int")) attribute = test_node.get_attribute("inputs:a_int") db_value = database.inputs.a_int expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_int64")) attribute = test_node.get_attribute("inputs:a_int64") db_value = database.inputs.a_int64 expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_objectId")) attribute = test_node.get_attribute("inputs:a_objectId") db_value = database.inputs.a_objectId expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_path")) attribute = test_node.get_attribute("inputs:a_path") db_value = database.inputs.a_path expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_string")) attribute = test_node.get_attribute("inputs:a_string") db_value = database.inputs.a_string expected_value = "helloString" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_token")) attribute = test_node.get_attribute("inputs:a_token") db_value = database.inputs.a_token expected_value = "helloToken" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:unsigned:a_uchar")) attribute = test_node.get_attribute("inputs:unsigned:a_uchar") db_value = database.inputs.unsigned_a_uchar expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:unsigned:a_uint")) attribute = test_node.get_attribute("inputs:unsigned:a_uint") db_value = database.inputs.unsigned_a_uint expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:unsigned:a_uint64")) attribute = test_node.get_attribute("inputs:unsigned:a_uint64") db_value = database.inputs.unsigned_a_uint64 expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:a_bool")) attribute = test_node.get_attribute("outputs:a_bool") db_value = database.outputs.a_bool self.assertTrue(test_node.get_attribute_exists("outputs:a_double")) attribute = test_node.get_attribute("outputs:a_double") db_value = database.outputs.a_double self.assertTrue(test_node.get_attribute_exists("outputs:a_float")) attribute = test_node.get_attribute("outputs:a_float") db_value = database.outputs.a_float self.assertTrue(test_node.get_attribute_exists("outputs:a_half")) attribute = test_node.get_attribute("outputs:a_half") db_value = database.outputs.a_half self.assertTrue(test_node.get_attribute_exists("outputs:a_int")) attribute = test_node.get_attribute("outputs:a_int") db_value = database.outputs.a_int self.assertTrue(test_node.get_attribute_exists("outputs:a_int64")) attribute = test_node.get_attribute("outputs:a_int64") db_value = database.outputs.a_int64 self.assertTrue(test_node.get_attribute_exists("outputs:a_objectId")) attribute = test_node.get_attribute("outputs:a_objectId") db_value = database.outputs.a_objectId self.assertTrue(test_node.get_attribute_exists("outputs:a_path")) attribute = test_node.get_attribute("outputs:a_path") db_value = database.outputs.a_path self.assertTrue(test_node.get_attribute_exists("outputs:a_string")) attribute = test_node.get_attribute("outputs:a_string") db_value = database.outputs.a_string self.assertTrue(test_node.get_attribute_exists("outputs:a_token")) attribute = test_node.get_attribute("outputs:a_token") db_value = database.outputs.a_token self.assertTrue(test_node.get_attribute_exists("outputs:unsigned:a_uchar")) attribute = test_node.get_attribute("outputs:unsigned:a_uchar") db_value = database.outputs.unsigned_a_uchar self.assertTrue(test_node.get_attribute_exists("outputs:unsigned:a_uint")) attribute = test_node.get_attribute("outputs:unsigned:a_uint") db_value = database.outputs.unsigned_a_uint self.assertTrue(test_node.get_attribute_exists("outputs:unsigned:a_uint64")) attribute = test_node.get_attribute("outputs:unsigned:a_uint64") db_value = database.outputs.unsigned_a_uint64
14,434
Python
46.019544
201
0.653942
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialBundleData.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialBundleDataDatabase import OgnTutorialBundleDataDatabase test_file_name = "OgnTutorialBundleDataTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_BundleData") database = OgnTutorialBundleDataDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:bundle")) attribute = test_node.get_attribute("inputs:bundle") db_value = database.inputs.bundle self.assertTrue(test_node.get_attribute_exists("outputs_bundle")) attribute = test_node.get_attribute("outputs_bundle") db_value = database.outputs.bundle
1,889
Python
47.461537
104
0.705664
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialStatePy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:overrideValue', 5, False], ['inputs:override', True, False], ], 'outputs': [ ['outputs:monotonic', 5, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_StatePy", "omni.graph.tutorials.StatePy", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.StatePy User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_StatePy","omni.graph.tutorials.StatePy", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.StatePy User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialStatePyDatabase import OgnTutorialStatePyDatabase test_file_name = "OgnTutorialStatePyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_StatePy") database = OgnTutorialStatePyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:override")) attribute = test_node.get_attribute("inputs:override") db_value = database.inputs.override expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:overrideValue")) attribute = test_node.get_attribute("inputs:overrideValue") db_value = database.inputs.overrideValue expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:monotonic")) attribute = test_node.get_attribute("outputs:monotonic") db_value = database.outputs.monotonic
4,033
Python
48.802469
176
0.66427
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialOverrideType.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:data', [1.0, 2.0, 3.0], False], ], 'outputs': [ ['outputs:data', [2.0, 3.0, 1.0], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_OverrideType", "omni.graph.tutorials.OverrideType", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.OverrideType User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_OverrideType","omni.graph.tutorials.OverrideType", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.OverrideType User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_OverrideType", "omni.graph.tutorials.OverrideType", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.OverrideType User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialOverrideTypeDatabase import OgnTutorialOverrideTypeDatabase test_file_name = "OgnTutorialOverrideTypeTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_OverrideType") database = OgnTutorialOverrideTypeDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:data")) attribute = test_node.get_attribute("inputs:data") db_value = database.inputs.data expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:typedData")) attribute = test_node.get_attribute("inputs:typedData") db_value = database.inputs.typedData expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:data")) attribute = test_node.get_attribute("outputs:data") db_value = database.outputs.data self.assertTrue(test_node.get_attribute_exists("outputs:typedData")) attribute = test_node.get_attribute("outputs:typedData") db_value = database.outputs.typedData
5,284
Python
49.333333
205
0.675246
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialBundleAddAttributesPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialBundleAddAttributesPyDatabase import OgnTutorialBundleAddAttributesPyDatabase test_file_name = "OgnTutorialBundleAddAttributesPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_BundleAddAttributesPy") database = OgnTutorialBundleAddAttributesPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:addedAttributeNames")) attribute = test_node.get_attribute("inputs:addedAttributeNames") db_value = database.inputs.addedAttributeNames expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:removedAttributeNames")) attribute = test_node.get_attribute("inputs:removedAttributeNames") db_value = database.inputs.removedAttributeNames expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:typesToAdd")) attribute = test_node.get_attribute("inputs:typesToAdd") db_value = database.inputs.typesToAdd expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:useBatchedAPI")) attribute = test_node.get_attribute("inputs:useBatchedAPI") db_value = database.inputs.useBatchedAPI expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs_bundle")) attribute = test_node.get_attribute("outputs_bundle") db_value = database.outputs.bundle
3,599
Python
52.731342
126
0.707419
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialTupleArrays.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:a', [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], False], ['inputs:b', [[10.0, 5.0, 1.0], [1.0, 5.0, 10.0]], False], ], 'outputs': [ ['outputs:result', [23.0, 57.0], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TupleArrays", "omni.graph.tutorials.TupleArrays", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TupleArrays User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TupleArrays","omni.graph.tutorials.TupleArrays", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TupleArrays User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_TupleArrays", "omni.graph.tutorials.TupleArrays", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.TupleArrays User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialTupleArraysDatabase import OgnTutorialTupleArraysDatabase test_file_name = "OgnTutorialTupleArraysTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_TupleArrays") database = OgnTutorialTupleArraysDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a")) attribute = test_node.get_attribute("inputs:a") db_value = database.inputs.a expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:b")) attribute = test_node.get_attribute("inputs:b") db_value = database.inputs.b expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:result")) attribute = test_node.get_attribute("outputs:result") db_value = database.outputs.result
5,130
Python
49.303921
203
0.665497
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialABI.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:namespace:a_bool', True, False], ], 'outputs': [ ['outputs:namespace:a_bool', False, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_Abi", "omni.graph.tutorials.Abi", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.Abi User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_Abi","omni.graph.tutorials.Abi", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.Abi User test case #{i+1}", 16) async def test_data_access(self): test_file_name = "OgnTutorialABITemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_Abi") self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:namespace:a_bool")) attribute = test_node.get_attribute("inputs:namespace:a_bool") expected_value = True actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("outputs:namespace:a_bool")) attribute = test_node.get_attribute("outputs:namespace:a_bool")
3,219
Python
47.059701
168
0.653308
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialVectorizedPassthrough.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:value', 1, False], ], 'outputs': [ ['outputs:value', 1, False], ], }, { 'inputs': [ ['inputs:value', 2, False], ], 'outputs': [ ['outputs:value', 2, False], ], }, { 'inputs': [ ['inputs:value', 3, False], ], 'outputs': [ ['outputs:value', 3, False], ], }, { 'inputs': [ ['inputs:value', 4, False], ], 'outputs': [ ['outputs:value', 4, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TutorialVectorizedPassThrough", "omni.graph.tutorials.TutorialVectorizedPassThrough", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TutorialVectorizedPassThrough User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TutorialVectorizedPassThrough","omni.graph.tutorials.TutorialVectorizedPassThrough", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TutorialVectorizedPassThrough User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialVectorizedPassthroughDatabase import OgnTutorialVectorizedPassthroughDatabase test_file_name = "OgnTutorialVectorizedPassthroughTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_TutorialVectorizedPassThrough") database = OgnTutorialVectorizedPassthroughDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:value")) attribute = test_node.get_attribute("inputs:value") db_value = database.inputs.value expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:value")) attribute = test_node.get_attribute("outputs:value") db_value = database.outputs.value
4,277
Python
43.5625
220
0.622633
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialExtendedTypes.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialExtendedTypesDatabase import OgnTutorialExtendedTypesDatabase test_file_name = "OgnTutorialExtendedTypesTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_ExtendedTypes") database = OgnTutorialExtendedTypesDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
1,547
Python
48.935482
110
0.714286
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialExtendedTypesPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialExtendedTypesPyDatabase import OgnTutorialExtendedTypesPyDatabase test_file_name = "OgnTutorialExtendedTypesPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_ExtendedTypesPy") database = OgnTutorialExtendedTypesPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
1,557
Python
49.258063
114
0.716121
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialBundles.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialBundlesDatabase import OgnTutorialBundlesDatabase test_file_name = "OgnTutorialBundlesTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_BundleManipulation") database = OgnTutorialBundlesDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:filteredBundle")) attribute = test_node.get_attribute("inputs:filteredBundle") db_value = database.inputs.filteredBundle self.assertTrue(test_node.get_attribute_exists("inputs:filters")) attribute = test_node.get_attribute("inputs:filters") db_value = database.inputs.filters expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:fullBundle")) attribute = test_node.get_attribute("inputs:fullBundle") db_value = database.inputs.fullBundle self.assertTrue(test_node.get_attribute_exists("outputs_combinedBundle")) attribute = test_node.get_attribute("outputs_combinedBundle") db_value = database.outputs.combinedBundle
2,553
Python
49.07843
101
0.705445
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialComplexDataPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'outputs': [ ['outputs:a_productArray', [], False], ], }, { 'inputs': [ ['inputs:a_inputArray', [1.0, 2.0, 3.0, 4.0, 5.0], False], ['inputs:a_vectorMultiplier', [6.0, 7.0, 8.0], False], ], 'outputs': [ ['outputs:a_productArray', [[6.0, 7.0, 8.0], [12.0, 14.0, 16.0], [18.0, 21.0, 24.0], [24.0, 28.0, 32.0], [30.0, 35.0, 40.0]], False], ['outputs:a_tokenArray', ["1.0", "2.0", "3.0", "4.0", "5.0"], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_ComplexDataPy", "omni.graph.tutorials.ComplexDataPy", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.ComplexDataPy User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_ComplexDataPy","omni.graph.tutorials.ComplexDataPy", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.ComplexDataPy User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialComplexDataPyDatabase import OgnTutorialComplexDataPyDatabase test_file_name = "OgnTutorialComplexDataPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_ComplexDataPy") database = OgnTutorialComplexDataPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a_inputArray")) attribute = test_node.get_attribute("inputs:a_inputArray") db_value = database.inputs.a_inputArray expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_vectorMultiplier")) attribute = test_node.get_attribute("inputs:a_vectorMultiplier") db_value = database.inputs.a_vectorMultiplier expected_value = [1.0, 2.0, 3.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:a_productArray")) attribute = test_node.get_attribute("outputs:a_productArray") db_value = database.outputs.a_productArray self.assertTrue(test_node.get_attribute_exists("outputs:a_tokenArray")) attribute = test_node.get_attribute("outputs:a_tokenArray") db_value = database.outputs.a_tokenArray
4,697
Python
50.626373
188
0.648073
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialEmpty.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialEmptyDatabase import OgnTutorialEmptyDatabase test_file_name = "OgnTutorialEmptyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_Empty") database = OgnTutorialEmptyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
1,507
Python
47.64516
94
0.706702
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialTokensPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:valuesToCheck', ["red", "Red", "magenta", "green", "cyan", "blue", "yellow"], False], ], 'outputs': [ ['outputs:isColor', [True, False, False, True, False, True, False], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TokensPy", "omni.graph.tutorials.TokensPy", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TokensPy User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TokensPy","omni.graph.tutorials.TokensPy", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TokensPy User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialTokensPyDatabase import OgnTutorialTokensPyDatabase test_file_name = "OgnTutorialTokensPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_TokensPy") database = OgnTutorialTokensPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:valuesToCheck")) attribute = test_node.get_attribute("inputs:valuesToCheck") db_value = database.inputs.valuesToCheck expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:isColor")) attribute = test_node.get_attribute("outputs:isColor") db_value = database.outputs.isColor
3,654
Python
49.763888
178
0.662288
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialRoleData.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:a_color3d', [1.0, 2.0, 3.0], False], ['inputs:a_color3f', [11.0, 12.0, 13.0], False], ['inputs:a_color3h', [21.0, 22.0, 23.0], False], ['inputs:a_color4d', [1.0, 2.0, 3.0, 4.0], False], ['inputs:a_color4f', [11.0, 12.0, 13.0, 14.0], False], ['inputs:a_color4h', [21.0, 22.0, 23.0, 24.0], False], ['inputs:a_frame', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0], False], ['inputs:a_matrix2d', [1.0, 2.0, 3.0, 4.0], False], ['inputs:a_matrix3d', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], False], ['inputs:a_matrix4d', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0], False], ['inputs:a_normal3d', [1.0, 2.0, 3.0], False], ['inputs:a_normal3f', [11.0, 12.0, 13.0], False], ['inputs:a_normal3h', [21.0, 22.0, 23.0], False], ['inputs:a_point3d', [1.0, 2.0, 3.0], False], ['inputs:a_point3f', [11.0, 12.0, 13.0], False], ['inputs:a_point3h', [21.0, 22.0, 23.0], False], ['inputs:a_quatd', [1.0, 2.0, 3.0, 4.0], False], ['inputs:a_quatf', [11.0, 12.0, 13.0, 14.0], False], ['inputs:a_quath', [21.0, 22.0, 23.0, 24.0], False], ['inputs:a_texcoord2d', [1.0, 2.0], False], ['inputs:a_texcoord2f', [11.0, 12.0], False], ['inputs:a_texcoord2h', [21.0, 22.0], False], ['inputs:a_texcoord3d', [1.0, 2.0, 3.0], False], ['inputs:a_texcoord3f', [11.0, 12.0, 13.0], False], ['inputs:a_texcoord3h', [21.0, 22.0, 23.0], False], ['inputs:a_timecode', 10.0, False], ['inputs:a_vector3d', [1.0, 2.0, 3.0], False], ['inputs:a_vector3f', [11.0, 12.0, 13.0], False], ['inputs:a_vector3h', [21.0, 22.0, 23.0], False], ], 'outputs': [ ['outputs:a_color3d', [2.0, 3.0, 4.0], False], ['outputs:a_color3f', [12.0, 13.0, 14.0], False], ['outputs:a_color3h', [22.0, 23.0, 24.0], False], ['outputs:a_color4d', [2.0, 3.0, 4.0, 5.0], False], ['outputs:a_color4f', [12.0, 13.0, 14.0, 15.0], False], ['outputs:a_color4h', [22.0, 23.0, 24.0, 25.0], False], ['outputs:a_frame', [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0], False], ['outputs:a_matrix2d', [2.0, 3.0, 4.0, 5.0], False], ['outputs:a_matrix3d', [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], False], ['outputs:a_matrix4d', [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0], False], ['outputs:a_normal3d', [2.0, 3.0, 4.0], False], ['outputs:a_normal3f', [12.0, 13.0, 14.0], False], ['outputs:a_normal3h', [22.0, 23.0, 24.0], False], ['outputs:a_point3d', [2.0, 3.0, 4.0], False], ['outputs:a_point3f', [12.0, 13.0, 14.0], False], ['outputs:a_point3h', [22.0, 23.0, 24.0], False], ['outputs:a_quatd', [2.0, 3.0, 4.0, 5.0], False], ['outputs:a_quatf', [12.0, 13.0, 14.0, 15.0], False], ['outputs:a_quath', [22.0, 23.0, 24.0, 25.0], False], ['outputs:a_texcoord2d', [2.0, 3.0], False], ['outputs:a_texcoord2f', [12.0, 13.0], False], ['outputs:a_texcoord2h', [22.0, 23.0], False], ['outputs:a_texcoord3d', [2.0, 3.0, 4.0], False], ['outputs:a_texcoord3f', [12.0, 13.0, 14.0], False], ['outputs:a_texcoord3h', [22.0, 23.0, 24.0], False], ['outputs:a_timecode', 11.0, False], ['outputs:a_vector3d', [2.0, 3.0, 4.0], False], ['outputs:a_vector3f', [12.0, 13.0, 14.0], False], ['outputs:a_vector3h', [22.0, 23.0, 24.0], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_RoleData", "omni.graph.tutorials.RoleData", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.RoleData User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_RoleData","omni.graph.tutorials.RoleData", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.RoleData User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_RoleData", "omni.graph.tutorials.RoleData", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.RoleData User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialRoleDataDatabase import OgnTutorialRoleDataDatabase test_file_name = "OgnTutorialRoleDataTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_RoleData") database = OgnTutorialRoleDataDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a_color3d")) attribute = test_node.get_attribute("inputs:a_color3d") db_value = database.inputs.a_color3d expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_color3f")) attribute = test_node.get_attribute("inputs:a_color3f") db_value = database.inputs.a_color3f expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_color3h")) attribute = test_node.get_attribute("inputs:a_color3h") db_value = database.inputs.a_color3h expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_color4d")) attribute = test_node.get_attribute("inputs:a_color4d") db_value = database.inputs.a_color4d expected_value = [0.0, 0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_color4f")) attribute = test_node.get_attribute("inputs:a_color4f") db_value = database.inputs.a_color4f expected_value = [0.0, 0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_color4h")) attribute = test_node.get_attribute("inputs:a_color4h") db_value = database.inputs.a_color4h expected_value = [0.0, 0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_frame")) attribute = test_node.get_attribute("inputs:a_frame") db_value = database.inputs.a_frame expected_value = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_matrix2d")) attribute = test_node.get_attribute("inputs:a_matrix2d") db_value = database.inputs.a_matrix2d expected_value = [[1.0, 0.0], [0.0, 1.0]] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_matrix3d")) attribute = test_node.get_attribute("inputs:a_matrix3d") db_value = database.inputs.a_matrix3d expected_value = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_matrix4d")) attribute = test_node.get_attribute("inputs:a_matrix4d") db_value = database.inputs.a_matrix4d expected_value = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_normal3d")) attribute = test_node.get_attribute("inputs:a_normal3d") db_value = database.inputs.a_normal3d expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_normal3f")) attribute = test_node.get_attribute("inputs:a_normal3f") db_value = database.inputs.a_normal3f expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_normal3h")) attribute = test_node.get_attribute("inputs:a_normal3h") db_value = database.inputs.a_normal3h expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_point3d")) attribute = test_node.get_attribute("inputs:a_point3d") db_value = database.inputs.a_point3d expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_point3f")) attribute = test_node.get_attribute("inputs:a_point3f") db_value = database.inputs.a_point3f expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_point3h")) attribute = test_node.get_attribute("inputs:a_point3h") db_value = database.inputs.a_point3h expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_quatd")) attribute = test_node.get_attribute("inputs:a_quatd") db_value = database.inputs.a_quatd expected_value = [0.0, 0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_quatf")) attribute = test_node.get_attribute("inputs:a_quatf") db_value = database.inputs.a_quatf expected_value = [0.0, 0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_quath")) attribute = test_node.get_attribute("inputs:a_quath") db_value = database.inputs.a_quath expected_value = [0.0, 0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_texcoord2d")) attribute = test_node.get_attribute("inputs:a_texcoord2d") db_value = database.inputs.a_texcoord2d expected_value = [0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_texcoord2f")) attribute = test_node.get_attribute("inputs:a_texcoord2f") db_value = database.inputs.a_texcoord2f expected_value = [0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_texcoord2h")) attribute = test_node.get_attribute("inputs:a_texcoord2h") db_value = database.inputs.a_texcoord2h expected_value = [0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_texcoord3d")) attribute = test_node.get_attribute("inputs:a_texcoord3d") db_value = database.inputs.a_texcoord3d expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_texcoord3f")) attribute = test_node.get_attribute("inputs:a_texcoord3f") db_value = database.inputs.a_texcoord3f expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_texcoord3h")) attribute = test_node.get_attribute("inputs:a_texcoord3h") db_value = database.inputs.a_texcoord3h expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_timecode")) attribute = test_node.get_attribute("inputs:a_timecode") db_value = database.inputs.a_timecode expected_value = 1.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_vector3d")) attribute = test_node.get_attribute("inputs:a_vector3d") db_value = database.inputs.a_vector3d expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_vector3f")) attribute = test_node.get_attribute("inputs:a_vector3f") db_value = database.inputs.a_vector3f expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_vector3h")) attribute = test_node.get_attribute("inputs:a_vector3h") db_value = database.inputs.a_vector3h expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:a_color3d")) attribute = test_node.get_attribute("outputs:a_color3d") db_value = database.outputs.a_color3d self.assertTrue(test_node.get_attribute_exists("outputs:a_color3f")) attribute = test_node.get_attribute("outputs:a_color3f") db_value = database.outputs.a_color3f self.assertTrue(test_node.get_attribute_exists("outputs:a_color3h")) attribute = test_node.get_attribute("outputs:a_color3h") db_value = database.outputs.a_color3h self.assertTrue(test_node.get_attribute_exists("outputs:a_color4d")) attribute = test_node.get_attribute("outputs:a_color4d") db_value = database.outputs.a_color4d self.assertTrue(test_node.get_attribute_exists("outputs:a_color4f")) attribute = test_node.get_attribute("outputs:a_color4f") db_value = database.outputs.a_color4f self.assertTrue(test_node.get_attribute_exists("outputs:a_color4h")) attribute = test_node.get_attribute("outputs:a_color4h") db_value = database.outputs.a_color4h self.assertTrue(test_node.get_attribute_exists("outputs:a_frame")) attribute = test_node.get_attribute("outputs:a_frame") db_value = database.outputs.a_frame self.assertTrue(test_node.get_attribute_exists("outputs:a_matrix2d")) attribute = test_node.get_attribute("outputs:a_matrix2d") db_value = database.outputs.a_matrix2d self.assertTrue(test_node.get_attribute_exists("outputs:a_matrix3d")) attribute = test_node.get_attribute("outputs:a_matrix3d") db_value = database.outputs.a_matrix3d self.assertTrue(test_node.get_attribute_exists("outputs:a_matrix4d")) attribute = test_node.get_attribute("outputs:a_matrix4d") db_value = database.outputs.a_matrix4d self.assertTrue(test_node.get_attribute_exists("outputs:a_normal3d")) attribute = test_node.get_attribute("outputs:a_normal3d") db_value = database.outputs.a_normal3d self.assertTrue(test_node.get_attribute_exists("outputs:a_normal3f")) attribute = test_node.get_attribute("outputs:a_normal3f") db_value = database.outputs.a_normal3f self.assertTrue(test_node.get_attribute_exists("outputs:a_normal3h")) attribute = test_node.get_attribute("outputs:a_normal3h") db_value = database.outputs.a_normal3h self.assertTrue(test_node.get_attribute_exists("outputs:a_point3d")) attribute = test_node.get_attribute("outputs:a_point3d") db_value = database.outputs.a_point3d self.assertTrue(test_node.get_attribute_exists("outputs:a_point3f")) attribute = test_node.get_attribute("outputs:a_point3f") db_value = database.outputs.a_point3f self.assertTrue(test_node.get_attribute_exists("outputs:a_point3h")) attribute = test_node.get_attribute("outputs:a_point3h") db_value = database.outputs.a_point3h self.assertTrue(test_node.get_attribute_exists("outputs:a_quatd")) attribute = test_node.get_attribute("outputs:a_quatd") db_value = database.outputs.a_quatd self.assertTrue(test_node.get_attribute_exists("outputs:a_quatf")) attribute = test_node.get_attribute("outputs:a_quatf") db_value = database.outputs.a_quatf self.assertTrue(test_node.get_attribute_exists("outputs:a_quath")) attribute = test_node.get_attribute("outputs:a_quath") db_value = database.outputs.a_quath self.assertTrue(test_node.get_attribute_exists("outputs:a_texcoord2d")) attribute = test_node.get_attribute("outputs:a_texcoord2d") db_value = database.outputs.a_texcoord2d self.assertTrue(test_node.get_attribute_exists("outputs:a_texcoord2f")) attribute = test_node.get_attribute("outputs:a_texcoord2f") db_value = database.outputs.a_texcoord2f self.assertTrue(test_node.get_attribute_exists("outputs:a_texcoord2h")) attribute = test_node.get_attribute("outputs:a_texcoord2h") db_value = database.outputs.a_texcoord2h self.assertTrue(test_node.get_attribute_exists("outputs:a_texcoord3d")) attribute = test_node.get_attribute("outputs:a_texcoord3d") db_value = database.outputs.a_texcoord3d self.assertTrue(test_node.get_attribute_exists("outputs:a_texcoord3f")) attribute = test_node.get_attribute("outputs:a_texcoord3f") db_value = database.outputs.a_texcoord3f self.assertTrue(test_node.get_attribute_exists("outputs:a_texcoord3h")) attribute = test_node.get_attribute("outputs:a_texcoord3h") db_value = database.outputs.a_texcoord3h self.assertTrue(test_node.get_attribute_exists("outputs:a_timecode")) attribute = test_node.get_attribute("outputs:a_timecode") db_value = database.outputs.a_timecode self.assertTrue(test_node.get_attribute_exists("outputs:a_vector3d")) attribute = test_node.get_attribute("outputs:a_vector3d") db_value = database.outputs.a_vector3d self.assertTrue(test_node.get_attribute_exists("outputs:a_vector3f")) attribute = test_node.get_attribute("outputs:a_vector3f") db_value = database.outputs.a_vector3f self.assertTrue(test_node.get_attribute_exists("outputs:a_vector3h")) attribute = test_node.get_attribute("outputs:a_vector3h") db_value = database.outputs.a_vector3h
25,764
Python
52.123711
197
0.662669
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCpuGpuExtendedPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCpuGpuExtendedPyDatabase import OgnTutorialCpuGpuExtendedPyDatabase test_file_name = "OgnTutorialCpuGpuExtendedPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CpuGpuExtendedPy") database = OgnTutorialCpuGpuExtendedPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:gpu")) attribute = test_node.get_attribute("inputs:gpu") db_value = database.inputs.gpu expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
1,984
Python
49.897435
116
0.708165
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialDefaults.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'outputs': [ ['outputs:a_bool', False, False], ['outputs:a_double', 0.0, False], ['outputs:a_float', 0.0, False], ['outputs:a_half', 0.0, False], ['outputs:a_int', 0, False], ['outputs:a_int64', 0, False], ['outputs:a_string', "", False], ['outputs:a_token', "", False], ['outputs:a_uchar', 0, False], ['outputs:a_uint', 0, False], ['outputs:a_uint64', 0, False], ['outputs:a_int2', [0, 0], False], ['outputs:a_matrix', [1.0, 0.0, 0.0, 1.0], False], ['outputs:a_array', [], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_Defaults", "omni.graph.tutorials.Defaults", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.Defaults User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_Defaults","omni.graph.tutorials.Defaults", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.Defaults User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_Defaults", "omni.graph.tutorials.Defaults", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.Defaults User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialDefaultsDatabase import OgnTutorialDefaultsDatabase test_file_name = "OgnTutorialDefaultsTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_Defaults") database = OgnTutorialDefaultsDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a_array")) attribute = test_node.get_attribute("inputs:a_array") db_value = database.inputs.a_array expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_bool")) attribute = test_node.get_attribute("inputs:a_bool") db_value = database.inputs.a_bool expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_double")) attribute = test_node.get_attribute("inputs:a_double") db_value = database.inputs.a_double expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_float")) attribute = test_node.get_attribute("inputs:a_float") db_value = database.inputs.a_float expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_half")) attribute = test_node.get_attribute("inputs:a_half") db_value = database.inputs.a_half expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_int")) attribute = test_node.get_attribute("inputs:a_int") db_value = database.inputs.a_int expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_int2")) attribute = test_node.get_attribute("inputs:a_int2") db_value = database.inputs.a_int2 expected_value = [0, 0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_int64")) attribute = test_node.get_attribute("inputs:a_int64") db_value = database.inputs.a_int64 expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_matrix")) attribute = test_node.get_attribute("inputs:a_matrix") db_value = database.inputs.a_matrix expected_value = [[1.0, 0.0], [0.0, 1.0]] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_string")) attribute = test_node.get_attribute("inputs:a_string") db_value = database.inputs.a_string expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_token")) attribute = test_node.get_attribute("inputs:a_token") db_value = database.inputs.a_token expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_uchar")) attribute = test_node.get_attribute("inputs:a_uchar") db_value = database.inputs.a_uchar expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_uint")) attribute = test_node.get_attribute("inputs:a_uint") db_value = database.inputs.a_uint expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_uint64")) attribute = test_node.get_attribute("inputs:a_uint64") db_value = database.inputs.a_uint64 expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:a_array")) attribute = test_node.get_attribute("outputs:a_array") db_value = database.outputs.a_array self.assertTrue(test_node.get_attribute_exists("outputs:a_bool")) attribute = test_node.get_attribute("outputs:a_bool") db_value = database.outputs.a_bool self.assertTrue(test_node.get_attribute_exists("outputs:a_double")) attribute = test_node.get_attribute("outputs:a_double") db_value = database.outputs.a_double self.assertTrue(test_node.get_attribute_exists("outputs:a_float")) attribute = test_node.get_attribute("outputs:a_float") db_value = database.outputs.a_float self.assertTrue(test_node.get_attribute_exists("outputs:a_half")) attribute = test_node.get_attribute("outputs:a_half") db_value = database.outputs.a_half self.assertTrue(test_node.get_attribute_exists("outputs:a_int")) attribute = test_node.get_attribute("outputs:a_int") db_value = database.outputs.a_int self.assertTrue(test_node.get_attribute_exists("outputs:a_int2")) attribute = test_node.get_attribute("outputs:a_int2") db_value = database.outputs.a_int2 self.assertTrue(test_node.get_attribute_exists("outputs:a_int64")) attribute = test_node.get_attribute("outputs:a_int64") db_value = database.outputs.a_int64 self.assertTrue(test_node.get_attribute_exists("outputs:a_matrix")) attribute = test_node.get_attribute("outputs:a_matrix") db_value = database.outputs.a_matrix self.assertTrue(test_node.get_attribute_exists("outputs:a_string")) attribute = test_node.get_attribute("outputs:a_string") db_value = database.outputs.a_string self.assertTrue(test_node.get_attribute_exists("outputs:a_token")) attribute = test_node.get_attribute("outputs:a_token") db_value = database.outputs.a_token self.assertTrue(test_node.get_attribute_exists("outputs:a_uchar")) attribute = test_node.get_attribute("outputs:a_uchar") db_value = database.outputs.a_uchar self.assertTrue(test_node.get_attribute_exists("outputs:a_uint")) attribute = test_node.get_attribute("outputs:a_uint") db_value = database.outputs.a_uint self.assertTrue(test_node.get_attribute_exists("outputs:a_uint64")) attribute = test_node.get_attribute("outputs:a_uint64") db_value = database.outputs.a_uint64
12,650
Python
47.84556
197
0.686087
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialBundleAddAttributes.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialBundleAddAttributesDatabase import OgnTutorialBundleAddAttributesDatabase test_file_name = "OgnTutorialBundleAddAttributesTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_BundleAddAttributes") database = OgnTutorialBundleAddAttributesDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:addedAttributeNames")) attribute = test_node.get_attribute("inputs:addedAttributeNames") db_value = database.inputs.addedAttributeNames expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:removedAttributeNames")) attribute = test_node.get_attribute("inputs:removedAttributeNames") db_value = database.inputs.removedAttributeNames expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:typesToAdd")) attribute = test_node.get_attribute("inputs:typesToAdd") db_value = database.inputs.typesToAdd expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:useBatchedAPI")) attribute = test_node.get_attribute("inputs:useBatchedAPI") db_value = database.inputs.useBatchedAPI expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs_bundle")) attribute = test_node.get_attribute("outputs_bundle") db_value = database.outputs.bundle
3,589
Python
52.582089
122
0.706604
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialState.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:overrideValue', 555, False], ['inputs:override', True, False], ], 'outputs': [ ['outputs:monotonic', 555, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_State", "omni.graph.tutorials.State", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.State User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_State","omni.graph.tutorials.State", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.State User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_State", "omni.graph.tutorials.State", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.State User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialStateDatabase import OgnTutorialStateDatabase test_file_name = "OgnTutorialStateTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_State") database = OgnTutorialStateDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:override")) attribute = test_node.get_attribute("inputs:override") db_value = database.inputs.override expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:overrideValue")) attribute = test_node.get_attribute("inputs:overrideValue") db_value = database.inputs.overrideValue expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:monotonic")) attribute = test_node.get_attribute("outputs:monotonic") db_value = database.outputs.monotonic
5,064
Python
48.656862
191
0.671801
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/_impl/extension.py
"""Support required by the Carbonite extension loader""" import omni.ext from ..bindings._omni_graph_tutorials import acquire_interface as _acquire_interface # noqa: PLE0402 from ..bindings._omni_graph_tutorials import release_interface as _release_interface # noqa: PLE0402 class _PublicExtension(omni.ext.IExt): """Object that tracks the lifetime of the Python part of the extension loading""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__interface = None def on_startup(self): """Set up initial conditions for the Python part of the extension""" self.__interface = _acquire_interface() def on_shutdown(self): """Shutting down this part of the extension prepares it for hot reload""" if self.__interface is not None: _release_interface(self.__interface) self.__interface = None
909
Python
36.916665
101
0.671067
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_omnigraph_python_interface.py
"""Basic tests of the Python interface to C++ nodes generated from a .ogn file""" import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.tutorials.ogn.OgnTutorialSimpleDataDatabase import OgnTutorialSimpleDataDatabase # ====================================================================== class TestOmniGraphPythonInterface(ogts.OmniGraphTestCase): """Run a simple unit test that exercises generated Python interface functionality""" # ---------------------------------------------------------------------- async def test_setting_in_ogn_python_api(self): """Test ability to set inputs on a node and retrieve them""" (_, [simple_node], _, _) = og.Controller.edit( "/TestGraph", { og.Controller.Keys.CREATE_NODES: ("PyTest_SimpleNode", "omni.graph.tutorials.SimpleData"), }, ) await og.Controller.evaluate() interface = OgnTutorialSimpleDataDatabase(simple_node) # Set input values through the database interface interface.inputs.a_bool = False interface.inputs.a_half = 2.0 interface.inputs.a_int = 3 interface.inputs.a_int64 = 4 interface.inputs.a_float = 5.0 interface.inputs.a_double = 6.0 # interface.inputs.a_token = "hello" interface.inputs.unsigned_a_uchar = 7 interface.inputs.unsigned_a_uint = 8 interface.inputs.unsigned_a_uint64 = 9 # Run the node's compute method await og.Controller.evaluate() # Retrieve output values from the database interface and verify against expected values self.assertEqual(interface.outputs.a_bool, True) self.assertAlmostEqual(interface.outputs.a_half, 3.0) self.assertEqual(interface.outputs.a_int, 4) self.assertEqual(interface.outputs.a_int64, 5) self.assertAlmostEqual(interface.outputs.a_float, 6.0) self.assertAlmostEqual(interface.outputs.a_double, 7.0) # self.assertEqual(interface.outputs.a_token, "world") self.assertEqual(interface.outputs.unsigned_a_uchar, 8) self.assertEqual(interface.outputs.unsigned_a_uint, 9) self.assertEqual(interface.outputs.unsigned_a_uint64, 10) # ---------------------------------------------------------------------- async def test_check_has_state(self): """Test ability to correctly determine if a node has marked itself as having internal state""" stateless_node_type = og.get_node_type("omni.graph.tutorials.SimpleData") stateful_node_type = og.get_node_type("omni.graph.tutorials.StatePy") self.assertFalse(stateless_node_type.has_state()) self.assertTrue(stateful_node_type.has_state())
2,753
Python
46.482758
106
0.625499
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_api.py
"""Testing the stability of the API in this module""" import omni.graph.core.tests as ogts import omni.graph.tutorials as ogtu from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents # ====================================================================== class _TestOmniGraphTutorialsApi(ogts.OmniGraphTestCase): _UNPUBLISHED = ["bindings", "ogn", "tests"] async def test_api(self): _check_module_api_consistency(ogtu, self._UNPUBLISHED) # noqa: PLW0212 _check_module_api_consistency(ogtu.tests, is_test_module=True) # noqa: PLW0212 async def test_api_features(self): """Test that the known public API features continue to exist""" _check_public_api_contents(ogtu, [], self._UNPUBLISHED, only_expected_allowed=True) # noqa: PLW0212 _check_public_api_contents(ogtu.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
936
Python
48.315787
108
0.65812
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/__init__.py
"""There is no public API to this module.""" __all__ = [] scan_for_test_modules = True """The presence of this object causes the test runner to automatically scan the directory for unit test cases"""
201
Python
32.666661
112
0.716418
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_tutorial_extended_types.py
""" Tests for the omni.graph.tutorials.ExtendedTypes and omni.graph.tutorials.ExtendedTypesPy nodes """ import omni.graph.core as og import omni.graph.core.tests as ogts class TestTutorialExtendedTypes(ogts.OmniGraphTestCase): """Extended attribute type tests require multiple nodes, not supported in the .ogn test framework""" # ---------------------------------------------------------------------- async def _test_tutorial_extended_attributes_node(self, test_node_type_name: str): """Test basic operation of the tutorial node containing extended attributes""" # Set up a graph that creates full type resolution for simple and array types of the extended attribute node # # SimpleIn ----=> Extended1 ----=> SimpleOut # \ / \ / # X X # / \ / \ # ArrayIn ----=> Extended2 ----=> ArrayOut # keys = og.Controller.Keys (_, [simple_node, _, extended_node_1, extended_node_2, array_node, _], _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("SimpleIn", "omni.graph.tutorials.SimpleData"), ("SimpleOut", "omni.graph.tutorials.SimpleData"), ("Extended1", test_node_type_name), ("Extended2", test_node_type_name), ("ArrayIn", "omni.graph.tutorials.ArrayData"), ("ArrayOut", "omni.graph.tutorials.ArrayData"), ], keys.CONNECT: [ ("SimpleIn.outputs:a_float", "Extended1.inputs:floatOrToken"), ("Extended1.outputs:doubledResult", "SimpleOut.inputs:a_float"), ("ArrayIn.outputs:result", "Extended1.inputs:toNegate"), ("Extended1.outputs:negatedResult", "ArrayOut.inputs:original"), ("SimpleIn.outputs:a_token", "Extended2.inputs:floatOrToken"), ("Extended2.outputs:doubledResult", "SimpleOut.inputs:a_token"), ("ArrayIn.outputs:negativeValues", "Extended2.inputs:toNegate"), ("Extended2.outputs:negatedResult", "ArrayOut.inputs:gates"), ], keys.SET_VALUES: [ ("SimpleIn.inputs:a_float", 5.0), ("SimpleIn.inputs:a_token", "hello"), ("ArrayIn.inputs:multiplier", 2.0), ("ArrayIn.inputs:original", [5.0, -6.0]), ("ArrayIn.inputs:gates", [False, True]), ], }, ) await og.Controller.evaluate() # Check that the inputs into the extended type nodes are correct self.assertEqual(6.0, og.Controller.get(("outputs:a_float", simple_node))) self.assertEqual("world", og.Controller.get(("outputs:a_token", simple_node))) self.assertCountEqual([5.0, -12.0], og.Controller.get(("outputs:result", array_node))) self.assertCountEqual([False, True], og.Controller.get(("outputs:negativeValues", array_node))) # Check the extended simple value outputs self.assertEqual(12.0, og.Controller.get(("outputs:doubledResult", extended_node_1))) self.assertEqual("worldworld", og.Controller.get(("outputs:doubledResult", extended_node_2))) # Check the extended array value outputs self.assertCountEqual([-5.0, 12.0], og.Controller.get(("outputs:negatedResult", extended_node_1))) self.assertCountEqual([True, False], og.Controller.get(("outputs:negatedResult", extended_node_2))) # ---------------------------------------------------------------------- async def test_tutorial_extended_attributes_node_cpp(self): """Test basic operation of the C++ tutorial node containing extended attributes.""" await self._test_tutorial_extended_attributes_node("omni.graph.tutorials.ExtendedTypes") # ---------------------------------------------------------------------- async def test_tutorial_extended_attributes_node_python(self): """Test basic operation of the Python tutorial node containing extended attributes.""" await self._test_tutorial_extended_attributes_node("omni.graph.tutorials.ExtendedTypesPy") # ---------------------------------------------------------------------- async def _test_tutorial_extended_attributes_tuples(self, test_node_type_name: str): """Test basic operation of the tutorial node containing extended attributes on its tuple-accepting attributes""" # Set up a graph that creates full type resolution for the tuple types of the extended attribute node with # two different resolved types. # keys = og.Controller.Keys ( _, [tuple_node, _, extended_node_1, extended_node_2, tuple_array_node, _, simple_node, _], _, _, ) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("TupleIn", "omni.tutorials.TupleData"), ("TupleOut", "omni.tutorials.TupleData"), ("Extended1", test_node_type_name), ("Extended2", test_node_type_name), ("TupleArrayIn", "omni.graph.tutorials.TupleArrays"), ("TupleArrayOut", "omni.graph.tutorials.TupleArrays"), ("SimpleIn", "omni.graph.tutorials.SimpleData"), ("SimpleOut", "omni.graph.tutorials.SimpleData"), ], keys.CONNECT: [ ("TupleIn.outputs:a_int2", "Extended1.inputs:tuple"), ("Extended1.outputs:tuple", "TupleOut.inputs:a_int2"), ("TupleArrayIn.inputs:a", "Extended1.inputs:flexible"), ("Extended1.outputs:flexible", "TupleArrayOut.inputs:a"), ("TupleIn.outputs:a_float3", "Extended2.inputs:tuple"), ("Extended2.outputs:tuple", "TupleOut.inputs:a_float3"), ("SimpleIn.outputs:a_token", "Extended2.inputs:flexible"), ("Extended2.outputs:flexible", "SimpleOut.inputs:a_token"), ], keys.SET_VALUES: [ ("TupleIn.inputs:a_int2", [4, 2]), ("TupleIn.inputs:a_float3", (4.0, 10.0, 2.0)), ("TupleArrayIn.inputs:a", [[2.0, 3.0, 7.0], [21.0, 14.0, 6.0]]), ("TupleArrayIn.inputs:b", [[21.0, 14.0, 6.0], [2.0, 3.0, 7.0]]), ("SimpleIn.inputs:a_token", "hello"), ], }, ) await og.Controller.evaluate() # Check that the inputs into the extended type nodes are correct self.assertEqual("world", og.Controller.get(("outputs:a_token", simple_node))) self.assertCountEqual([5, 3], og.Controller.get(("outputs:a_int2", tuple_node))) self.assertCountEqual([5.0, 11.0, 3.0], og.Controller.get(("outputs:a_float3", tuple_node))) self.assertCountEqual([126.0, 126.0], og.Controller.get(("outputs:result", tuple_array_node))) # Check the resulting values from resolving the "any" type to tuples self.assertCountEqual([-5, -3], og.Controller.get(("outputs:tuple", extended_node_1))) self.assertCountEqual([-5.0, -11.0, -3.0], og.Controller.get(("outputs:tuple", extended_node_2))) # Check the resulting values from resolving the flexible type as both of its types self.assertEqual("dlrow", og.Controller.get(("outputs:flexible", extended_node_2))) list_expected = [[-2.0, -3.0, -7.0], [-21.0, -14.0, -6.0]] list_computed = og.Controller.get(("outputs:flexible", extended_node_1)) for expected, computed in zip(list_expected, list_computed): self.assertCountEqual(expected, computed) # ---------------------------------------------------------------------- async def test_tutorial_extended_attributes_tuples_cpp(self): """Test basic operation of the C++ tutorial node containing extended attributes.""" await self._test_tutorial_extended_attributes_tuples("omni.graph.tutorials.ExtendedTypes") # ---------------------------------------------------------------------- async def test_tutorial_extended_attributes_tuples_python(self): """Test basic operation of the Python tutorial node containing extended attributes.""" await self._test_tutorial_extended_attributes_tuples("omni.graph.tutorials.ExtendedTypesPy")
8,633
Python
55.431372
120
0.554269
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_omnigraph_deletion.py
"""OmniGraph deletion tests""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.usd class TestOmniGraphDeletion(ogts.OmniGraphTestCase): # In these tests, we test various aspects of deleting things from OG async def test_omnigraph_usd_deletion(self): # In this test we set up 2 very similar looking nodes: # /new_node and /new_node_01. We then delete /new_node # The idea is that this looks very similar to cases like # /parent/path/stuff/mynode where we delete /parent/path # In that case we want to delete mynode, but in our case # we do not want to delete /new_node_01 when /new_node is # deleted. keys = og.Controller.Keys (graph, [new_node, new_node_01], _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("new_node", "omni.graph.tutorials.Empty"), ("new_node_01", "omni.graph.tutorials.Empty"), ] }, ) await og.Controller.evaluate() self.assertIsNotNone(new_node_01) self.assertTrue(new_node_01.is_valid()) self.assertIsNotNone(new_node) self.assertTrue(new_node.is_valid()) og.Controller.delete_node(new_node) new_node_01 = graph.get_node("/TestGraph/new_node_01") self.assertIsNotNone(new_node_01) self.assertTrue(new_node_01.is_valid()) new_node = graph.get_node("/TestGraph/new_node") self.assertTrue(not new_node.is_valid()) omni.kit.undo.undo() new_node_01 = graph.get_node("/TestGraph/new_node_01") self.assertIsNotNone(new_node_01) self.assertTrue(new_node_01.is_valid()) new_node = graph.get_node("/TestGraph/new_node") self.assertIsNotNone(new_node) self.assertTrue(new_node.is_valid()) # -------------------------------------------------------------------------------------------------------------- async def test_fabric_dangling_connections(self): # In this test we create two nodes, connect them together. The output of the first node drives the input # of the second node. When we break the connection, we need to verify that the output of the second node # now takes its input from its own value, rather than the connected value (ie. the connection is actually # broken in the fabric). keys = og.Controller.Keys (graph, [node_a, node_b], _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("node_a", "omni.graph.tutorials.SimpleData"), ("node_b", "omni.graph.tutorials.SimpleData"), ] }, ) await og.Controller.evaluate() node_a = graph.get_node("/TestGraph/node_a") self.assertIsNotNone(node_a) self.assertTrue(node_a.is_valid()) node_b = graph.get_node("/TestGraph/node_b") self.assertIsNotNone(node_b) self.assertTrue(node_b.is_valid()) upstream_attr = node_a.get_attribute("outputs:a_int") downstream_attr = node_b.get_attribute("inputs:a_int") og.Controller.connect(upstream_attr, downstream_attr) await og.Controller.evaluate() # This node "omni.graph.tutorials.SimpleData" add 1 to the input. The default value of a_int is 0, so the output # of the first node is 1. When this is used as the input to the second node, we expect the value to be 2: value = og.Controller.get(node_b.get_attribute("outputs:a_int")) self.assertEqual(value, 2) og.Controller.disconnect(upstream_attr, downstream_attr) await og.Controller.evaluate() # Now that the connection is broken, the value should now be 1. However, if it didn't actually break the # connection in the fabric, the graph would still "think" it's connected and output 2. value = og.Controller.get(node_b.get_attribute("outputs:a_int")) self.assertEqual(value, 1)
4,140
Python
42.135416
120
0.602657
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_tutorial_state.py
""" Tests for the omnigraph.tutorial.state node """ import omni.graph.core as og import omni.graph.core.tests as ogts class TestTutorialState(ogts.OmniGraphTestCase): """.ogn tests only run once while state tests require multiple evaluations, handled here""" # ---------------------------------------------------------------------- async def test_tutorial_state_node(self): """Test basic operation of the tutorial node containing internal node state""" self.assertTrue(og.get_node_type("omni.graph.tutorials.State").has_state(), "Tutorial state node has state") # Create a set of state nodes, updating after each one so that the state information is properly initialized. # If that requirement weren't there this would just be done in one call. state_nodes = [] for index in range(5): (graph, new_nodes, _, _) = og.Controller.edit( "/StateGraph", { og.Controller.Keys.CREATE_NODES: [ (f"State{index}", "omni.graph.tutorials.State"), ] }, ) state_nodes.append(new_nodes[0]) await og.Controller.evaluate(graph) output_attrs = [state_node.get_attribute("outputs:monotonic") for state_node in state_nodes] output_values = [og.Controller(output_attr).get() for output_attr in output_attrs] for i in range(len(output_values) - 1): self.assertLess(output_values[i], output_values[i + 1], "Comparing state of other nodes") await og.Controller.evaluate(graph) new_values = [og.Controller(output_attr).get() for output_attr in output_attrs] for i in range(len(new_values) - 1): self.assertLess(new_values[i], new_values[i + 1], "Comparing second state of other nodes") for i, new_value in enumerate(new_values): self.assertLess(output_values[i], new_value, "Comparing node state updates")
1,998
Python
45.488371
117
0.605105
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_tutorial_state_attributes_py.py
""" Tests for the omnigraph.tutorial.stateAttributesPy node """ import omni.graph.core as og import omni.graph.core.tests as ogts class TestTutorialStateAttributesPy(ogts.OmniGraphTestCase): """.ogn tests only run once while state tests require multiple evaluations, handled here""" # ---------------------------------------------------------------------- async def test_tutorial_state_attributes_py_node(self): """Test basic operation of the Python tutorial node containing state attributes""" keys = og.Controller.Keys (_, [state_node], _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: ("StateNode", "omni.graph.tutorials.StateAttributesPy"), keys.SET_VALUES: ("StateNode.state:reset", True), }, ) await og.Controller.evaluate() reset_attr = og.Controller.attribute("state:reset", state_node) monotonic_attr = og.Controller.attribute("state:monotonic", state_node) self.assertEqual(og.Controller.get(reset_attr), False, "Reset attribute set back to False") self.assertEqual(og.Controller.get(monotonic_attr), 0, "Monotonic attribute reset to start") await og.Controller.evaluate() self.assertEqual(og.Controller.get(reset_attr), False, "Reset attribute still False") self.assertEqual(og.Controller.get(monotonic_attr), 1, "Monotonic attribute incremented once") await og.Controller.evaluate() self.assertEqual(og.Controller.get(monotonic_attr), 2, "Monotonic attribute incremented twice") og.Controller.set(reset_attr, True) await og.Controller.evaluate() self.assertEqual(og.Controller.get(reset_attr), False, "Reset again set back to False") self.assertEqual(og.Controller.get(monotonic_attr), 0, "Monotonic attribute again reset to start")
1,890
Python
46.274999
106
0.655026
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_omnigraph_bundles.py
""" Tests for attribute bundles """ import unittest from contextlib import suppress from typing import Any, List, Tuple import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.nodes.tests as ognts import omni.graph.tools as ogt from omni.kit.test.teamcity import is_running_in_teamcity from pxr import Gf # ============================================================================================================== def multiply_elements(multiplier, original: Any) -> Any: """Take in a numeric value, tuple, list, tuple of tuples, etc. and multiply every element by a constant""" if isinstance(original, tuple): return tuple(multiply_elements(multiplier, element) for element in original) if isinstance(original, list): return tuple(multiply_elements(multiplier, element) for element in original) return multiplier * original # ============================================================================================================== def as_tuple(value: Any) -> Tuple: """Return the value, interpreted as a tuple (except simple values, which are returned as themselves)""" if isinstance(value, tuple): return value if isinstance(value, list): return tuple(value) if isinstance(value, (Gf.Quatd, Gf.Quatf, Gf.Quath)): return (*value.GetImaginary(), value.GetReal()) if isinstance(value, Gf.Matrix4d): return tuple(tuple(element for element in list(row)) for row in value) with suppress(TypeError): if len(value) > 1: return tuple(value) return value # ============================================================================================================== class TestOmniGraphBundles(ogts.OmniGraphTestCase): """Attribute bundles do not yet have the ability to log tests directly in a .ogn file so it's done here""" # -------------------------------------------------------------------------------------------------------------- def _compare_results(self, expected_raw: Any, actual_raw: Any, test_info: str): """Loose comparison of two types of compatible values Args: expected_raw: Expected results. Can be simple values, tuples, lists, or pxr.Gf types actual_raw: Actual results. Can be simple values, tuples, lists, or pxr.Gf types test_info: String to accompany error messages Returns: Error encountered when mismatched values found, None if everything matched """ expected = as_tuple(expected_raw) actual = as_tuple(actual_raw) self.assertEqual( type(expected), type(actual), f"{test_info} Mismatched types - expected {expected_raw}, got {actual_raw}" ) if isinstance(expected, tuple): for expected_element, actual_element in zip(expected, actual): self._compare_results(expected_element, actual_element, test_info) else: self.assertEqual(expected, actual, f"{test_info} Expected {expected}, got {actual}") # ---------------------------------------------------------------------- async def _test_bundle_contents(self, node_type_to_test: str): """Test access to bundle attribute manipulation for C++ and Python implementations""" keys = og.Controller.Keys (graph, [bundle_node, inspector_node, _, _], [_, filtered_prim], _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("BundleManipulator", node_type_to_test), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CREATE_PRIMS: [ ("FullPrim", {"fullInt": ("int", 2), "floatArray": ("float[]", [3.0, 4.0, 5.0])}), ( "FilteredPrim", { "int_1": ("int", 6), "uint_1": ("uint", 7), "int64_x": ("int64", 8), "uint64_1": ("uint64", 9), "int_3": ("int[3]", (10, 11, 12)), "int_array": ("int[]", [13, 14, 15]), "float_1": ("float", 3.0), "double_x": ("double", 4.0), "big_int": ("int[]", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), }, ), ], keys.EXPOSE_PRIMS: [ (og.Controller.PrimExposureType.AS_BUNDLE, "/FullPrim", "FullPrimExtract"), (og.Controller.PrimExposureType.AS_BUNDLE, "/FilteredPrim", "FilteredPrimExtract"), ], keys.CONNECT: [ ("FullPrimExtract.outputs_primBundle", "BundleManipulator.inputs:fullBundle"), ("FilteredPrimExtract.outputs_primBundle", "BundleManipulator.inputs:filteredBundle"), ("BundleManipulator.outputs_combinedBundle", "Inspector.inputs:bundle"), ], }, ) _ = ogt.OGN_DEBUG and ognts.enable_debugging(inspector_node) await og.Controller.evaluate() expected_results = { "big_int": ("int", 1, 1, "none", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), "int_1": ("int", 1, 0, "none", 6), "uint_1": ("uint", 1, 0, "none", 7), "int64_x": ("int64", 1, 0, "none", 8), "uint64_1": ("uint64", 1, 0, "none", 9), "int_3": ("int", 3, 0, "none", (10, 11, 12)), "int_array": ("int", 1, 1, "none", [13, 14, 15]), "float_1": ("float", 1, 0, "none", 3.0), "double_x": ("double", 1, 0, "none", 4.0), "fullInt": ("int", 1, 0, "none", 2), "floatArray": ("float", 1, 1, "none", [3.0, 4.0, 5.0]), "sourcePrimPath": ("token", 1, 0, "none", str(filtered_prim.GetPrimPath())), "sourcePrimType": ("token", 1, 0, "none", str(filtered_prim.GetTypeName())), } def __result_subset(elements_removed: List[str]): """Return the set of results with the index list of elements removed""" return {key: value for key, value in expected_results.items() if key not in elements_removed} # Test data consists of a list of individual test configurations with the filters to set and the # expected contents of the output bundle using those filters. test_data = [ ([], expected_results), (["x"], __result_subset(["int64_x", "double_x"])), (["int"], __result_subset(["big_int", "int_1", "uint_1", "int64_x", "uint64_1", "int_3", "int_array"])), (["big"], __result_subset(["big_int"])), ( ["x", "big", "int"], __result_subset( ["big_int", "int_1", "uint_1", "int64_x", "uint64_1", "int_3", "int_array", "double_x"] ), ), ] for (filters, expected_results) in test_data: og.Controller.edit( graph, { keys.SET_VALUES: (("inputs:filters", bundle_node), filters), }, ) await og.Controller.evaluate() try: ognts.verify_bundles_are_equal( ognts.filter_bundle_inspector_results( ognts.bundle_inspector_results(inspector_node), [], filter_for_inclusion=False ), ognts.filter_bundle_inspector_results( (len(expected_results), expected_results), [], filter_for_inclusion=False ), ) except ValueError as error: self.assertTrue(False, error) # ---------------------------------------------------------------------- async def test_bundle_contents_cpp(self): """Test access to bundle attribute manipulation on the C++ implemented node""" await self._test_bundle_contents("omni.graph.tutorials.BundleManipulation") # ---------------------------------------------------------------------- async def test_bundle_contents_py(self): """Test bundle attribute manipulation on the Python implemented node""" await self._test_bundle_contents("omni.graph.tutorials.BundleManipulationPy") # ---------------------------------------------------------------------- async def _test_simple_bundled_data(self, node_type_to_test: str): """Test access to attributes with simple data types within bundles for both C++ and Python implementations""" controller = og.Controller() keys = og.Controller.Keys prim_definition = ognts.prim_with_everything_definition() (_, [_, inspector_node, _], _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("BundledDataModifier", node_type_to_test), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CREATE_PRIMS: ("TestPrim", prim_definition), keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "TestPrim", "TestBundle"), keys.CONNECT: [ ("TestBundle.outputs_primBundle", "BundledDataModifier.inputs:bundle"), ("BundledDataModifier.outputs_bundle", "Inspector.inputs:bundle"), ], }, ) _ = ogt.OGN_DEBUG and ognts.enable_debugging(inspector_node) await controller.evaluate() (bundled_count, bundled_results) = ognts.bundle_inspector_results(inspector_node) # Prim will not have the "sourcePrimXX" attributes so it is smaller by 2 self.assertEqual(len(prim_definition) + 2, bundled_count) for name, (ogn_type, array_depth, tuple_count, role, actual_output) in bundled_results.items(): if name in ["sourcePrimType", "sourcePrimPath"]: continue if not node_type_to_test.endswith("Py") and ogn_type not in ["int", "int64", "uint", "uint64"]: # The C++ node only handles integer types, in the interest of brevity continue test_info = "Bundled" if tuple_count > 1: test_info += f" tuple[{tuple_count}]" if array_depth > 0: test_info += " array" test_info += f" attribute {name} of type {ogn_type}" if role != "none": test_info += f" (role {role})" if ogn_type == "token" or role == "text": expected_output = prim_definition[name][1] if isinstance(expected_output, str): expected_output += expected_output else: expected_output = [f"{element}{element}" for element in expected_output] self._compare_results(expected_output, actual_output, test_info) else: if ogn_type in ["bool", "bool[]"]: expected_output = as_tuple(prim_definition[name][1]) else: expected_output = multiply_elements(2, as_tuple(prim_definition[name][1])) self._compare_results(expected_output, actual_output, test_info) # ---------------------------------------------------------------------- async def test_simple_bundled_data_cpp(self): """Test access to attributes with simple data types within bundles on the C++ implemented node""" await self._test_simple_bundled_data("omni.graph.tutorials.BundleData") # ---------------------------------------------------------------------- async def test_simple_bundled_data_py(self): """Test access to attributes with simple data types within bundles on the Python implemented node""" await self._test_simple_bundled_data("omni.graph.tutorials.BundleDataPy") # ---------------------------------------------------------------------- async def _test_add_attributes_to_bundle(self, node_type_to_test: str): """Test basic operation of the tutorial node that adds new attributes to a bundle""" keys = og.Controller.Keys (graph, [add_node, inspector_node], _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("AddAttributes", node_type_to_test), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CONNECT: ("AddAttributes.outputs_bundle", "Inspector.inputs:bundle"), }, ) await og.Controller.evaluate() types_attribute = og.Controller.attribute("inputs:typesToAdd", add_node) added_names_attribute = og.Controller.attribute("inputs:addedAttributeNames", add_node) removed_names_attribute = og.Controller.attribute("inputs:removedAttributeNames", add_node) _ = ogt.OGN_DEBUG and ognts.enable_debugging(inspector_node) # List of test data configurations to run. The individual test entries consist of: # - list of the types for the attributes to be added # - list of the base types corresponding to the main types # - list of names for the attributes to be added # - list of values expected for the new bundle as (count, roles, arrayDepths, tupleCounts, values) test_data = [ [ ["float", "double", "int", "int64", "uchar", "uint", "uint64", "bool", "token"], ["float", "double", "int", "int64", "uchar", "uint", "uint64", "bool", "token"], [f"output{n}" for n in range(9)], (9, ["none"] * 9, [0] * 9, [1] * 9, [0.0, 0.0, 0, 0, 0, 0, 0, False, ""]), ], [ ["float[]", "double[]", "int[]", "int64[]", "uchar[]", "uint[]", "uint64[]", "token[]"], ["float", "double", "int", "int64", "uchar", "uint", "uint64", "token"], [f"output{n}" for n in range(8)], (8, ["none"] * 8, [1] * 8, [1] * 8, [[], [], [], [], [], [], [], []]), ], [ ["float[3]", "double[2]", "int[4]"], ["float", "double", "int"], [f"output{n}" for n in range(3)], (3, ["none"] * 3, [0] * 3, [3, 2, 4], [[0.0, 0.0, 0.0], [0.0, 0.0], [0, 0, 0, 0]]), ], [ ["float[3][]", "double[2][]", "int[4][]"], ["float", "double", "int"], [f"output{n}" for n in range(3)], (3, ["none"] * 3, [1] * 3, [3, 2, 4], [[], [], []]), ], [ ["any"], ["token"], ["output0"], (1, ["none"], [0], [1], [""]), ], [ ["colord[3]", "colorf[4]", "colorh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["color"] * 3, [0] * 3, [3, 4, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["normald[3]", "normalf[3]", "normalh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["normal"] * 3, [0] * 3, [3, 3, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["pointd[3]", "pointf[3]", "pointh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["point"] * 3, [0] * 3, [3, 3, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["quatd[4]", "quatf[4]", "quath[4]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], ( 3, ["quat"] * 3, [0] * 3, [4, 4, 4], [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], ), ], [ ["texcoordd[3]", "texcoordf[2]", "texcoordh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["texcoord"] * 3, [0] * 3, [3, 2, 3], [[0.0, 0.0, 0.0], [0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["vectord[3]", "vectorf[3]", "vectorh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["vector"] * 3, [0] * 3, [3, 3, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["timecode"], ["double"], ["output0"], (1, ["timecode"], [0], [1], [0.0]), ], ] for (types, base_types, names, results) in test_data: og.Controller.edit( graph, { keys.SET_VALUES: [ (types_attribute, types), (added_names_attribute, names), ] }, ) await og.Controller.evaluate() (bundled_count, bundled_results) = ognts.bundle_inspector_results(inspector_node) self.assertEqual(bundled_count, results[0]) self.assertCountEqual(list(bundled_results.keys()), names) for index, name in enumerate(names): error = f"Checking {{}} for attribute {name}" named_results = bundled_results[name] self.assertEqual( named_results[ognts.BundleResultKeys.TYPE_IDX], base_types[index], error.format("type") ) self.assertEqual( named_results[ognts.BundleResultKeys.ARRAY_DEPTH_IDX], results[2][index], error.format("array depth"), ) self.assertEqual( named_results[ognts.BundleResultKeys.TUPLE_COUNT_IDX], results[3][index], error.format("tuple count"), ) self.assertEqual( named_results[ognts.BundleResultKeys.ROLE_IDX], results[1][index], error.format("role") ) # One final test run that also includes a remove of the 2nd, 4th, and 7th attributes in the first test list (types, base_types, names, results) = test_data[0] og.Controller.edit( graph, { keys.SET_VALUES: [ (types_attribute, types), (added_names_attribute, names), (removed_names_attribute, [names[2], names[4], names[7]]), ] }, ) await og.Controller.evaluate() def pruned_list(original: List) -> List: """Remove the elements 2, 4, 7 from the list and return the result""" return [item for index, item in enumerate(original) if index not in [2, 4, 7]] (bundled_count, bundled_results) = ognts.bundle_inspector_results(inspector_node) # Modify the expected results to account for the removed attributes self.assertEqual(bundled_count, results[0] - 3) names_expected = pruned_list(names) base_types_expected = pruned_list(base_types) array_depths_expected = pruned_list(results[2]) tuple_counts_expected = pruned_list(results[3]) roles_expected = pruned_list(results[1]) self.assertCountEqual(list(bundled_results.keys()), names_expected) for index, name in enumerate(names_expected): error = f"Checking {{}} for attribute {name}" named_results = bundled_results[name] self.assertEqual( named_results[ognts.BundleResultKeys.TYPE_IDX], base_types_expected[index], error.format("type") ) self.assertEqual( named_results[ognts.BundleResultKeys.ARRAY_DEPTH_IDX], array_depths_expected[index], error.format("array depth"), ) self.assertEqual( named_results[ognts.BundleResultKeys.TUPLE_COUNT_IDX], tuple_counts_expected[index], error.format("tuple count"), ) self.assertEqual( named_results[ognts.BundleResultKeys.ROLE_IDX], roles_expected[index], error.format("role") ) # ---------------------------------------------------------------------- async def test_add_attributes_to_bundle_cpp(self): """Test adding attributes to bundles on the C++ implemented node""" await self._test_add_attributes_to_bundle("omni.graph.tutorials.BundleAddAttributes") # ---------------------------------------------------------------------- async def test_add_attributes_to_bundle_py(self): """Test adding attributes to bundles on the Python implemented node""" await self._test_add_attributes_to_bundle("omni.graph.tutorials.BundleAddAttributesPy") # ---------------------------------------------------------------------- async def _test_batched_add_attributes_to_bundle(self, node_type_to_test: str): """Test basic operation of the tutorial node that adds new attributes to a bundle""" keys = og.Controller.Keys (graph, [add_node, inspector_node], _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("AddAttributes", node_type_to_test), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CONNECT: ("AddAttributes.outputs_bundle", "Inspector.inputs:bundle"), }, ) await og.Controller.evaluate() types_attribute = og.Controller.attribute("inputs:typesToAdd", add_node) added_names_attribute = og.Controller.attribute("inputs:addedAttributeNames", add_node) removed_names_attribute = og.Controller.attribute("inputs:removedAttributeNames", add_node) batched_api_attribute = og.Controller.attribute("inputs:useBatchedAPI", add_node) _ = ogt.OGN_DEBUG and ognts.enable_debugging(inspector_node) # List of test data configurations to run. The individual test entries consist of: # - list of the types for the attributes to be added # - list of the base types corresponding to the main types # - list of names for the attributes to be added # - list of values expected for the new bundle as (count, roles, arrayDepths, tupleCounts, values) test_data = [ [ ["float", "double", "int", "int64", "uchar", "uint", "uint64", "bool", "token"], ["float", "double", "int", "int64", "uchar", "uint", "uint64", "bool", "token"], [f"output{n}" for n in range(9)], (9, ["none"] * 9, [0] * 9, [1] * 9, [0.0, 0.0, 0, 0, 0, 0, 0, False, ""]), ], [ ["float[]", "double[]", "int[]", "int64[]", "uchar[]", "uint[]", "uint64[]", "token[]"], ["float", "double", "int", "int64", "uchar", "uint", "uint64", "token"], [f"output{n}" for n in range(8)], (8, ["none"] * 8, [1] * 8, [1] * 8, [[], [], [], [], [], [], [], []]), ], [ ["float[3]", "double[2]", "int[4]"], ["float", "double", "int"], [f"output{n}" for n in range(3)], (3, ["none"] * 3, [0] * 3, [3, 2, 4], [[0.0, 0.0, 0.0], [0.0, 0.0], [0, 0, 0, 0]]), ], [ ["float[3][]", "double[2][]", "int[4][]"], ["float", "double", "int"], [f"output{n}" for n in range(3)], (3, ["none"] * 3, [1] * 3, [3, 2, 4], [[], [], []]), ], [ ["any"], ["token"], ["output0"], (1, ["none"], [0], [1], [""]), ], [ ["colord[3]", "colorf[4]", "colorh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["color"] * 3, [0] * 3, [3, 4, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["normald[3]", "normalf[3]", "normalh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["normal"] * 3, [0] * 3, [3, 3, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["pointd[3]", "pointf[3]", "pointh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["point"] * 3, [0] * 3, [3, 3, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["quatd[4]", "quatf[4]", "quath[4]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], ( 3, ["quat"] * 3, [0] * 3, [4, 4, 4], [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], ), ], [ ["texcoordd[3]", "texcoordf[2]", "texcoordh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["texcoord"] * 3, [0] * 3, [3, 2, 3], [[0.0, 0.0, 0.0], [0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["vectord[3]", "vectorf[3]", "vectorh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["vector"] * 3, [0] * 3, [3, 3, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["timecode"], ["double"], ["output0"], (1, ["timecode"], [0], [1], [0.0]), ], ] for (types, base_types, names, results) in test_data: og.Controller.edit( graph, { keys.SET_VALUES: [ (types_attribute, types), (added_names_attribute, names), (batched_api_attribute, True), ] }, ) await og.Controller.evaluate() (bundled_count, bundled_results) = ognts.bundle_inspector_results(inspector_node) self.assertEqual(bundled_count, results[0]) self.assertCountEqual(list(bundled_results.keys()), names) for index, name in enumerate(names): error = f"Checking {{}} for attribute {name}" named_results = bundled_results[name] self.assertEqual( named_results[ognts.BundleResultKeys.TYPE_IDX], base_types[index], error.format("type") ) self.assertEqual( named_results[ognts.BundleResultKeys.ARRAY_DEPTH_IDX], results[2][index], error.format("array depth"), ) self.assertEqual( named_results[ognts.BundleResultKeys.TUPLE_COUNT_IDX], results[3][index], error.format("tuple count"), ) self.assertEqual( named_results[ognts.BundleResultKeys.ROLE_IDX], results[1][index], error.format("role") ) # One final test run that also includes a remove of the 2nd, 4th, and 7th attributes in the first test list (types, base_types, names, results) = test_data[0] og.Controller.edit( graph, { keys.SET_VALUES: [ (types_attribute, types), (added_names_attribute, names), (removed_names_attribute, [names[2], names[4], names[7]]), ] }, ) await og.Controller.evaluate() def pruned_list(original: List) -> List: """Remove the elements 2, 4, 7 from the list and return the result""" return [item for index, item in enumerate(original) if index not in [2, 4, 7]] await og.Controller.evaluate() (bundled_count, bundled_results) = ognts.bundle_inspector_results(inspector_node) self.assertEqual(bundled_count, results[0] - 3) # Modify the expected results to account for the removed attributes names_expected = pruned_list(names) base_types_expected = pruned_list(base_types) array_depths_expected = pruned_list(results[2]) tuple_counts_expected = pruned_list(results[3]) roles_expected = pruned_list(results[1]) self.assertCountEqual(list(bundled_results.keys()), names_expected) for index, name in enumerate(names_expected): error = f"Checking {{}} for attribute {name}" named_results = bundled_results[name] self.assertEqual( named_results[ognts.BundleResultKeys.TYPE_IDX], base_types_expected[index], error.format("type") ) self.assertEqual( named_results[ognts.BundleResultKeys.ARRAY_DEPTH_IDX], array_depths_expected[index], error.format("array depth"), ) self.assertEqual( named_results[ognts.BundleResultKeys.TUPLE_COUNT_IDX], tuple_counts_expected[index], error.format("tuple count"), ) self.assertEqual( named_results[ognts.BundleResultKeys.ROLE_IDX], roles_expected[index], error.format("role") ) # ---------------------------------------------------------------------- async def test_batched_add_attributes_to_bundle_cpp(self): """Test adding attributes to bundles on the C++ implemented node""" await self._test_batched_add_attributes_to_bundle("omni.graph.tutorials.BundleAddAttributes") # ---------------------------------------------------------------------- async def test_batched_add_attributes_to_bundle_py(self): """Test adding attributes to bundles on the Python implemented node""" await self._test_batched_add_attributes_to_bundle("omni.graph.tutorials.BundleAddAttributesPy") # ---------------------------------------------------------------------- async def _test_bundle_gpu(self, node_type_to_test: str): """Test basic operation of the tutorial node that accesses bundle data on the GPU""" controller = og.Controller() keys = og.Controller.Keys (graph, (bundle_node, inspector_node), _, _) = controller.edit( "/TestGraph", { keys.CREATE_PRIMS: [ ("Prim1", {"points": ("pointf[3][]", [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])}), ("Prim2", {"points": ("pointf[3][]", [[4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])}), ], keys.CREATE_NODES: [ ("GpuBundleNode", node_type_to_test), ("Inspector", "omni.graph.nodes.BundleInspector"), ], }, ) controller.edit( graph, { keys.EXPOSE_PRIMS: [ (og.GraphController.PrimExposureType.AS_BUNDLE, "Prim1", "Prim1Extract"), (og.GraphController.PrimExposureType.AS_BUNDLE, "Prim2", "Prim2Extract"), ], keys.CONNECT: [ ("Prim1Extract.outputs_primBundle", "GpuBundleNode.inputs:cpuBundle"), ("Prim2Extract.outputs_primBundle", "GpuBundleNode.inputs:gpuBundle"), ("GpuBundleNode.outputs_cpuGpuBundle", "Inspector.inputs:bundle"), ], }, ) _ = ogt.OGN_DEBUG and ognts.enable_debugging(inspector_node) await controller.evaluate(graph) for gpu in [False, True]: controller.attribute("inputs:gpu", bundle_node, graph).set(gpu) await controller.evaluate() (_, bundled_values) = ognts.bundle_inspector_results(inspector_node) self.assertEqual(bundled_values["dotProducts"][ognts.BundleResultKeys.VALUE_IDX], [32.0, 122.0]) # ---------------------------------------------------------------------- async def test_bundle_gpu_cpp(self): """Test access to bundle contents on GPU on the C++ implemented node""" await self._test_bundle_gpu("omni.graph.tutorials.CpuGpuBundles") # ---------------------------------------------------------------------- async def test_bundle_gpu_py(self): """Test bundle contents on GPU on the Python implemented node""" await self._test_bundle_gpu("omni.graph.tutorials.CpuGpuBundlesPy") # ---------------------------------------------------------------------- @unittest.skipIf(is_running_in_teamcity(), "This is a manual test so it only needs to run locally") async def test_cuda_pointers_py(self): """Run a simple test on a node that extracts CUDA pointers from the GPU. Inspect the output for information""" controller = og.Controller() keys = og.Controller.Keys (graph, (_, inspector_node), _, _) = controller.edit( "/TestGraph", { keys.CREATE_PRIMS: [ ("Prim1", {"points": ("float[3][]", [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])}), ], keys.CREATE_NODES: [ ("GpuBundleNode", "omni.graph.tutorials.CudaCpuArraysPy"), ("Inspector", "omni.graph.nodes.BundleInspector"), ], }, ) controller.edit( graph, { keys.EXPOSE_PRIMS: [ (og.GraphController.PrimExposureType.AS_ATTRIBUTES, "Prim1", "Prim1Extract"), ], }, ) _ = ogt.OGN_DEBUG and ognts.enable_debugging(inspector_node) await controller.evaluate(graph) controller.edit( graph, { keys.CONNECT: [ ("Prim1Extract.outputs:points", "GpuBundleNode.inputs:points"), ("GpuBundleNode.outputs_outBundle", "Inspector.inputs:bundle"), ], }, )
34,927
Python
45.632844
118
0.474361
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_omnigraph_metadata.py
"""Basic tests of the metadata bindings found in OmniGraphBindingsPython.cpp""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.tools.ogn as ogn # ====================================================================== class TestOmniGraphMetadata(ogts.OmniGraphTestCase): """Encapsulate simple tests that exercise metadata access""" # ---------------------------------------------------------------------- def __node_type_metadata_test(self, node_type: og.NodeType): """Test a node type object for metadata access""" original_count = node_type.get_metadata_count() key = "_node_type_metadata" value = "_test_value" node_type.set_metadata(key, value) # The new metadata key should now have the new value self.assertEqual(value, node_type.get_metadata(key)) new_metadata = node_type.get_all_metadata() # The new key/value pair should now be part of the entire metadata listt self.assertTrue(key in new_metadata) self.assertEqual(value, new_metadata[key]) # Since a unique key was chosen there should be one extra metadata value self.assertEqual(original_count + 1, node_type.get_metadata_count()) # Setting a value to None should remove the metadata from the node type. # Do this last so that the test can run multiple times successfully. node_type.set_metadata(key, None) self.assertEqual(original_count, node_type.get_metadata_count()) # Test silent success of trying to set the metadata to illegal data node_type.set_metadata(None, value) # Verify the hardcoded metadata type names self.assertTrue(ogn.MetadataKeys.UI_NAME in new_metadata) self.assertTrue(ogn.MetadataKeys.TAGS in new_metadata) self.assertEqual("Tutorial Node: Tuple Attributes", new_metadata[ogn.MetadataKeys.UI_NAME]) self.assertEqual("tuple,tutorial,internal", new_metadata[ogn.MetadataKeys.TAGS]) # ---------------------------------------------------------------------- async def test_node_type_metadata(self): """Test metadata features in the NodeType class""" # The TupleData tutorial node happens to have special metadata types defined node_type = og.get_node_type("omni.tutorials.TupleData") self.assertIsNotNone(node_type, "Empty node type to be used for test was not registered") self.__node_type_metadata_test(node_type) # ---------------------------------------------------------------------- async def test_node_metadata(self): """Test metadata access through the node class""" # The TupleData tutorial node happens to have special metadata types defined (_, [test_node], _, _) = og.Controller.edit( "/TestGraph", { og.Controller.Keys.CREATE_NODES: ("TupleNode", "omni.tutorials.TupleData"), }, ) await og.Controller.evaluate() self.__node_type_metadata_test(test_node.get_node_type()) # ---------------------------------------------------------------------- async def test_attribute_metadata(self): """Test metadata features in the NodeType class""" # Any node type will do for metadata tests so use a simple one (_, [test_node], _, _) = og.Controller.edit( "/TestGraph", { og.Controller.Keys.CREATE_NODES: ("SimpleNode", "omni.graph.tutorials.SimpleData"), }, ) await og.Controller.evaluate() self.assertIsNotNone(test_node, "Simple data node type to be used for test was not registered") test_attribute = test_node.get_attribute("inputs:a_bool") self.assertIsNotNone(test_attribute, "Boolean input on simple data node type not found") original_count = test_attribute.get_metadata_count() key = "_test_attribute_metadata" value = "_test_value" test_attribute.set_metadata(key, value) # The new metadata key should now have the new value self.assertEqual(value, test_attribute.get_metadata(key)) new_metadata = test_attribute.get_all_metadata() # The new key/value pair should now be part of the entire metadata listt self.assertTrue(key in new_metadata) self.assertEqual(value, new_metadata[key]) # Since a unique key was chosen there should be one extra metadata value self.assertEqual(original_count + 1, test_attribute.get_metadata_count()) # Setting a value to None should remove the metadata from the node type. # Do this last so that the test can run multiple times successfully. test_attribute.set_metadata(key, None) self.assertEqual(original_count, test_attribute.get_metadata_count()) # Test silent success of trying to set the metadata to illegal data test_attribute.set_metadata(None, value) # ObjectId types get special metadata hardcoded for attribute_name in ["inputs:a_objectId", "outputs:a_objectId"]: object_id_attribute = test_node.get_attribute(attribute_name) self.assertIsNotNone(object_id_attribute, f"ObjectId {attribute_name} on simple data node type not found") object_id_metadata = object_id_attribute.get_all_metadata() self.assertTrue(ogn.MetadataKeys.OBJECT_ID in object_id_metadata) # Check on the constant attribute constant_attribute = test_node.get_attribute("inputs:a_constant_input") self.assertEqual("1", constant_attribute.get_metadata(ogn.MetadataKeys.OUTPUT_ONLY))
5,658
Python
49.079646
118
0.627253
omniverse-code/kit/exts/omni.graph.tutorials/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [1.3.3] - 2022-08-31 ### Fixed - Refactored out use of a deprecated class ## [1.3.2] - 2022-08-30 ### Fixed - Doc error referencing a Python node in a C++ node docs ## [1.3.1] - 2022-08-09 ### Fixed - Applied formatting to all of the Python files ## [1.3.0] - 2022-07-07 ### Changed - Refactored imports from omni.graph.tools to get the new locations ### Added - Test for public API consistency ## [1.2.0] - 2022-05-06 ### Changed - Updated the CPU to GPU test to show the actual pointer contents ## [1.1.3] - 2022-04-29 ### Changed - Made tests derive from OmniGraphTestCase ## [1.1.2] - 2022-03-07 ### Changed - Substituted old tutorial 1 node icons with new version ## [1.1.1] - 2022-03-01 ### Fixed - Made bundle tests use the Controller ## [1.0.0] - 2021-03-01 ### Initial Version - Started changelog with initial released version of the OmniGraph core
1,138
Markdown
23.760869
87
0.692443
omniverse-code/kit/exts/omni.graph.tutorials/docs/README.md
# OmniGraph Tutorials [omni.graph.tutorials] Sets of nodes that provide tutorials on the construction of OmniGraph nodes, with an emphasis on the use of the OmniGraph node description files (*.ogn).
200
Markdown
39.199992
107
0.795
omniverse-code/kit/exts/omni.graph.tutorials/docs/index.rst
.. _ogn_tutorial_nodes: OmniGraph Walkthrough Tutorials ############################### .. tabularcolumns:: |L|R| .. csv-table:: :width: 100% **Extension**: omni.graph.tutorials,**Documentation Generated**: |today| .. toctree:: :maxdepth: 1 CHANGELOG In the source tree are several tutorials. Enclosed in these tutorial files are curated nodes that implement a representative portion of the available features in an OmniGraph Node interface. By working through these tutorials you can gradually build up a knowledge of the concepts used to effectively write OmniGraph Nodes. .. note:: In the tutorial files irrelevant details such as the copyright notice are omitted for clarity .. toctree:: :maxdepth: 1 :glob: ../tutorials/conversionTutorial/* ../tutorials/extensionTutorial/* ../tutorials/tutorial1/* ../tutorials/tutorial2/* ../tutorials/tutorial3/* ../tutorials/tutorial4/* ../tutorials/tutorial5/* ../tutorials/tutorial6/* ../tutorials/tutorial7/* ../tutorials/tutorial8/* ../tutorials/tutorial9/* ../tutorials/tutorial10/* ../tutorials/tutorial11/* ../tutorials/tutorial12/* ../tutorials/tutorial13/* ../tutorials/tutorial14/* ../tutorials/tutorial15/* ../tutorials/tutorial16/* ../tutorials/tutorial17/* ../tutorials/tutorial18/* ../tutorials/tutorial19/* ../tutorials/tutorial20/* ../tutorials/tutorial21/* ../tutorials/tutorial22/* ../tutorials/tutorial23/* ../tutorials/tutorial24/* ../tutorials/tutorial25/* ../tutorials/tutorial26/* ../tutorials/tutorial27/*
1,588
reStructuredText
26.396551
115
0.684509
omniverse-code/kit/exts/omni.audiorecorder/PACKAGE-LICENSES/omni.audiorecorder-LICENSE.md
Copyright (c) 2020, 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.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.audiorecorder/config/extension.toml
[package] title = "Kit Audio Recorder" category = "Audio" feature = true version = "0.1.0" description = "An audio recorder API which is available from python and C++" detailedDescription = """This is a simple interface that can be used to record audio to file or send recorded audio to a callback for generic audio recording tasks. This recorder can achieve a relatively low latency (e.g. 20ms). This API is available in python and C++. See omni.kit.window.audiorecorder for an example use of this API. """ authors = ["NVIDIA"] keywords = ["audio", "capture", "recording"] [dependencies] "carb.audio" = {} "omni.usd.libs" = {} "omni.usd.schema.semantics" = {} "omni.usd.schema.audio" = {} "omni.kit.audiodeviceenum" = {} [[native.plugin]] path = "bin/*.plugin" [[python.module]] name = "omni.audiorecorder" [[test]] args = [ "--/audio/deviceBackend=null" ] dependencies = [ "omni.usd", "omni.kit.test_helpers_gfx", ] stdoutFailPatterns.exclude = [ "*failed to create an encoder state*", "*failed to initialize the output stream*", "*recording is already in progress*", "*no supported conversion path from ePcmFloat (4) to eRaw (10)*", ] # uncomment and re-open OM-50069 if it breaks again #pythonTests.unreliable = [ # "*test_callback_recording", # OM-50069 #]
1,302
TOML
23.584905
78
0.690476
omniverse-code/kit/exts/omni.audiorecorder/omni/audiorecorder/__init__.py
""" This module contains bindings to the C++ omni::audio::IAudioRecorder interface. This provides functionality for simple audio recording to file or using a callback. Recording can be done in 16 bit, 32 bit or float PCM if a callback is required. Recording can be done in any format when only recording to a file. Recording to a file while simultaneously receiving data callbacks is also possible. """ # recorder bindings depend on some types from carb.audio import carb.audio from ._audiorecorder import *
550
Python
41.384612
91
0.732727
omniverse-code/kit/exts/omni.audiorecorder/omni/audiorecorder/tests/__init__.py
from .test_audio_recorder import * # pragma: no cover
56
Python
17.999994
54
0.714286
omniverse-code/kit/exts/omni.audiorecorder/omni/audiorecorder/tests/test_audio_recorder.py
import pathlib import time import os import math from PIL import Image import omni.kit.test_helpers_gfx.compare_utils import carb.tokens import carb.audio import omni.audiorecorder import omni.usd.audio import omni.kit.audiodeviceenum import omni.kit.test import omni.log OUTPUTS_DIR = pathlib.Path(omni.kit.test.get_test_output_path()) # boilerplate to work around python lacking references class IntReference: # pragma: no cover def __init__(self, v): self._v = v; def _get_value(self): return self._v def _set_value(self, v): self._v = v value = property(_get_value, _set_value) def wait_for_data(received: IntReference, ms: int, expected_data: int): # pragma: no cover for i in range(ms): if received.value > expected_data: # log this so we can see timing margins on teamcity omni.log.warn("finished waiting after " + str(i / 1000.0) + " seconds") break if i > 0 and i % 1000 == 0: omni.log.warn("waited " + str(i // 1000) + " seconds") if i == ms - 1: self.assertTrue(not "timeout of " + str(ms) + "ms waiting for " + str(expected_data) + " frames") time.sleep(0.001) class TestAudioRecorder(omni.kit.test.AsyncTestCase): # pragma: no cover def setUp(self): self._recorder = omni.audiorecorder.create_audio_recorder() self.assertIsNotNone(self._recorder) extension_path = carb.tokens.get_tokens_interface().resolve("${omni.audiorecorder}") self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute() self._golden_path = self._test_path.joinpath("golden") def tearDown(self): self._recorder = None def test_callback_recording(self): valid = [] for i in range(1, 16): valid.append(4800 * i) received = IntReference(0) def read_validation(data): nonlocal received received.value += len(data) self.assertTrue(len(data) in valid) def float_read_callback(data): read_validation(data) self.assertTrue(isinstance(data[0], float)) def int_read_callback(data): read_validation(data) self.assertTrue(isinstance(data[0], int)) # if there are no devices, this won't work if omni.kit.audiodeviceenum.acquire_audio_device_enum_interface().get_device_count(omni.kit.audiodeviceenum.Direction.CAPTURE) == 0: self.assertFalse(self._recorder.begin_recording_float( callback = float_read_callback, )) return # not open => should be some valid default format fmt = self._recorder.get_format() self.assertIsNotNone(fmt) self.assertGreaterEqual(fmt.channels, carb.audio.MIN_CHANNELS) self.assertLessEqual(fmt.channels, carb.audio.MAX_CHANNELS) self.assertGreaterEqual(fmt.frame_rate, carb.audio.MIN_FRAMERATE) self.assertLessEqual(fmt.frame_rate, carb.audio.MAX_FRAMERATE) self.assertTrue(self._recorder.begin_recording_float( callback = float_read_callback, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, length_type = carb.audio.UnitType.FRAMES, channels = 1 )) # try again and it will fail because a recording is already in progress self.assertFalse(self._recorder.begin_recording_float( callback = float_read_callback, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, length_type = carb.audio.UnitType.FRAMES, channels = 1 )) # not much we can test here aside from it being valid fmt = self._recorder.get_format() self.assertIsNotNone(fmt) self.assertEqual(fmt.channels, 1) self.assertGreaterEqual(fmt.frame_rate, carb.audio.MIN_FRAMERATE) self.assertLessEqual(fmt.frame_rate, carb.audio.MAX_FRAMERATE) self.assertEqual(fmt.format, carb.audio.SampleFormat.PCM_FLOAT) # this timeout seems absurd, but anything's possible with teamcity's timing wait_for_data(received, 8000, 4800) self._recorder.stop_recording() # try again with int16 received.value = 0 self.assertTrue(self._recorder.begin_recording_int16( callback = int_read_callback, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, length_type = carb.audio.UnitType.FRAMES, channels = 1 )) # not much we can test here aside from it being valid fmt = self._recorder.get_format() self.assertIsNotNone(fmt) self.assertEqual(fmt.channels, 1) self.assertGreaterEqual(fmt.frame_rate, carb.audio.MIN_FRAMERATE) self.assertLessEqual(fmt.frame_rate, carb.audio.MAX_FRAMERATE) self.assertEqual(fmt.format, carb.audio.SampleFormat.PCM16) wait_for_data(received, 8000, 4800) self._recorder.stop_recording() # try again with int32 received.value = 0 self.assertTrue(self._recorder.begin_recording_int32( callback = int_read_callback, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, length_type = carb.audio.UnitType.FRAMES, channels = 1 )) # not much we can test here aside from it being valid fmt = self._recorder.get_format() self.assertIsNotNone(fmt) self.assertEqual(fmt.channels, 1) self.assertGreaterEqual(fmt.frame_rate, carb.audio.MIN_FRAMERATE) self.assertLessEqual(fmt.frame_rate, carb.audio.MAX_FRAMERATE) self.assertEqual(fmt.format, carb.audio.SampleFormat.PCM32) wait_for_data(received, 8000, 4800) self._recorder.stop_recording() # test that the format is set as specified self.assertTrue(self._recorder.begin_recording_float( callback = float_read_callback, channels = 1, # 1 channel because that's all we can guarantee # when we upgrade IAudioCapture, this should no longer # be an issue frame_rate = 43217, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, length_type = carb.audio.UnitType.FRAMES )) fmt = self._recorder.get_format() self.assertEqual(fmt.channels, 1) self.assertEqual(fmt.frame_rate, 43217) self.assertEqual(fmt.format, carb.audio.SampleFormat.PCM_FLOAT) self._recorder.stop_recording() def _validate_sound(self, path): # to validate that this is a working sound, load it into a sound prim # and check if the sound asset loaded successfully context = omni.usd.get_context() self.assertIsNotNone(context) context.new_stage() stage = context.get_stage() self.assertIsNotNone(stage) prim = stage.DefinePrim("/sound", "OmniSound") self.assertIsNotNone(prim) prim.GetAttribute("filePath").Set(path) audio = omni.usd.audio.get_stage_audio_interface() self.assertIsNotNone(audio) i = 0 while audio.get_sound_asset_status(prim) == omni.usd.audio.AssetLoadStatus.IN_PROGRESS: time.sleep(0.001) if i > 5000: raise Exception("asset load timed out") i += 1 self.assertEqual(audio.get_sound_asset_status(prim), omni.usd.audio.AssetLoadStatus.DONE) def test_recording_to_file(self): received = IntReference(0) def read_callback(data): nonlocal received received.value += len(data) if omni.kit.audiodeviceenum.acquire_audio_device_enum_interface().get_device_count(omni.kit.audiodeviceenum.Direction.CAPTURE) == 0: self.assertFalse(self._recorder.begin_recording_float( callback = read_callback, filename = str(OUTPUTS_DIR.joinpath("test.oga")) )) self.assertFalse(self._recorder.begin_recording_to_file( filename = str(OUTPUTS_DIR.joinpath("test.oga")) )) return self.assertTrue(self._recorder.begin_recording_float( callback = read_callback, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, channels = 1, frame_rate = 48000, length_type = carb.audio.UnitType.FRAMES, output_format = carb.audio.SampleFormat.OPUS, filename = str(OUTPUTS_DIR.joinpath("test.opus.oga")) )) wait_for_data(received, 8000, 4800) self._recorder.stop_recording() self._validate_sound(str(OUTPUTS_DIR.joinpath("test.opus.oga"))) # try again with a default output format self.assertTrue(self._recorder.begin_recording_float( callback = read_callback, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, channels = 1, frame_rate = 48000, length_type = carb.audio.UnitType.FRAMES, filename = str(OUTPUTS_DIR.joinpath("test.default.0.wav")) )) wait_for_data(received, 8000, 4800) self._recorder.stop_recording() self._validate_sound(str(OUTPUTS_DIR.joinpath("test.default.0.wav"))) self.assertTrue(self._recorder.begin_recording_to_file( frame_rate = 73172, channels = 1, filename = str(OUTPUTS_DIR.joinpath("test.vorbis.oga")), output_format = carb.audio.SampleFormat.VORBIS )) time.sleep(2.0) self._recorder.stop_recording() self._validate_sound(str(OUTPUTS_DIR.joinpath("test.vorbis.oga"))) # try again with a default output format self.assertTrue(self._recorder.begin_recording_to_file( frame_rate = 73172, channels = 1, filename = str(OUTPUTS_DIR.joinpath("test.default.1.wav")), )) time.sleep(2.0) self._recorder.stop_recording() self._validate_sound(str(OUTPUTS_DIR.joinpath("test.default.1.wav"))) def test_bad_parameters(self): def read_callback(data): pass # MP3 is not supported self.assertFalse(self._recorder.begin_recording_float( callback = read_callback, output_format = carb.audio.SampleFormat.MP3, filename = str(OUTPUTS_DIR.joinpath("test.mp3")) )) # bad format self.assertFalse(self._recorder.begin_recording_float( callback = read_callback, output_format = carb.audio.SampleFormat.RAW, filename = str(OUTPUTS_DIR.joinpath("test.mp3")) )) # bad file name self.assertFalse(self._recorder.begin_recording_float( callback = read_callback, output_format = carb.audio.SampleFormat.OPUS, filename = "a/b/c/d/e/f/g/h/i/j.oga" )) self.assertFalse(self._recorder.begin_recording_float( callback = read_callback, channels = carb.audio.MAX_CHANNELS + 1 )) self.assertFalse(self._recorder.begin_recording_float( callback = read_callback, frame_rate = carb.audio.MAX_FRAMERATE + 1 )) def test_draw_waveform(self): # toggle in case you want to regenerate waveforms GENERATE_GOLDEN_IMAGES = False samples_int16 = [] samples_int32 = [] samples_float = [] for i in range(4800): samples_float.append(math.sin(i / 48.0)) samples_int16.append(int(samples_float[-1] * (2 ** 15 - 1))) samples_int32.append(int(samples_float[-1] * (2 ** 31 - 1))) W = 256 H = 256 raw = omni.audiorecorder.draw_waveform_from_blob_float(samples_float, 1, W, H, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath("waveform.float.png"))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath("waveform.float.png"), self._golden_path.joinpath("waveform.png"), pathlib.Path(OUTPUTS_DIR).joinpath("waveform.float.png.diff.png")), 0.1) raw = omni.audiorecorder.draw_waveform_from_blob_int32(samples_int32, 1, W, H, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath("waveform.int32.png"))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath("waveform.int32.png"), self._golden_path.joinpath("waveform.png"), pathlib.Path(OUTPUTS_DIR).joinpath("waveform.int32.png.diff.png")), 0.1) raw = omni.audiorecorder.draw_waveform_from_blob_int16(samples_int16, 1, W, H, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath("waveform.int16.png"))) if not GENERATE_GOLDEN_IMAGES: # 1 pixel of difference was 756.0 difference self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath("waveform.int16.png"), self._golden_path.joinpath("waveform.png"), pathlib.Path(OUTPUTS_DIR).joinpath("waveform.int16.png.diff.png")), 1024.0)
14,313
Python
36.276042
140
0.604066
omniverse-code/kit/exts/omni.graph.tools/PACKAGE-LICENSES/omni.graph.tools-LICENSE.md
Copyright (c) 2020, 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.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.graph.tools/config/extension.toml
[package] title = "OmniGraph Tools" # Note that for this extension the semantic versioning is interpreted slightly differently as it has to be concerned # with the public Python API, the content of the generated code, and the .ogn format. Ordinarily the versioning of the # generated code would be handled by a dependency on a particular version of omni.graph/omni.graph.core, however as # this extension cannot see them the dependency has to be managed manually. # # MAJOR VERSION: Changes are made to the generated code, OGN format, or the public API that are not backward compatible. # i.e. the user has to change some of their code to make it work with the new version # # MINOR VERSION: 1. A change is made to the Python API that is backward compatible with no user changes # 2. A change is made to the .ogn format that is backward compatible with no user changes # 3. A change is made that would require regeneration of the Python node database at runtime in order # to ensure backward compatibility, but with no user changes required to the .ogn or node files. # e.g. extra runtime information is added to the database # # PATCH VERSION: 1. A change is made to the implementation of the Python API that does not change functionality # 2. A change is made to the .ogn parsing that does not change the generated code # version = "1.17.2" category = "Graph" readme = "docs/README.md" changelog = "docs/CHANGELOG.md" description = "Contains the implementation of the Omniverse Graph node generator scripts." repository = "" keywords = ["kit", "omnigraph", "tools"] authors = ["NVIDIA"] # The tools are used for the build and so have no dependencies [dependencies] "omni.usd.libs" = {} "omni.kit.pip_archive" = {} # For AutoNode - to be removed after the deprecation support is removed from omni.graph.tools/python/_impl/v1_2_0/autograph [python.pipapi] requirements = [ "numpy", # SWIPAT filed under: http://nvbugs/3193231 "toml", # SWIPAT filed under: http://nvbugs/3060676 ] # Main python module this extension provides, it will be publicly available as "import omni.graph.tools". [[python.module]] name = "omni.graph.tools" [documentation] deps = [ ["kit-sdk", "_build/docs/kit-sdk/latest"], # WAR to include omni.graph.tutorial/etc refs until that workflow is moved ] pages = [ "docs/Overview.md", "docs/node_architects_guide.rst", "docs/ogn_user_guide.rst", "docs/ogn_reference_guide.rst", "docs/attribute_types.rst", "docs/ogn_code_samples_cpp.rst", "docs/ogn_code_samples_python.rst", "docs/ogn_generation_script.rst", "docs/CHANGELOG.md", ]
2,726
TOML
44.449999
123
0.70653
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/ensure_node_types_in_toml.py
""" Given a collection of node metadata, ensure that all nodes appear in the [omnigraph.node_types] section of the extension.toml used by the owning extension to register its information. Invoke this script by passing the location of the .json file containing the metadata for all node types and the location of the extension.toml file to which the metadata should be populated. python ensure_node_types_in_toml.py --nodeInfo $BUILD/exts/omni.my.extension/ogn/nodes.json --toml $SRC/extensions/omni.my.extension/config/extension.toml The extension.toml file will be modified to included a generated section with this format: # === GENERATED BY ensure_node_types_in_toml.py -- DO NOT MODIFY === [omnigraph.node_types] "omni.my.extension.MyNodeType" = 1 "omni.my.extension.MyOtherNodeType" = 1 # === END OF GENERATED CODE === or if the "--allData" flag is set then this more verbose format will be used: # === GENERATED BY ensure_node_types_in_toml.py -- DO NOT MODIFY === [omnigraph.node_types."omni.my.extension.MyNodeType"] version = 1 language = "C++" description = "This is my node" [omnigraph.node_types."omni.my.extension.MyOtherNodeType"] version = 1 language = "C++" description = "This is my other node" # === END OF GENERATED CODE === Note that this script explicitly does not handle the case of multiple versions of the same node type in the same extension as that is also not handled by OmniGraph proper. You might also want to use an intermediate directory, which will create an explicit tag when the .toml is regenerated so that you can safely handle the case of regeneration after a direct edit of the .toml file itself. This will ensure that a user cannot accidentally delete a node definition from the automatically generated section; python ensure_node_types_in_toml.py --nodeInfo $BUILD/exts/omni.my.extension/ogn/nodes.json --toml $SRC/extensions/omni.my.extension/config/extension.toml --intermediate $TOP/_build/intermediate Lastly, the support for the toml package is only available through repo_man in the build, not in the standard path. You can pass in the root directory of the repo_man module if it is needed to find the toml package. python ensure_node_types_in_toml.py --nodeInfo $BUILD/exts/omni.my.extension/ogn/nodes.json --toml $SRC/extensions/omni.my.extension/config/extension.toml --intermediate $TOP/_build/intermediate --repoMan $TOP/_repo/deps/repo_man """ import argparse import json import logging import os import sys from pathlib import Path from node_generator.utils import WritableDir # Create a logger and selectively turn on logging if the OGN debugging environment variable is set logger = logging.getLogger("add_nodes_to_toml") logging_handler = logging.StreamHandler(sys.stdout) logging_handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s")) logger.addHandler(logging_handler) logger.setLevel(logging.INFO if os.getenv("OGN_PARSE_DEBUG") else logging.WARN) START_MARKER = "# === GENERATED BY ensure_node_types_in_toml.py -- DO NOT MODIFY ===" """Special marker text identifying the start of the generated node type identifier code""" SECTION_NAME = "omnigraph.node_types" """Name of the generated section of the .toml file""" END_MARKER = "# === END OF GENERATED CODE ===" """Special marker text identifying the end of the generated node type identifier code""" # ====================================================================== class TomlModifier: """Encapsulates the reading, modifying, and writing of the .toml file with the node information Attributes: changes_made: True iff processing the .toml file resulted in changes to it toml: The toml module root - a member of the class because it may need to be imported from an alternate location Internal Attributes: __all_data: If True then the .toml will include language and description in addition to type name and version __existing_types: Dictionary of node_type_name:version_number for node types found in the original .toml file __node_info: Dictionary of node_type_name:node_type_info generated by the build for this extension __node_info_path: Path pointing to the generated file containing the node type information for this extension __tag_path: Path pointing to a file to use to tag the operation as complete (so that edits to the .toml can trigger regeneration) __toml_path: Path pointing to the .toml file to be modified """ # -------------------------------------------------------------------------------------------------------------- def __init__(self): """Set up the information required for the operations - do nothing just yet""" # Construct the parsing information. Run the script with "--help" to see the usage. parser = argparse.ArgumentParser( description="Ensure that the supplied .toml file contains metadata for all of the nodes defined" " in the extension", formatter_class=argparse.RawTextHelpFormatter, ) parser.add_argument( "-a", "--allData", action="store_true", help="Dump all metadata to the .toml file instead of just the version and node type name", ) parser.add_argument( "-in", "--intermediate", action=WritableDir, const=None, type=Path, metavar="INTERMEDIATE_DIRECTORY", help="Directory into which temporary build information is stored", ) parser.add_argument( "-ni", "--nodeInfoFile", type=Path, metavar="NODE_INFO_FILE.json", help=".json file generated by the build that contains the registration information for all of the nodes", ) parser.add_argument( "-rm", "--repoMan", type=Path, metavar="REPO_MAN_DIR", help="Path to the repo_man support directory", ) parser.add_argument( "-t", "--tomlFile", type=Path, metavar="TOML_FILE", help=".toml file that will contain the node information", ) parser.add_argument("-v", "--verbose", action="store_true", help="Output the steps the script is performing") args = parser.parse_args() # If the script steps are to be echoed enable the logger and dump the script arguments as a first step if args.verbose: logger.setLevel(logging.DEBUG) logger.info("Processing the arguments") logger.info(" Args = %s", args) # Set up the internal attributes. All path files are resolved to absolute paths for convenience. self.__all_data = args.allData self.__toml_path = args.tomlFile.resolve() self.__node_info_path = args.nodeInfoFile.resolve() self.__tag_path = args.intermediate / "extension.toml.built" if args.intermediate is not None else None if self.__tag_path is not None: self.__tag_path = self.__tag_path.resolve() self.changes_made = False self.__in_team_city = False self.__existing_types = {} self.__node_info = {} # The toml package is installed as part of repo_man, not directly available in the build, so it may not be # available here and may have to be found through a location supplied by the script arguments. try: import toml self.toml = toml except ModuleNotFoundError: self.toml = None # There is some information to get from repoMan when running through a build so that we can successfully # determine when a failure is fatal and when it is just part of the normal generation process. if args.repoMan is not None: try: python_path = args.repoMan.resolve().as_posix() sys.path.append(python_path) import omni.repo.man if self.toml is None: toml = omni.repo.man.get_toml_module() self.toml = toml self.__in_team_city = omni.repo.man.is_running_in_teamcity() except (ModuleNotFoundError, AttributeError): # If repoMan is inaccessible then issue a warning but continue on to avoid spurious failures if self.toml is None: logger.warning( "toml module could not be found natively or at path '%s', parsing cannot happen", python_path ) else: logger.warning( "Not able to determine if running in TeamCity without module at '%s', assuming not.", python_path, ) logger.info(" Team City run = %s", self.__in_team_city) # -------------------------------------------------------------------------------------------------------------- @property def needs_generation(self) -> bool: """Returns True iff the extension.toml is older than either the generator script itself or the nodes.json file. This is done here after several unsuccessful attempts to get the build structure to recognize when the file needs rebuilding. At worst it means running this script when it isn't necessary, but then returning immediately after checking the file modification times so hopefully no big deal. """ # If the toml cannot be parsed no generation can happen if self.toml is None: return False this_file = Path(__file__) # If the nodes.json does not exist then no generation is needed because there are no nodes if not self.__node_info_path.exists(): logger.info("Skipping generation - no nodes.json file") return False # If the .toml file does not exist it definitely needs generation if not self.__toml_path.exists(): logger.info("Forcing generation - no .toml file") return True # If the tag file does not exist but should then generation has never been done so it needs to be done now if self.__tag_path is not None and not self.__tag_path.exists(): logger.info("Forcing generation - missing tag file") return True # All four files exist. Regeneration is only needed if the .tag file is not the newest one this_file_mtime = this_file.stat().st_mtime node_info_mtime = self.__node_info_path.stat().st_mtime toml_mtime = self.__toml_path.stat().st_mtime tag_mtime = self.__tag_path.stat().st_mtime if self.__tag_path is not None else 0 if tag_mtime < toml_mtime: logger.info("Forcing generation - .toml is newer %s than the tag file %s", toml_mtime, tag_mtime) return True if tag_mtime < node_info_mtime: logger.info("Forcing generation - tag file is older than nodes.json") return True if tag_mtime < this_file_mtime: logger.info("Forcing generation - tag file is older than the generation script") return True # No good reason was found to regenerate, so don't logger.info("Skipping generation - the .toml file is up to date") return False # -------------------------------------------------------------------------------------------------------------- def read_files(self): """Read in the contents of the .toml and .json files and parse them for modification""" logger.info("Reading the extension's .toml file") contents = self.toml.load(self.__toml_path) try: sections = SECTION_NAME.split(".") self.__existing_types = contents for section in sections: self.__existing_types = self.__existing_types[section] except KeyError: self.__existing_types = {} logger.info("Reading the extension's .json node information file") try: with open(self.__node_info_path, "r", encoding="utf-8") as json_fd: self.__node_info = json.load(json_fd)["nodes"] except (IOError, json.JSONDecodeError): self.__node_info = {} # -------------------------------------------------------------------------------------------------------------- def __existing_version_matches(self, node_type_name: str, version: int) -> bool: """Returns True iff the node type name has a version number in the .toml file matching the one passed in""" if node_type_name not in self.__existing_types: return False node_type_info = self.__existing_types[node_type_name] # If the abbreviated version of the metadata was used the version number is all there is if isinstance(node_type_info, int): return version == node_type_info # Otherwise extract the version number from the metadata dictionary try: return version == node_type_info["version"] except KeyError: return False # -------------------------------------------------------------------------------------------------------------- def add_nodes(self): """Ensure the nodes that were passed in are present in the .toml file""" logger.info("Ensuring the node types are in the file") for node_type_name, node_type_info in self.__node_info.items(): version = int(node_type_info["version"]) if not self.__existing_version_matches(node_type_name, version): self.changes_made = True if self.__all_data: new_item = { "version": version, "language": node_type_info["language"], "description": node_type_info["description"], } else: new_item = version logger.info(" Found an unregistered type - %s = %s", node_type_name, new_item) self.__existing_types[node_type_name] = new_item # -------------------------------------------------------------------------------------------------------------- def write_file(self): """Write the new contents of the .toml file back to the original location. The toml library dump() method cannot be used here as it would lose information like comments and formatting so instead it narrows its focus to the [[omnigraph]] section, surrounding it with fixed markers so that it can be easily identified and replaced using a text-based edit. """ logger.info("Writing the file") if self.__in_team_city: raise AttributeError( f"The file {self.__toml_path} was not up to date in the merge request. Rebuild and add it." ) with open(self.__toml_path, "r", encoding="utf-8") as toml_fd: raw_contents = toml_fd.readlines() raw_line_count = len(raw_contents) # Convert the node type list to a .toml format logger.info(" Inserting new section %s", self.__existing_types) # Build the structure from the bottom up to ensure the .toml has the correct nesting section_dict = self.__existing_types sections = SECTION_NAME.split(".") sections.reverse() for section in sections: section_dict = {section: dict(sorted(section_dict.items()))} inserted_section = self.toml.dumps(section_dict) # Scan the file to see if/where the generated section currently resides in_section = False section_start_index = -1 section_end_index = -1 for line_index, line in enumerate(raw_contents): if in_section and line.rstrip() == END_MARKER: in_section = False section_end_index = line_index if line.rstrip() == START_MARKER: in_section = True section_start_index = line_index logger.info(" Existing section location was %s, %s", section_start_index, section_end_index) if section_start_index >= 0 and section_end_index == -1: raise ValueError( f"The .toml file '{self.__toml_path}' was illegal - it had a start marker but no end marker" ) if section_start_index < 0: section_start_index = raw_line_count section_end_index = section_start_index # Write the modified contents with the new generated section try: with open(self.__toml_path, "w", encoding="utf-8") as toml_fd: toml_fd.writelines(raw_contents[0:section_start_index]) # If inserting at the end of the file then insert a blank line for readability if section_start_index == raw_line_count: toml_fd.write("\n") toml_fd.write(f"{START_MARKER}\n") toml_fd.write(inserted_section) toml_fd.write(f"{END_MARKER}\n") toml_fd.writelines(raw_contents[section_end_index + 1 : raw_line_count]) toml_fd.flush() # Required to ensure the mtime is earlier than the tag file's except IOError as error: raise IOError(f"Failed to write back the .toml file '{self.__toml_path}'") from error # -------------------------------------------------------------------------------------------------------------- def touch_tag_file(self): """Forces update of the tag file mtime.""" try: # Tag the conversion as being complete so that a build process can properly manage dependencies. # This has to happen last to avoid a false positive where the tag file is older than the .toml logger.info("Touching the tag file %s", self.__tag_path) if self.__tag_path is not None: with open(self.__tag_path, "w", newline="\n", encoding="utf-8") as tag_fd: tag_fd.write("This file tags the last time its .toml file was processed with node metadata") except IOError as error: raise IOError(f"Failed to write back the tag file '{self.__tag_path}'") from error # ============================================================================================================== def main_update_extension_toml(): """Walk through the steps required to parse, modify, and write the .toml file.""" modifier = TomlModifier() if modifier.needs_generation: modifier.read_files() modifier.add_nodes() if modifier.changes_made: modifier.write_file() # The tag file needs updating even if changes were not made so that it doesn't repeatedly try and fail to # regenerate every time the script runs. modifier.touch_tag_file() # ============================================================================================================== if __name__ == "__main__": main_update_extension_toml()
19,319
Python
48.035533
120
0.591076
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/_internal.py
"""Imports for support code that will used internally by OmniGraph but should not be used elsewhere. These are all subject to change without supported deprecation paths. """ __all__ = [ "cache_location", "Compatibility", "ExtensionContentsBase", "ExtensionContentsStandalone", "ExtensionContentsV118", "ExtensionContentsV119", "ExtensionVersion_t", "extension_contents_factory", "FileType", "find_ogn_build_directory", "full_cache_path", "GENERATED_FILE_CONFIG_NAMES", "GenerationVersions", "get_generator_extension_version", "get_module_path", "get_ogn_file_name", "get_ogn_type_and_node", "get_target_extension_version", "import_tests_in_directory", "load_module_from_file", "LOG", "NodeTypeDefinition", "OmniGraphExtensionError", "set_registration_logging", "Settings", "TemporaryCacheLocation", "TemporaryLogLocation", "VersionProperties", "walk_with_excludes", ] from ._impl.internal.cache_utils import TemporaryCacheLocation, cache_location, full_cache_path from ._impl.internal.extension_contents_1_18 import ExtensionContentsV118 from ._impl.internal.extension_contents_1_19 import ExtensionContentsV119 from ._impl.internal.extension_contents_base import ExtensionContentsBase from ._impl.internal.extension_contents_factory import extension_contents_factory from ._impl.internal.extension_contents_standalone import ExtensionContentsStandalone from ._impl.internal.file_utils import ( GENERATED_FILE_CONFIG_NAMES, FileType, find_ogn_build_directory, get_module_path, get_ogn_file_name, get_ogn_type_and_node, load_module_from_file, walk_with_excludes, ) from ._impl.internal.logging_utils import LOG, OmniGraphExtensionError, TemporaryLogLocation, set_registration_logging from ._impl.internal.node_type_definition import NodeTypeDefinition from ._impl.internal.versions import ( Compatibility, ExtensionVersion_t, GenerationVersions, VersionProperties, get_generator_extension_version, get_target_extension_version, ) from ._impl.node_generator.generate_test_imports import import_tests_in_directory from ._impl.node_generator.utils import Settings
2,234
Python
33.384615
118
0.744405
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/__init__.py
"""Tools that support all of OmniGraph in general, and the .ogn format in particular. General tools can be imported directly with the top level import: .. code-block:: python import omni.graph.tools as ogt help(ogt.deprecated_function) This module also supports a submodule just for the .ogn handling. .. code-block:: python # Support for the parsing and creation of the .ogn format import omni.graph.tools.ogn as ogn """ from . import ogn from ._impl.debugging import destroy_property, function_trace from ._impl.deprecate import ( DeprecatedClass, DeprecatedDictConstant, DeprecatedImport, DeprecatedStringConstant, DeprecateMessage, DeprecationError, DeprecationLevel, RenamedClass, deprecated_constant_object, deprecated_function, ) from ._impl.extension import _PublicExtension # noqa: F401 from ._impl.node_generator.utils import IndentedOutput, shorten_string_lines_to # ============================================================================================================== __all__ = [ "dbg_gc", "dbg_ui", "dbg", "deprecated_constant_object", "deprecated_function", "DeprecatedClass", "DeprecatedDictConstant", "DeprecatedImport", "DeprecatedStringConstant", "DeprecateMessage", "DeprecationError", "DeprecationLevel", "destroy_property", "function_trace", "import_tests_in_directory", "IndentedOutput", "OGN_DEBUG", "RenamedClass", "shorten_string_lines_to", "supported_attribute_type_names", ] # ============================================================================================================== # Soft-deprecated imports. Kept around for backward compatibility for one version. # _____ ______ _____ _____ ______ _____ _______ ______ _____ # | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ # | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | # | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | # | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | # |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ # from ._impl.debugging import OGN_DEBUG, dbg, dbg_gc, dbg_ui from ._impl.node_generator.attributes.management import supported_attribute_type_names as _moved_to_ogn from ._impl.node_generator.generate_test_imports import import_tests_in_directory @deprecated_function("supported_attribute_type_names() has moved to omni.graph.tools.ogn") def supported_attribute_type_names(*args, **kwargs): return _moved_to_ogn(*args, **kwargs)
2,683
Python
34.315789
112
0.530004
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/_1_11.py
"""Backward compatible module for omni.graph.tools version 1.11 and earlier. This module contains everything that was formerly visible by default but will no longer be part of the Python API for omni.graph.tools. If there is something here you rely on contact the OmniGraph team and let them know. Currently the module is in pre-deprecation, meaning you can still access everything here from the main module with .. code-block:: python import omni.graph.tools as ogt ogt.pre_deprecated_but_still_visible() Once the soft deprecation is enabled you will only be able to access the deprecated function with an explicit import: .. code-block:: python import omni.graph.tools as ogt import omni.graph.tools._1_11 as ogt1_11 if i_want_v1_11: ogt1_11.soft_deprecated_but_still_accessible() else: ogt.current_function() When hard deprecation is in place all functionality will be removed and import of this module will fail: .. code-block:: python import omni.graph.tools._1_11 as ot1_11 # Raises DeprecationError """ from ._impl.debugging import OGN_DEBUG, OGN_EVAL_DEBUG, OGN_GC_DEBUG, OGN_UI_DEBUG, dbg, dbg_eval, dbg_gc, dbg_ui from ._impl.node_generator.attributes.management import ATTRIBUTE_MANAGERS from ._impl.node_generator.attributes.parsing import sdf_type_name from ._impl.node_generator.generate_test_imports import import_tests_in_directory # Code that should be retired from ._impl.node_generator.keys import GraphSetupKeys_V1 from ._impl.node_generator.type_definitions import apply_type_definitions # Code that should be refactored and moved to an appropriate location from ._impl.node_generator.utils import ( OGN_PARSE_DEBUG, OGN_REG_DEBUG, Settings, dbg_parse, dbg_reg, is_unwritable, shorten_string_lines_to, ) # Code that is entirely internal to the node description editor and should be made local from ._impl.ogn_types import _OGN_TO_SDF_BASE_NAME as OGN_TO_SDF_BASE_NAME from ._impl.ogn_types import _SDF_BASE_NAME_TO_OGN as SDF_BASE_NAME_TO_OGN from ._impl.ogn_types import _SDF_TO_OGN as SDF_TO_OGN __all__ = [ "apply_type_definitions", "ATTRIBUTE_MANAGERS", "dbg_eval", "dbg_gc", "dbg_parse", "dbg_reg", "dbg_ui", "dbg", "GraphSetupKeys_V1", "import_tests_in_directory", "is_unwritable", "OGN_DEBUG", "OGN_EVAL_DEBUG", "OGN_GC_DEBUG", "OGN_PARSE_DEBUG", "OGN_REG_DEBUG", "OGN_TO_SDF_BASE_NAME", "OGN_UI_DEBUG", "SDF_BASE_NAME_TO_OGN", "SDF_TO_OGN", "sdf_type_name", "Settings", "shorten_string_lines_to", ]
2,611
Python
30.853658
117
0.711605
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/generate_node.py
"""Command line script to run the node generator scripts Mainly a separate script to create a package for the node generator scripts so that the files can use shorter names and relative imports. See node_generator/README.md for the usage information. """ from _impl.node_generator import main main.main()
307
Python
33.222219
115
0.791531