mjbatch-uni 0.2.1__tar.gz → 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,91 @@
1
+ cmake_minimum_required(VERSION 3.15...3.30)
2
+ project(${SKBUILD_PROJECT_NAME} LANGUAGES CXX)
3
+
4
+ find_package(Python 3.10 COMPONENTS Interpreter Development.Module REQUIRED)
5
+
6
+ execute_process(
7
+ COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
8
+ OUTPUT_STRIP_TRAILING_WHITESPACE
9
+ OUTPUT_VARIABLE nanobind_ROOT)
10
+ find_package(nanobind CONFIG REQUIRED)
11
+
12
+ # Headers and libmujoco come from the installed mujoco wheel.
13
+ execute_process(
14
+ COMMAND "${Python_EXECUTABLE}" -c
15
+ "import mujoco, pathlib; print(pathlib.Path(mujoco.__file__).parent)"
16
+ OUTPUT_STRIP_TRAILING_WHITESPACE
17
+ OUTPUT_VARIABLE MUJOCO_PKG_DIR
18
+ COMMAND_ERROR_IS_FATAL ANY)
19
+ if(WIN32)
20
+ set(MUJOCO_DLL "${MUJOCO_PKG_DIR}/mujoco.dll")
21
+ if(NOT EXISTS "${MUJOCO_DLL}")
22
+ message(FATAL_ERROR "Could not find mujoco.dll in ${MUJOCO_PKG_DIR}")
23
+ endif()
24
+
25
+ # The MuJoCo wheel exports the C API from mujoco.dll but does not ship an
26
+ # MSVC import library. Generate one at build time; it is not installed.
27
+ get_filename_component(MSVC_TOOL_BIN_DIR "${CMAKE_CXX_COMPILER}" DIRECTORY)
28
+ find_program(MSVC_LIB_EXECUTABLE NAMES lib HINTS "${MSVC_TOOL_BIN_DIR}")
29
+ if(NOT MSVC_LIB_EXECUTABLE)
30
+ message(FATAL_ERROR "Could not find MSVC lib.exe")
31
+ endif()
32
+ find_program(MSVC_DUMPBIN_EXECUTABLE NAMES dumpbin HINTS "${MSVC_TOOL_BIN_DIR}")
33
+ if(NOT MSVC_DUMPBIN_EXECUTABLE)
34
+ message(FATAL_ERROR "Could not find MSVC dumpbin.exe")
35
+ endif()
36
+
37
+ execute_process(
38
+ COMMAND "${MSVC_DUMPBIN_EXECUTABLE}" "/EXPORTS" "${MUJOCO_DLL}"
39
+ OUTPUT_VARIABLE MUJOCO_EXPORTS
40
+ COMMAND_ERROR_IS_FATAL ANY)
41
+ string(REGEX MATCHALL
42
+ " +[0-9]+ +[0-9A-Fa-f]+ +[0-9A-Fa-f]+ +([^ \r\n]+)"
43
+ MUJOCO_EXPORT_MATCHES "${MUJOCO_EXPORTS}")
44
+ if(NOT MUJOCO_EXPORT_MATCHES)
45
+ message(FATAL_ERROR "Could not parse exports from ${MUJOCO_DLL}")
46
+ endif()
47
+
48
+ set(MUJOCO_DEF_FILE "${CMAKE_CURRENT_BINARY_DIR}/mujoco.def")
49
+ file(WRITE "${MUJOCO_DEF_FILE}" "LIBRARY mujoco.dll\nEXPORTS\n")
50
+ foreach(export_match IN LISTS MUJOCO_EXPORT_MATCHES)
51
+ string(REGEX REPLACE ".* +([^ \r\n]+)$" "\\1" export_symbol "${export_match}")
52
+ file(APPEND "${MUJOCO_DEF_FILE}" " ${export_symbol}\n")
53
+ endforeach()
54
+
55
+ set(MUJOCO_LIBRARY "${CMAKE_CURRENT_BINARY_DIR}/mujoco.lib")
56
+ execute_process(
57
+ COMMAND "${MSVC_LIB_EXECUTABLE}" "/def:${MUJOCO_DEF_FILE}" "/machine:x64"
58
+ "/out:${MUJOCO_LIBRARY}"
59
+ COMMAND_ERROR_IS_FATAL ANY)
60
+ else()
61
+ file(GLOB MUJOCO_LIBRARY "${MUJOCO_PKG_DIR}/libmujoco*${CMAKE_SHARED_LIBRARY_SUFFIX}*")
62
+ if(NOT MUJOCO_LIBRARY)
63
+ message(FATAL_ERROR "Could not find libmujoco in ${MUJOCO_PKG_DIR}")
64
+ endif()
65
+ list(GET MUJOCO_LIBRARY 0 MUJOCO_LIBRARY)
66
+ endif()
67
+
68
+ nanobind_add_module(_bindings FREE_THREADED NOMINSIZE src/mjbatch/csrc/bindings.cpp)
69
+ if(WIN32)
70
+ # Windows headers are nested one directory deeper than the Unix wheels.
71
+ target_include_directories(_bindings PRIVATE "${MUJOCO_PKG_DIR}/include/mujoco")
72
+ else()
73
+ target_include_directories(_bindings PRIVATE "${MUJOCO_PKG_DIR}/include")
74
+ endif()
75
+ target_link_libraries(_bindings PRIVATE "${MUJOCO_LIBRARY}")
76
+
77
+ # Find libmujoco next to the installed extension, <site-packages>/mujoco. The
78
+ # macOS wheel's install name is a framework path that does not exist, so point
79
+ # our load command at the plain file name instead.
80
+ if(APPLE)
81
+ get_filename_component(MUJOCO_LIB_NAME "${MUJOCO_LIBRARY}" NAME)
82
+ execute_process(COMMAND otool -D "${MUJOCO_LIBRARY}" OUTPUT_VARIABLE _otool)
83
+ string(REGEX MATCH "@rpath[^\n]*" MUJOCO_INSTALL_NAME "${_otool}")
84
+ add_custom_command(TARGET _bindings POST_BUILD COMMAND install_name_tool -change
85
+ "${MUJOCO_INSTALL_NAME}" "@rpath/${MUJOCO_LIB_NAME}" $<TARGET_FILE:_bindings>)
86
+ set_target_properties(_bindings PROPERTIES INSTALL_RPATH "@loader_path/../mujoco")
87
+ elseif(NOT WIN32)
88
+ set_target_properties(_bindings PROPERTIES INSTALL_RPATH "$ORIGIN/../mujoco")
89
+ endif()
90
+
91
+ install(TARGETS _bindings DESTINATION mjbatch)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mjbatch-uni
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: A Python library for running thousands of MuJoCo simulations in parallel on CPU (unilabsim fork).
5
5
  Keywords: mujoco,physics,simulation,batched,reinforcement-learning
6
6
  Author-Email: Kevin Zakka <zakka@berkeley.edu>, Yufei Jia <jyf23@mails.tsinghua.edu.cn>
@@ -11,6 +11,7 @@ Classifier: Intended Audience :: Developers
11
11
  Classifier: Intended Audience :: Science/Research
12
12
  Classifier: Operating System :: MacOS
13
13
  Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Operating System :: Microsoft :: Windows
14
15
  Classifier: Programming Language :: C++
15
16
  Classifier: Programming Language :: Python :: 3.10
16
17
  Classifier: Programming Language :: Python :: 3.11
@@ -80,6 +81,18 @@ Acceleration-stage sensors and contact forces are not available before `mj_step2
80
81
  be stale in that view. The default callback path and all outputs are unchanged unless the
81
82
  optional range is passed.
82
83
 
84
+ After a normal `step()` with `forward=False`, selected position- and velocity-stage sensor
85
+ columns can be refreshed from the final integration state without a full `mj_forward`:
86
+
87
+ ```python
88
+ batch.refresh_sensor_range(ids, (sensor_start, sensor_stop))
89
+ ```
90
+
91
+ The refresh runs in native worker threads, copies only the requested columns into the bound
92
+ `sensordata` view, and leaves acceleration-stage sensors (including contact forces) and all
93
+ other bound fields unchanged. Disjoint ranges can be refreshed in one dispatch with
94
+ `refresh_sensor_ranges(ids, (start0, stop0, start1, stop1, ...))`.
95
+
83
96
  ## Model randomization and variants
84
97
 
85
98
  `expand(field)` returns a live `(num_sims, ...)` view of a non-asset `MjModel` field.
@@ -51,6 +51,18 @@ Acceleration-stage sensors and contact forces are not available before `mj_step2
51
51
  be stale in that view. The default callback path and all outputs are unchanged unless the
52
52
  optional range is passed.
53
53
 
54
+ After a normal `step()` with `forward=False`, selected position- and velocity-stage sensor
55
+ columns can be refreshed from the final integration state without a full `mj_forward`:
56
+
57
+ ```python
58
+ batch.refresh_sensor_range(ids, (sensor_start, sensor_stop))
59
+ ```
60
+
61
+ The refresh runs in native worker threads, copies only the requested columns into the bound
62
+ `sensordata` view, and leaves acceleration-stage sensors (including contact forces) and all
63
+ other bound fields unchanged. Disjoint ranges can be refreshed in one dispatch with
64
+ `refresh_sensor_ranges(ids, (start0, stop0, start1, stop1, ...))`.
65
+
54
66
  ## Model randomization and variants
55
67
 
56
68
  `expand(field)` returns a live `(num_sims, ...)` view of a non-asset `MjModel` field.
@@ -4,7 +4,7 @@ build-backend = "scikit_build_core.build"
4
4
 
5
5
  [project]
6
6
  name = "mjbatch-uni"
7
- version = "0.2.1"
7
+ version = "0.2.3"
8
8
  description = "A Python library for running thousands of MuJoCo simulations in parallel on CPU (unilabsim fork)."
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -20,6 +20,7 @@ classifiers = [
20
20
  "Intended Audience :: Science/Research",
21
21
  "Operating System :: MacOS",
22
22
  "Operating System :: POSIX :: Linux",
23
+ "Operating System :: Microsoft :: Windows",
23
24
  "Programming Language :: C++",
24
25
  "Programming Language :: Python :: 3.10",
25
26
  "Programming Language :: Python :: 3.11",
@@ -79,9 +80,7 @@ testpaths = ["tests"]
79
80
 
80
81
  [tool.cibuildwheel]
81
82
  build = "cp310-* cp311-* cp312-* cp313-*"
82
- # Windows: the mujoco wheel ships mujoco.dll with no import library, and the
83
- # extension finds libmujoco by rpath, which Windows has no equivalent of.
84
- skip = "*-musllinux_* *-win* *_i686"
83
+ skip = "*-musllinux_* *_i686"
85
84
  test-requires = "pytest"
86
85
  test-command = "pytest {project}/tests"
87
86
 
@@ -79,6 +79,16 @@ class Batch:
79
79
  """
80
80
 
81
81
  def forward(self, ids: Annotated[NDArray, dict(shape=(None,), order='C')] | None = None) -> None: ...
82
+ def refresh_sensor_range(
83
+ self,
84
+ ids: Annotated[NDArray, dict(shape=(None,), order='C')] | None = ...,
85
+ sensor_range: Sequence[int] = ...,
86
+ ) -> None: ...
87
+ def refresh_sensor_ranges(
88
+ self,
89
+ ids: Annotated[NDArray, dict(shape=(None,), order='C')] | None = ...,
90
+ sensor_ranges: Sequence[int] = ...,
91
+ ) -> None: ...
82
92
 
83
93
  def reset(self, ids: Annotated[NDArray, dict(shape=(None,), order='C')] | None = None, keyframe: int = -1) -> None:
84
94
  """
@@ -11,8 +11,8 @@
11
11
  #include <nanobind/ndarray.h>
12
12
 
13
13
  #include <algorithm>
14
- #include <csetjmp>
15
14
  #include <cstdint>
15
+ #include <csetjmp>
16
16
  #include <cstdio>
17
17
  #include <cstdlib>
18
18
  #include <cstring>
@@ -26,6 +26,7 @@
26
26
  #include <string_view>
27
27
  #include <thread>
28
28
  #include <unordered_map>
29
+ #include <utility>
29
30
  #include <vector>
30
31
 
31
32
  #ifdef __linux__
@@ -318,6 +319,8 @@ struct QueryCtx {
318
319
  int npoint = 0;
319
320
  HfieldAlign align = HfieldAlign::World; // SampleHfield: sampling grid rotation
320
321
  mjtNum* out = nullptr; // (sel, npoint) rows
322
+ Slot* sensor = nullptr; // RefreshSensor: bound sensordata slot
323
+ const std::vector<int>* sensor_ranges = nullptr; // flattened (start, stop) pairs
321
324
  };
322
325
 
323
326
  // One substep of a callback-driven step (Op::Substep): the calling thread
@@ -388,19 +391,69 @@ inline void SampleHfield(const mjModel* m, const mjData* d, const QueryCtx& ctx)
388
391
  }
389
392
  }
390
393
 
391
- // mju_error trap for worker threads: record the message and unwind to the
392
- // worker's setjmp; everything else goes to the handler that was active before.
393
- inline thread_local std::jmp_buf* tls_jmp = nullptr;
394
- inline thread_local std::string tls_error;
395
- inline mjfLogHandler prev_log_handler = nullptr;
394
+ // MuJoCo error handlers must not return. A thread-local handler and longjmp
395
+ // keep the unwind within the worker's C++ frame, matching the official Python
396
+ // bindings, without changing handlers owned by other threads.
397
+ inline thread_local std::jmp_buf tls_jmp_buf = {};
398
+ inline thread_local bool tls_jmp_active = false;
399
+ inline thread_local char tls_error[1024] = {};
400
+ inline thread_local mjfLogHandler tls_prev_handler = nullptr;
401
+
402
+ // Declared in MuJoCo's internal engine header but omitted from the installed
403
+ // public header. The Python dependency is pinned, so these exported symbols
404
+ // have a stable ABI for this build.
405
+ extern "C" mjfLogHandler _mjPRIVATE_setTlsLogHandler(mjfLogHandler handler);
406
+ extern "C" mjfLogHandler _mjPRIVATE_getGlobalLogHandler(void);
407
+
396
408
  inline void LogTrap(const mjLogMessage* msg) {
397
- if (msg->level == mjLOG_ERROR && tls_jmp) {
398
- tls_error = msg->subject;
399
- std::longjmp(*tls_jmp, 1);
409
+ if (msg->level == mjLOG_ERROR && tls_jmp_active) {
410
+ std::snprintf(tls_error, sizeof(tls_error), "%s", msg->subject);
411
+ std::longjmp(tls_jmp_buf, 1);
412
+ }
413
+ // MuJoCo dispatches to this TLS handler instead of the global one. Preserve
414
+ // an existing TLS handler when present; otherwise keep official bindings'
415
+ // behavior of not forwarding while a scoped wrapper is active.
416
+ if (tls_prev_handler) {
417
+ tls_prev_handler(msg);
418
+ } else if (mjfLogHandler previous = _mjPRIVATE_getGlobalLogHandler(); previous) {
419
+ previous(msg);
420
+ }
421
+ }
422
+
423
+ // A fatal MuJoCo callback cannot safely throw or return through C. Jump only
424
+ // back to this tight wrapper, then throw from C++ after the C frames are gone.
425
+ struct MjError : std::exception {
426
+ const char* what() const noexcept override { return tls_error; }
427
+ };
428
+
429
+ template <typename Return, typename... Args, typename... CallArgs>
430
+ #if defined(_MSC_VER)
431
+ __forceinline
432
+ #endif
433
+ Return TrapCall(Return (*fn)(Args...), CallArgs&&... args) {
434
+ mjfLogHandler previous = _mjPRIVATE_setTlsLogHandler(LogTrap);
435
+ tls_prev_handler = previous;
436
+ tls_jmp_active = true;
437
+ if (setjmp(tls_jmp_buf) == 0) {
438
+ if constexpr (std::is_void_v<Return>) {
439
+ fn(std::forward<CallArgs>(args)...);
440
+ } else {
441
+ Return result = fn(std::forward<CallArgs>(args)...);
442
+ tls_jmp_active = false;
443
+ _mjPRIVATE_setTlsLogHandler(previous);
444
+ tls_prev_handler = nullptr;
445
+ return result;
446
+ }
447
+ tls_jmp_active = false;
448
+ _mjPRIVATE_setTlsLogHandler(previous);
449
+ tls_prev_handler = nullptr;
450
+ return;
400
451
  }
401
- prev_log_handler(msg);
452
+ tls_jmp_active = false;
453
+ _mjPRIVATE_setTlsLogHandler(previous);
454
+ tls_prev_handler = nullptr;
455
+ throw MjError{};
402
456
  }
403
- inline void InstallLogTrap() { prev_log_handler = mju_setLogHandler(LogTrap); }
404
457
 
405
458
  // The Batch whose step callback is running on this thread: a reentrant call
406
459
  // from inside it raises instead of deadlocking on mu_.
@@ -416,6 +469,7 @@ class Batch {
416
469
  Substep2, // split callback: apply writes and mj_step2
417
470
  Forward,
418
471
  Reset,
472
+ RefreshSensor,
419
473
  SetConst,
420
474
  JacSite,
421
475
  SampleHfield
@@ -522,6 +576,41 @@ class Batch {
522
576
  Run(Op::Forward, Parse(ids), 0);
523
577
  }
524
578
 
579
+ void RefreshSensorRanges(std::optional<Ids> ids, const std::vector<int>& sensor_ranges) {
580
+ ReentryGuard();
581
+ for (size_t i = 0; i < sensor_ranges.size(); i += 2) {
582
+ int start = sensor_ranges[i], stop = sensor_ranges[i + 1];
583
+ if (start < 0 || start >= stop || stop > template_->nsensordata) {
584
+ throw nb::value_error("sensor range entries must satisfy 0 <= start < stop <= nsensordata");
585
+ }
586
+ }
587
+ auto sel = Parse(ids);
588
+ Slot* sensor;
589
+ {
590
+ std::lock_guard<std::mutex> lock(mu_);
591
+ sensor = &BoundOrAdd(Field(data_fields_, "sensordata"), false);
592
+ }
593
+ QueryCtx ctx;
594
+ ctx.sensor = sensor;
595
+ ctx.sensor_ranges = &sensor_ranges;
596
+ Run(Op::RefreshSensor, std::move(sel), 0, nullptr, &ctx);
597
+ }
598
+
599
+ void refresh_sensor_range(std::optional<Ids> ids, std::optional<std::vector<int>> sensor_range) {
600
+ if (!sensor_range || sensor_range->size() != 2) {
601
+ throw nb::value_error("sensor_range must have shape (2,)");
602
+ }
603
+ RefreshSensorRanges(std::move(ids), *sensor_range);
604
+ }
605
+
606
+ void refresh_sensor_ranges(std::optional<Ids> ids,
607
+ std::optional<std::vector<int>> sensor_ranges) {
608
+ if (!sensor_ranges || sensor_ranges->empty() || sensor_ranges->size() % 2 != 0) {
609
+ throw nb::value_error("sensor_ranges must contain (start, stop) pairs");
610
+ }
611
+ RefreshSensorRanges(std::move(ids), *sensor_ranges);
612
+ }
613
+
525
614
  void reset(std::optional<Ids> ids, int keyframe) {
526
615
  ReentryGuard();
527
616
  if (keyframe < -1 || keyframe >= template_->nkey) {
@@ -625,7 +714,7 @@ class Batch {
625
714
  bool ParseDtype(const FieldInfo& f, std::optional<nb::object>& dtype) {
626
715
  if (!dtype || dtype->is_none()) return false;
627
716
  nb::object np = nb::module_::import_("numpy");
628
- std::string name = nb::cast<std::string>(nb::str(np.attr("dtype")(*dtype).attr("name")));
717
+ std::string name = nb::cast<std::string>(np.attr("dtype")(*dtype).attr("name"));
629
718
  if (name == DtypeName(f.elem)) return false;
630
719
  if (name == "float32" && f.elem == Elem::Num) return true;
631
720
  throw nb::value_error((std::string(f.name) + " cannot be " + name).c_str());
@@ -803,7 +892,7 @@ class Batch {
803
892
  if (op == Op::SetConst) Restore(m);
804
893
  for (auto& s : expanded_) FromBuf(s->info->get(m), s->buf.get() + i * s->row, *s);
805
894
  if (op == Op::SetConst) {
806
- mj_setConst(m, d);
895
+ TrapCall(mj_setConst, m, d);
807
896
  for (auto& s : expanded_) ToBuf(s->buf.get() + i * s->row, s->info->get(m), *s);
808
897
  scalars_[i] = Scalars::Of(m);
809
898
  for (const FieldInfo* f : restorable_) {
@@ -818,12 +907,12 @@ class Batch {
818
907
  if (!models_.empty()) scalars_[i].Apply(m);
819
908
  if (op == Op::Reset) {
820
909
  if (arg >= 0) {
821
- mj_resetDataKeyframe(m, d, arg);
910
+ TrapCall(mj_resetDataKeyframe, m, d, arg);
822
911
  } else {
823
- mj_resetData(m, d);
912
+ TrapCall(mj_resetData, m, d);
824
913
  }
825
914
  } else {
826
- mj_setState(m, d, State(i), mjSTATE_INTEGRATION);
915
+ TrapCall(mj_setState, m, d, State(i), mjSTATE_INTEGRATION);
827
916
  std::memcpy(d->warning, Warning(i), sizeof(d->warning));
828
917
  }
829
918
  for (auto& s : bound_) {
@@ -836,12 +925,13 @@ class Batch {
836
925
  switch (op) {
837
926
  case Op::Step: {
838
927
  for (int k = 0; k < arg; ++k) {
839
- mj_step(m, d);
928
+ TrapCall(mj_step, m, d);
840
929
  if (hist) {
841
- mj_getState(m, d, hist + static_cast<size_t>(k) * nstate_, mjSTATE_INTEGRATION);
930
+ TrapCall(mj_getState, m, d, hist + static_cast<size_t>(k) * nstate_,
931
+ mjSTATE_INTEGRATION);
842
932
  }
843
933
  }
844
- if (forward_) mj_forward(m, d); // derived fields current with the new state
934
+ if (forward_) TrapCall(mj_forward, m, d); // derived fields current with new state
845
935
  break;
846
936
  }
847
937
  case Op::Substep: {
@@ -855,12 +945,12 @@ class Batch {
855
945
  }
856
946
  bool tail = cctx->tail_only;
857
947
  if (!cctx->tail_only) {
858
- mj_step(m, d);
948
+ TrapCall(mj_step, m, d);
859
949
  if (cctx->hist) {
860
- mj_getState(m, d, cctx->hist + static_cast<size_t>(cctx->k) * nstate_,
861
- mjSTATE_INTEGRATION);
950
+ TrapCall(mj_getState, m, d,
951
+ cctx->hist + static_cast<size_t>(cctx->k) * nstate_, mjSTATE_INTEGRATION);
862
952
  }
863
- mj_getState(m, d, State(i), mjSTATE_INTEGRATION);
953
+ TrapCall(mj_getState, m, d, State(i), mjSTATE_INTEGRATION);
864
954
  std::memcpy(Warning(i), d->warning, sizeof(d->warning));
865
955
  if (cctx->k + 1 == cctx->nstep) tail = true;
866
956
  }
@@ -868,7 +958,7 @@ class Batch {
868
958
  cctx->done[0] = 1;
869
959
  // A tail after an exception always forwards, so derived fields are current
870
960
  // with the state the sim stopped at rather than one substep behind.
871
- if (forward_ || cctx->tail_only) mj_forward(m, d);
961
+ if (forward_ || cctx->tail_only) TrapCall(mj_forward, m, d);
872
962
  if (cctx->tail_only) std::memcpy(Warning(i), d->warning, sizeof(d->warning));
873
963
  for (auto& s : bound_) CopyOut(*s, d, i);
874
964
  return;
@@ -876,7 +966,7 @@ class Batch {
876
966
  case Op::Substep1: {
877
967
  // Position- and velocity-stage sensors are current with State(i) here.
878
968
  // Input mirrors stay stale because Substep2 applies the callback writes.
879
- mj_step1(m, d);
969
+ TrapCall(mj_step1, m, d);
880
970
  CopySensorRange(*cctx->sensor, d, i, cctx->sensor_start, cctx->sensor_width);
881
971
  return;
882
972
  }
@@ -885,47 +975,58 @@ class Batch {
885
975
  // per-sim snapshot. Stage one is recomputed after State(i) and the
886
976
  // callback writes have been loaded; the sensor view copied above is
887
977
  // still the fresh result at x_k. Sync mirrors only after mj_step2.
888
- mj_step1(m, d);
978
+ TrapCall(mj_step1, m, d);
889
979
  for (auto& s : bound_) {
890
980
  if (s->mirror) {
891
981
  std::memcpy(s->mirror.get() + i * s->row, s->buf.get() + i * s->row, s->row);
892
982
  }
893
983
  }
894
- mj_step2(m, d);
984
+ TrapCall(mj_step2, m, d);
895
985
  if (cctx->hist) {
896
- mj_getState(m, d, cctx->hist + static_cast<size_t>(cctx->k) * nstate_,
897
- mjSTATE_INTEGRATION);
986
+ TrapCall(mj_getState, m, d,
987
+ cctx->hist + static_cast<size_t>(cctx->k) * nstate_, mjSTATE_INTEGRATION);
898
988
  }
899
- mj_getState(m, d, State(i), mjSTATE_INTEGRATION);
989
+ TrapCall(mj_getState, m, d, State(i), mjSTATE_INTEGRATION);
900
990
  std::memcpy(Warning(i), d->warning, sizeof(d->warning));
901
991
  if (cctx->k + 1 != cctx->nstep) return;
902
992
  cctx->done[0] = 1;
903
- if (forward_) mj_forward(m, d);
993
+ if (forward_) TrapCall(mj_forward, m, d);
904
994
  for (auto& s : bound_) CopyOut(*s, d, i);
905
995
  return;
906
996
  }
907
997
  case Op::Forward:
908
998
  case Op::Reset:
909
- mj_forward(m, d);
999
+ TrapCall(mj_forward, m, d);
910
1000
  break;
1001
+ case Op::RefreshSensor:
1002
+ TrapCall(mj_kinematics, m, d);
1003
+ TrapCall(mj_comPos, m, d);
1004
+ TrapCall(mj_comVel, m, d);
1005
+ TrapCall(mj_sensorPos, m, d);
1006
+ TrapCall(mj_sensorVel, m, d);
1007
+ for (int j = 0; j < static_cast<int>(ctx->sensor_ranges->size()); j += 2) {
1008
+ CopySensorRange(*ctx->sensor, d, i, (*ctx->sensor_ranges)[j],
1009
+ (*ctx->sensor_ranges)[j + 1] - (*ctx->sensor_ranges)[j]);
1010
+ }
1011
+ return;
911
1012
  // The query ops run kinematics only: they do not change the integration
912
1013
  // state, so the copy-out tail below is skipped. mjData is shared by every
913
1014
  // sim a worker serves, and copying out would leak another sim's stale
914
1015
  // derived fields into the bound views; the outputs are the
915
1016
  // caller-allocated rows.
916
1017
  case Op::JacSite:
917
- mj_kinematics(m, d);
918
- mj_comPos(m, d);
919
- mj_jacSite(m, d, ctx->jacp, ctx->jacr, ctx->site);
1018
+ TrapCall(mj_kinematics, m, d);
1019
+ TrapCall(mj_comPos, m, d);
1020
+ TrapCall(mj_jacSite, m, d, ctx->jacp, ctx->jacr, ctx->site);
920
1021
  return;
921
1022
  case Op::SampleHfield:
922
- mj_kinematics(m, d);
1023
+ TrapCall(mj_kinematics, m, d);
923
1024
  SampleHfield(m, d, *ctx);
924
1025
  return;
925
1026
  case Op::SetConst:
926
1027
  break;
927
1028
  }
928
- mj_getState(m, d, State(i), mjSTATE_INTEGRATION);
1029
+ TrapCall(mj_getState, m, d, State(i), mjSTATE_INTEGRATION);
929
1030
  std::memcpy(Warning(i), d->warning, sizeof(d->warning));
930
1031
  for (auto& s : bound_) CopyOut(*s, d, i);
931
1032
  }
@@ -958,22 +1059,22 @@ class Batch {
958
1059
  return out;
959
1060
  }
960
1061
 
961
- void Guarded(int t, int i, Op op, int arg, mjtNum* hist, const QueryCtx* ctx,
1062
+ // TrapCall throws only after its short longjmp has returned to C++, so the
1063
+ // exception can unwind RunSim normally instead of crossing MuJoCo C frames.
1064
+ bool Guarded(int t, int i, Op op, int arg, mjtNum* hist, const QueryCtx* ctx,
962
1065
  const CallbackCtx* cctx) {
963
- std::jmp_buf jb;
964
- tls_jmp = &jb;
965
- if (setjmp(jb) == 0) {
1066
+ try {
966
1067
  RunSim(t, i, op, arg, hist, ctx, cctx);
967
- } else {
1068
+ } catch (const MjError&) {
968
1069
  // The sim's state was not written back; the worker's mjData, left
969
1070
  // mid-call with its stack and arena in use, serves other sims next.
970
- tls_jmp = nullptr;
971
1071
  if (op == Op::SetConst) Restore(models_[t]);
972
1072
  mj_resetData(template_, data_[t]);
973
1073
  std::lock_guard<std::mutex> lock(changed_mu_);
974
1074
  if (error_.empty()) error_ = "sim " + std::to_string(i) + ": " + tls_error;
1075
+ return false;
975
1076
  }
976
- tls_jmp = nullptr;
1077
+ return true;
977
1078
  }
978
1079
 
979
1080
  void Run(Op op, std::optional<std::vector<int>> sel, int arg, mjtNum* hist = nullptr,
@@ -982,7 +1083,9 @@ class Batch {
982
1083
  std::lock_guard<std::mutex> lock(mu_);
983
1084
  error_.clear();
984
1085
  RunLocked(op, sel, arg, hist, ctx);
985
- if (!error_.empty()) throw std::runtime_error(error_);
1086
+ if (!error_.empty()) {
1087
+ throw std::runtime_error(error_);
1088
+ }
986
1089
  }
987
1090
 
988
1091
  // A per-sim enableflags must not switch on what the constructor refused. Raised
@@ -1037,8 +1140,10 @@ class Batch {
1037
1140
  if (row_ctx.out) row_ctx.out += static_cast<size_t>(j) * row_ctx.npoint;
1038
1141
  c = &row_ctx;
1039
1142
  }
1040
- Guarded(t, p ? p[j] : j, op, arg,
1041
- hist ? hist + static_cast<size_t>(j) * arg * nstate_ : nullptr, c, nullptr);
1143
+ if (!Guarded(t, p ? p[j] : j, op, arg,
1144
+ hist ? hist + static_cast<size_t>(j) * arg * nstate_ : nullptr, c, nullptr)) {
1145
+ return;
1146
+ }
1042
1147
  };
1043
1148
  if (pool_->size() == 1) {
1044
1149
  for (int j = 0; j < n; ++j) fn(0, j);
@@ -1063,7 +1168,7 @@ class Batch {
1063
1168
  CallbackCtx row = base;
1064
1169
  if (hist) row.hist = hist + static_cast<size_t>(j) * nstep * nstate_;
1065
1170
  row.done = done + j;
1066
- Guarded(t, p ? p[j] : j, op, k, nullptr, nullptr, &row);
1171
+ if (!Guarded(t, p ? p[j] : j, op, k, nullptr, nullptr, &row)) return;
1067
1172
  };
1068
1173
  if (pool_->size() == 1) {
1069
1174
  for (int j = 0; j < n; ++j) fn(0, j);
@@ -13,7 +13,6 @@ using namespace nb::literals;
13
13
  NB_MODULE(_bindings, m) {
14
14
  // Bound arrays keep their Batch alive by design, often until exit.
15
15
  nb::set_leak_warnings(false);
16
- InstallLogTrap();
17
16
  if (mj_version() != mjVERSION_HEADER) {
18
17
  throw std::runtime_error("mjbatch was built against MuJoCo " +
19
18
  std::to_string(mjVERSION_HEADER) + " but " +
@@ -60,8 +59,9 @@ changed, so derived constants are per simulation too; mjModel scalars it writes
60
59
  Derived constants follow expanded inputs only after set_const, as with
61
60
  mj_setConst on one model. A MuJoCo error on a worker raises RuntimeError naming
62
61
  the first failing simulation; the others still ran, and the failing one keeps the
63
- state it had before the call, its writes still pending. The trap is a MuJoCo log
64
- handler installed at import; installing another handler later disables it.)")
62
+ state it had before the call, its writes still pending. Errors are trapped with a
63
+ thread-local MuJoCo handler scoped to each worker call, so process-global handlers
64
+ remain available to the application.)")
65
65
  .def(nb::init<nb::object, int, int, bool, std::optional<std::vector<int>>>(), "model"_a,
66
66
  "num_sims"_a, "num_threads"_a = 0, "forward"_a = false, "cpu_ids"_a = nb::none(),
67
67
  "num_threads=0 uses every logical CPU, clamped to num_sims. forward=True ends "
@@ -99,6 +99,18 @@ handler installed at import; installing another handler later disables it.)")
99
99
  "so they affect the current substep. If the callback raises, state remains at "
100
100
  "the last completed substep; intermediate mjData is recovered on the next call.")
101
101
  .def("forward", &Batch::forward, "ids"_a.noconvert() = nb::none())
102
+ .def("refresh_sensor_range", &Batch::refresh_sensor_range, "ids"_a.noconvert() = nb::none(),
103
+ "sensor_range"_a,
104
+ "Refresh position- and velocity-stage sensors in a half-open sensordata column "
105
+ "range from each selected simulation's final integration state. The work runs "
106
+ "in native worker threads and only the declared columns are copied into the "
107
+ "bound sensordata view; acceleration-stage sensors (including contact forces) "
108
+ "and every other bound field are preserved.")
109
+ .def("refresh_sensor_ranges", &Batch::refresh_sensor_ranges, "ids"_a.noconvert() = nb::none(),
110
+ "sensor_ranges"_a,
111
+ "Refresh disjoint position- and velocity-stage sensor column ranges, expressed "
112
+ "as a flattened sequence of half-open (start, stop) pairs. Semantics match "
113
+ "refresh_sensor_range(); columns outside every requested range are preserved.")
102
114
  .def("reset", &Batch::reset, "ids"_a.noconvert() = nb::none(), "keyframe"_a = -1,
103
115
  "mj_resetData, or mj_resetDataKeyframe when keyframe >= 0, then mj_forward.")
104
116
  .def("jac_site", &Batch::jac_site, "site"_a, "jacp"_a.noconvert() = nb::none(),
@@ -52,7 +52,18 @@ _SHARED_PARAMETER_PREFIXES = (
52
52
  "qpos0",
53
53
  "qpos_spring",
54
54
  )
55
- _IGNORED_COMPILER_FLAGS = frozenset({"body_sameframe", "geom_sameframe"})
55
+ # Compiler-derived fields, not structure: ``body_simple``/``dof_simplenum``
56
+ # are fast-path flags/counts the compiler derives from each variant's own
57
+ # inertial frames, and ``light_poscom0`` is derived from the model's center of
58
+ # mass. They legitimately differ across same-layout variants whose allowed
59
+ # per-variant fields (``body_mass``/``body_ipos``/``body_iquat``/
60
+ # ``body_inertia``, geom pose/size) already carry the underlying physics, and
61
+ # none of them changes the dynamics computed with the canonical model's
62
+ # flags. Treating them as shared skeleton parameters falsely rejects
63
+ # mass-varying pools (unilabsim/mjbatch_uni#33).
64
+ _IGNORED_COMPILER_FLAGS = frozenset(
65
+ {"body_sameframe", "geom_sameframe", "body_simple", "dof_simplenum", "light_poscom0"}
66
+ )
56
67
  _IGNORED_COMPILER_METADATA_PREFIXES = ("body_geom", "body_bvh", "geom_bvh")
57
68
 
58
69
  _LAYOUT_SCALARS = (
@@ -142,6 +153,7 @@ class VariantPack:
142
153
  mesh_names[mesh.name] = pooled_name
143
154
  mesh_names_by_variant.append(mesh_names)
144
155
 
156
+ _disable_simple_where_variants_break_inertial_frame(canonical_spec, reference_models, canonical_index)
145
157
  canonical = canonical_spec.compile()
146
158
  _validate_layout(reference_models, canonical)
147
159
  geom_maps = _validate_names_and_build_geom_maps(reference_models, canonical)
@@ -349,6 +361,44 @@ def _validate_shared_parameters(
349
361
  raise ValueError(f"variant {variant} changes shared field {name}")
350
362
 
351
363
 
364
+ def _disable_simple_where_variants_break_inertial_frame(
365
+ canonical_spec: mujoco.MjSpec,
366
+ references: Sequence[mujoco.MjModel],
367
+ canonical_index: int,
368
+ ) -> None:
369
+ """Force the general (non-simple) code path where variant inertia requires it.
370
+
371
+ The compiler marks a body ``simple`` when its inertial frame coincides with
372
+ the body frame (zero ``ipos``, identity ``iquat``), and the batch executor
373
+ refuses per-variant inertial writes that break that invariant on a simple
374
+ canonical body ("compiled as simple but sameframe no longer holds").
375
+ Variant pools legitimately differ in exactly those allowed variant fields,
376
+ so the canonical model must not carry the fast-path flag on such bodies.
377
+ ``simple=False`` is a codegen hint only; the compiled dynamics are
378
+ numerically identical.
379
+ """
380
+ canonical = references[canonical_index]
381
+ # MjSpec.bodies is the flattened depth-first list, aligned with the compiled
382
+ # model's body ids (world first in both).
383
+ spec_bodies = list(canonical_spec.bodies)[1:]
384
+ if len(spec_bodies) != canonical.nbody - 1:
385
+ raise ValueError(
386
+ f"canonical spec has {len(spec_bodies)} bodies but its compiled model has "
387
+ f"{canonical.nbody - 1}; cannot map the simple flags"
388
+ )
389
+ zero = np.zeros(3)
390
+ identity = np.array([1.0, 0.0, 0.0, 0.0])
391
+ for spec_body, body_id in zip(spec_bodies, range(1, canonical.nbody), strict=True):
392
+ if not canonical.body_simple[body_id]:
393
+ continue
394
+ for reference in references:
395
+ if not np.array_equal(reference.body_ipos[body_id], zero) or not np.array_equal(
396
+ reference.body_iquat[body_id], identity
397
+ ):
398
+ spec_body.simple = False
399
+ break
400
+
401
+
352
402
  def _validate_shared_options(
353
403
  references: Sequence[mujoco.MjModel],
354
404
  canonical: mujoco.MjModel,
@@ -1,43 +0,0 @@
1
- cmake_minimum_required(VERSION 3.15...3.30)
2
- project(${SKBUILD_PROJECT_NAME} LANGUAGES CXX)
3
-
4
- find_package(Python 3.10 COMPONENTS Interpreter Development.Module REQUIRED)
5
-
6
- execute_process(
7
- COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
8
- OUTPUT_STRIP_TRAILING_WHITESPACE
9
- OUTPUT_VARIABLE nanobind_ROOT)
10
- find_package(nanobind CONFIG REQUIRED)
11
-
12
- # Headers and libmujoco come from the installed mujoco wheel.
13
- execute_process(
14
- COMMAND "${Python_EXECUTABLE}" -c
15
- "import mujoco, pathlib; print(pathlib.Path(mujoco.__file__).parent)"
16
- OUTPUT_STRIP_TRAILING_WHITESPACE
17
- OUTPUT_VARIABLE MUJOCO_PKG_DIR
18
- COMMAND_ERROR_IS_FATAL ANY)
19
- file(GLOB MUJOCO_LIBRARY "${MUJOCO_PKG_DIR}/libmujoco*${CMAKE_SHARED_LIBRARY_SUFFIX}*")
20
- if(NOT MUJOCO_LIBRARY)
21
- message(FATAL_ERROR "Could not find libmujoco in ${MUJOCO_PKG_DIR}")
22
- endif()
23
- list(GET MUJOCO_LIBRARY 0 MUJOCO_LIBRARY)
24
-
25
- nanobind_add_module(_bindings FREE_THREADED NOMINSIZE src/mjbatch/csrc/bindings.cpp)
26
- target_include_directories(_bindings PRIVATE "${MUJOCO_PKG_DIR}/include")
27
- target_link_libraries(_bindings PRIVATE "${MUJOCO_LIBRARY}")
28
-
29
- # Find libmujoco next to the installed extension, <site-packages>/mujoco. The
30
- # macOS wheel's install name is a framework path that does not exist, so point
31
- # our load command at the plain file name instead.
32
- if(APPLE)
33
- get_filename_component(MUJOCO_LIB_NAME "${MUJOCO_LIBRARY}" NAME)
34
- execute_process(COMMAND otool -D "${MUJOCO_LIBRARY}" OUTPUT_VARIABLE _otool)
35
- string(REGEX MATCH "@rpath[^\n]*" MUJOCO_INSTALL_NAME "${_otool}")
36
- add_custom_command(TARGET _bindings POST_BUILD COMMAND install_name_tool -change
37
- "${MUJOCO_INSTALL_NAME}" "@rpath/${MUJOCO_LIB_NAME}" $<TARGET_FILE:_bindings>)
38
- set_target_properties(_bindings PROPERTIES INSTALL_RPATH "@loader_path/../mujoco")
39
- else()
40
- set_target_properties(_bindings PROPERTIES INSTALL_RPATH "$ORIGIN/../mujoco")
41
- endif()
42
-
43
- install(TARGETS _bindings DESTINATION mjbatch)
File without changes