MFC: warning C4244: “参数”: 从“double”转换到“float”,可能丢失数据

本文介绍如何在stdafx.h文件中通过添加#pragma warning(disable:4244)来禁用特定的编译器警告。这有助于减少编译时的警告信息,但可能会影响代码质量。若项目不涉及大量数据转换,此方法较为适用。
stdafx.h 文件中:

增加一行代码即可过滤此提示:

#pragma warning(disable:4244)

重新编译即可,但是有时候不建议去除这个,
有这个提示有利于写好代码,
当然如果整个工程里面不会涉及大数据,
过滤掉这个提示基本没问题

Windows PowerShell 版权所有(C) Microsoft Corporation。保留所有权利。 安装最新的 PowerShell,了解新功能和改进!https://aka.ms/PSWindows PS F:\pythonten\project> cl 用于 x64 的 Microsoft (R) C/C++ 优化编译器 19.44.35209 版 版权所有(C) Microsoft Corporation。保留所有权利。 用法: cl [ 选项... ] 文件名... [ /link 链接选项... ] PS F:\pythonten\project> pip install mnnpy -i https://pypi.tuna.tsinghua.edu.cn/simple/ Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple/ Collecting mnnpy Using cached https://pypi.tuna.tsinghua.edu.cn/packages/c2/6e/e8f963203e552d80a04adf80b19ecb248fa949b3db7a6fc935a2f49e8454/mnnpy-0.1.9.5.tar.gz (117 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Requirement already satisfied: numpy in f:\pythonten\python310\lib\site-packages (from mnnpy) (1.26.3) Requirement already satisfied: scipy in f:\pythonten\python310\lib\site-packages (from mnnpy) (1.12.0) Requirement already satisfied: anndata in f:\pythonten\python310\lib\site-packages (from mnnpy) (0.9.2) Requirement already satisfied: pandas in f:\pythonten\python310\lib\site-packages (from mnnpy) (2.2.0) Requirement already satisfied: numba in f:\pythonten\python310\lib\site-packages (from mnnpy) (0.58.1) Requirement already satisfied: h5py>=3 in f:\pythonten\python310\lib\site-packages (from anndata->mnnpy) (3.10.0) Requirement already satisfied: natsort in f:\pythonten\python310\lib\site-packages (from anndata->mnnpy) (8.4.0) Requirement already satisfied: packaging>=20 in f:\pythonten\python310\lib\site-packages (from anndata->mnnpy) (23.2) Requirement already satisfied: python-dateutil>=2.8.2 in f:\pythonten\python310\lib\site-packages (from pandas->mnnpy) (2.8.2) Requirement already satisfied: pytz>=2020.1 in f:\pythonten\python310\lib\site-packages (from pandas->mnnpy) (2023.3.post1) Requirement already satisfied: tzdata>=2022.7 in f:\pythonten\python310\lib\site-packages (from pandas->mnnpy) (2023.4) Requirement already satisfied: six>=1.5 in f:\pythonten\python310\lib\site-packages (from python-dateutil>=2.8.2->pandas->mnnpy) (1.16.0) Requirement already satisfied: llvmlite<0.42,>=0.41.0dev0 in f:\pythonten\python310\lib\site-packages (from numba->mnnpy) (0.41.1) Building wheels for collected packages: mnnpy Building wheel for mnnpy (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for mnnpy (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [73 lines of output] C:\Users\Lenovo\AppData\Local\Temp\pip-build-env-2jqu8z5o\overlay\Lib\site-packages\setuptools\dist.py:599: SetuptoolsDeprecationWarning: Invalid dash-separated key 'python-tag' in 'bdist_wheel' (setup.cfg), please use the underscore name 'python_tag' instead. !! ******************************************************************************** Usage of dash-separated 'python-tag' will not be supported in future versions. Please use the underscore name 'python_tag' instead. (Affected: mnnpy). By 2026-Mar-03, you need to update your project and remove deprecated calls or your builds will no longer be supported. See https://setuptools.pypa.io/en/latest/userguide/declarative_config.html for details. ******************************************************************************** !! opt = self._enforce_underscore(opt, section) C:\Users\Lenovo\AppData\Local\Temp\pip-build-env-2jqu8z5o\overlay\Lib\site-packages\setuptools\dist.py:759: SetuptoolsDeprecationWarning: License classifiers are deprecated. !! ******************************************************************************** Please consider removing the following classifiers in favor of a SPDX license expression: License :: OSI Approved :: BSD License See https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#license for details. ******************************************************************************** !! self._finalize_license_expression() Building with c. running bdist_wheel running build running build_py file irlb.py (for module irlb) not found file mnn.py (for module mnn) not found file utils.py (for module utils) not found creating build\lib.win-amd64-cpython-310\mnnpy copying mnnpy\irlb.py -> build\lib.win-amd64-cpython-310\mnnpy copying mnnpy\mnn.py -> build\lib.win-amd64-cpython-310\mnnpy copying mnnpy\settings.py -> build\lib.win-amd64-cpython-310\mnnpy copying mnnpy\utils.py -> build\lib.win-amd64-cpython-310\mnnpy copying mnnpy\__init__.py -> build\lib.win-amd64-cpython-310\mnnpy file irlb.py (for module irlb) not found file mnn.py (for module mnn) not found file utils.py (for module utils) not found running build_ext building 'mnnpy._utils' extension creating build\temp.win-amd64-cpython-310\Release\mnnpy "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.44.35207\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -IF:\pythonten\python310\include -IF:\pythonten\python310 \Include "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.44.35207\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.44.35207\ATLMFC\include" "- IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.26100.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0 .26100.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\cppwinrt" /Tcmnnpy/_utils.c /Fobuild\temp.win-amd64-cpython-310\Release\mnnpy\_utils.obj -O2 -ffast-math -march=native -fopenmp cl: 命令行 warning D9002 :忽略未知选项“-ffast-math” cl: 命令行 warning D9002 :忽略未知选项“-march=native” cl: 命令行 warning D9002 :忽略未知选项“-fopenmp” _utils.c mnnpy/_utils.c(2117): warning C4244: “=”: 从“double转换到“float”,可能丢失数据 mnnpy/_utils.c(2359): warning C4244: “=”: 从“double转换到“float”,可能丢失数据 mnnpy/_utils.c(2576): warning C4244: “=”: 从“double转换到“float”,可能丢失数据 mnnpy/_utils.c(16475): error C2105: “++”需要左值 mnnpy/_utils.c(16477): error C2105: “--”需要左值 mnnpy/_utils.c(16764): error C2105: “++”需要左值 mnnpy/_utils.c(16766): error C2105: “--”需要左值 mnnpy/_utils.c(17003): error C2105: “++”需要左值 mnnpy/_utils.c(17005): error C2105: “--”需要左值 mnnpy/_utils.c(17615): warning C4996: 'PyEval_InitThreads': deprecated in 3.9 mnnpy/_utils.c(17674): error C2039: "tp_print": 不是 "_typeobject" 的成员 F:\pythonten\python310\include\cpython/object.h(191): note: 参见“_typeobject”的声明 mnnpy/_utils.c(17679): error C2039: "tp_print": 不是 "_typeobject" 的成员 F:\pythonten\python310\include\cpython/object.h(191): note: 参见“_typeobject”的声明 mnnpy/_utils.c(17694): error C2039: "tp_print": 不是 "_typeobject" 的成员 F:\pythonten\python310\include\cpython/object.h(191): note: 参见“_typeobject”的声明 mnnpy/_utils.c(17707): error C2039: "tp_print": 不是 "_typeobject" 的成员 F:\pythonten\python310\include\cpython/object.h(191): note: 参见“_typeobject”的声明 mnnpy/_utils.c(19372): warning C4996: 'PyUnicode_FromUnicode': deprecated in 3.3 error: command 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.44.35207\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mnnpy Failed to build mnnpy ERROR: Failed to build installable wheels for some pyproject.toml based projects (mnnpy) PS F:\pythonten\project> pip install mnnpy Collecting mnnpy Using cached mnnpy-0.1.9.5.tar.gz (117 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Requirement already satisfied: numpy in f:\pythonten\python310\lib\site-packages (from mnnpy) (1.26.3) Requirement already satisfied: scipy in f:\pythonten\python310\lib\site-packages (from mnnpy) (1.12.0) Requirement already satisfied: anndata in f:\pythonten\python310\lib\site-packages (from mnnpy) (0.9.2) Requirement already satisfied: pandas in f:\pythonten\python310\lib\site-packages (from mnnpy) (2.2.0) Requirement already satisfied: numba in f:\pythonten\python310\lib\site-packages (from mnnpy) (0.58.1) Requirement already satisfied: h5py>=3 in f:\pythonten\python310\lib\site-packages (from anndata->mnnpy) (3.10.0) Requirement already satisfied: natsort in f:\pythonten\python310\lib\site-packages (from anndata->mnnpy) (8.4.0) Requirement already satisfied: packaging>=20 in f:\pythonten\python310\lib\site-packages (from anndata->mnnpy) (23.2) Requirement already satisfied: python-dateutil>=2.8.2 in f:\pythonten\python310\lib\site-packages (from pandas->mnnpy) (2.8.2) Requirement already satisfied: pytz>=2020.1 in f:\pythonten\python310\lib\site-packages (from pandas->mnnpy) (2023.3.post1) Requirement already satisfied: tzdata>=2022.7 in f:\pythonten\python310\lib\site-packages (from pandas->mnnpy) (2023.4) Requirement already satisfied: six>=1.5 in f:\pythonten\python310\lib\site-packages (from python-dateutil>=2.8.2->pandas->mnnpy) (1.16.0) Requirement already satisfied: llvmlite<0.42,>=0.41.0dev0 in f:\pythonten\python310\lib\site-packages (from numba->mnnpy) (0.41.1) Building wheels for collected packages: mnnpy Building wheel for mnnpy (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for mnnpy (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [73 lines of output] C:\Users\Lenovo\AppData\Local\Temp\pip-build-env-sra4z_m5\overlay\Lib\site-packages\setuptools\dist.py:599: SetuptoolsDeprecationWarning: Invalid dash-separated key 'python-tag' in 'bdist_wheel' (setup.cfg), please use the underscore name 'python_tag' instead. !! ******************************************************************************** Usage of dash-separated 'python-tag' will not be supported in future versions. Please use the underscore name 'python_tag' instead. (Affected: mnnpy). By 2026-Mar-03, you need to update your project and remove deprecated calls or your builds will no longer be supported. See https://setuptools.pypa.io/en/latest/userguide/declarative_config.html for details. ******************************************************************************** !! opt = self._enforce_underscore(opt, section) C:\Users\Lenovo\AppData\Local\Temp\pip-build-env-sra4z_m5\overlay\Lib\site-packages\setuptools\dist.py:759: SetuptoolsDeprecationWarning: License classifiers are deprecated. !! ******************************************************************************** Please consider removing the following classifiers in favor of a SPDX license expression: License :: OSI Approved :: BSD License See https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#license for details. ******************************************************************************** !! self._finalize_license_expression() Building with c. running bdist_wheel running build running build_py file irlb.py (for module irlb) not found file mnn.py (for module mnn) not found file utils.py (for module utils) not found creating build\lib.win-amd64-cpython-310\mnnpy copying mnnpy\irlb.py -> build\lib.win-amd64-cpython-310\mnnpy copying mnnpy\mnn.py -> build\lib.win-amd64-cpython-310\mnnpy copying mnnpy\settings.py -> build\lib.win-amd64-cpython-310\mnnpy copying mnnpy\utils.py -> build\lib.win-amd64-cpython-310\mnnpy copying mnnpy\__init__.py -> build\lib.win-amd64-cpython-310\mnnpy file irlb.py (for module irlb) not found file mnn.py (for module mnn) not found file utils.py (for module utils) not found running build_ext building 'mnnpy._utils' extension creating build\temp.win-amd64-cpython-310\Release\mnnpy "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.44.35207\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -IF:\pythonten\python310\include -IF:\pythonten\python310 \Include "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.44.35207\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.44.35207\ATLMFC\include" "- IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.26100.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0 .26100.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\cppwinrt" /Tcmnnpy/_utils.c /Fobuild\temp.win-amd64-cpython-310\Release\mnnpy\_utils.obj -O2 -ffast-math -march=native -fopenmp cl: 命令行 warning D9002 :忽略未知选项“-ffast-math” cl: 命令行 warning D9002 :忽略未知选项“-march=native” cl: 命令行 warning D9002 :忽略未知选项“-fopenmp” _utils.c mnnpy/_utils.c(2117): warning C4244: “=”: 从“double转换到“float”,可能丢失数据 mnnpy/_utils.c(2359): warning C4244: “=”: 从“double转换到“float”,可能丢失数据 mnnpy/_utils.c(2576): warning C4244: “=”: 从“double转换到“float”,可能丢失数据 mnnpy/_utils.c(16475): error C2105: “++”需要左值 mnnpy/_utils.c(16477): error C2105: “--”需要左值 mnnpy/_utils.c(16764): error C2105: “++”需要左值 mnnpy/_utils.c(16766): error C2105: “--”需要左值 mnnpy/_utils.c(17003): error C2105: “++”需要左值 mnnpy/_utils.c(17005): error C2105: “--”需要左值 mnnpy/_utils.c(17615): warning C4996: 'PyEval_InitThreads': deprecated in 3.9 mnnpy/_utils.c(17674): error C2039: "tp_print": 不是 "_typeobject" 的成员 F:\pythonten\python310\include\cpython/object.h(191): note: 参见“_typeobject”的声明 mnnpy/_utils.c(17679): error C2039: "tp_print": 不是 "_typeobject" 的成员 F:\pythonten\python310\include\cpython/object.h(191): note: 参见“_typeobject”的声明 mnnpy/_utils.c(17694): error C2039: "tp_print": 不是 "_typeobject" 的成员 F:\pythonten\python310\include\cpython/object.h(191): note: 参见“_typeobject”的声明 mnnpy/_utils.c(17707): error C2039: "tp_print": 不是 "_typeobject" 的成员 F:\pythonten\python310\include\cpython/object.h(191): note: 参见“_typeobject”的声明 mnnpy/_utils.c(19372): warning C4996: 'PyUnicode_FromUnicode': deprecated in 3.3 error: command 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.44.35207\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mnnpy Failed to build mnnpy ERROR: Failed to build installable wheels for some pyproject.toml based projects (mnnpy)
06-08
(pytorch) F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops>python setup.py build install running build running build_py running build_ext C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\utils\cpp_extension.py:411: UserWarning: Attempted to use ninja as the BuildExtension backend but we could not find ninja.. Falling back to using the slow distutils backend. warnings.warn(msg.format('we could not find ninja.')) C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\utils\cpp_extension.py:346: UserWarning: Error checking compiler version for cl: [WinError 2] 系统找不到指定的文件。 warnings.warn(f'Error checking compiler version for {compiler}: {error}') "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -DWITH_CUDA -IF:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src -IC:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include -IC:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\torch\csrc\api\include -IC:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\TH -IC:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\THC "-IC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.3\include" -IC:\Users\QML\AppData\Local\conda\conda\envs\pytorch\include -IC:\Users\QML\AppData\Local\conda\conda\envs\pytorch\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt" /EHsc /TpF:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cpu\ms_deform_attn_cpu.cpp /Fobuild\temp.win-amd64-3.8\Release\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cpu\ms_deform_attn_cpu.obj /MD /wd4819 /wd4251 /wd4244 /wd4267 /wd4275 /wd4018 /wd4190 /EHsc -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=MultiScaleDeformableAttention -D_GLIBCXX_USE_CXX11_ABI=0 ms_deform_attn_cpu.cpp C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/macros/Macros.h(143): warning C4067: 预处理器指令后有意外标记 - 应输入换行符 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/core/TensorImpl.h(2214): warning C4805: “|”: 在操作中将类型“uintptr_t”与类型“bool”混合不安全 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=c10::impl::InlineDeviceGuard<c10::impl::VirtualGuardImpl> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=c10::impl::InlineDeviceGuard<c10::impl::VirtualGuardImpl> ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=c10::impl::InlineDeviceGuard<c10::impl::VirtualGuardImpl> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=c10::impl::InlineDeviceGuard<c10::impl::VirtualGuardImpl> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<c10::impl::InlineDeviceGuard<c10::impl::VirtualGuardImpl>>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/core/impl/InlineDeviceGuard.h(427): note: 参见对正在编译的 类 模板 实例化 "c10::optional<c10::impl::InlineDeviceGuard<c10::impl::VirtualGuardImpl>>" 的 引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/core/DeviceGuard.h(178): note: 参见对正在编译的 类 模板 实例化 "c10::impl::InlineOptionalDeviceGuard<c10::impl::VirtualGuardImpl>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/core/TensorImpl.h(2660): note: 参见对正在编译的 类 模板 实例化 "c10::C10_TensorImpl_Size_Check_Dummy_Class<199711,0,0,0,0,0,0,8>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/core/DispatchKeySet.h(237): note: 参见对正在编译的 类 模板 实例化 "std::initializer_list<c10::BackendComponent>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=c10::impl::InlineDeviceGuard<c10::impl::VirtualGuardImpl> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/TensorBase.h(807): warning C4522: “at::TensorBase”: 指定了多个赋值运算符 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=at::TensorBase ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=at::TensorBase ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=at::TensorBase ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=at::TensorBase ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<at::TensorBase>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/TensorBase.h(951): note: 参见对正在编译的 类 模板 实例化 "c10::optional<at::TensorBase>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=at::TensorBase ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/TensorBody.h(1392): warning C4522: “at::Tensor”: 指定了多个赋值运算符 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=at::Tensor ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=at::Tensor ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=at::Tensor ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=at::Tensor ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<at::Tensor>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/TensorBody.h(509): note: 参见对正在编译的 类 模板 实例化 "c10::optional<at::Tensor>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=at::Tensor ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=at::Generator ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=at::Generator ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=at::Generator ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=at::Generator ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<at::Generator>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/TensorBody.h(584): note: 参见对正在编译的 类 模板 实例化 "c10::optional<at::Generator>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=at::Generator ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=c10::DimVector ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=c10::DimVector ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=c10::DimVector ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=c10::DimVector ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<c10::DimVector>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/TensorIterator.h(766): note: 参见对正在编译的 类 模板 实例化 "c10::optional<c10::DimVector>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=c10::DimVector ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::string ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=std::string ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=std::string ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=std::string ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<std::string>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/jit_type_base.h(448): note: 参见对正在编译的 类 模板 实例化 "c10::optional<std::string>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::string ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=c10::QualifiedName ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=c10::QualifiedName ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=c10::QualifiedName ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=c10::QualifiedName ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<c10::QualifiedName>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/jit_type_base.h(696): note: 参见对正在编译的 类 模板 实例化 "c10::optional<c10::QualifiedName>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=c10::QualifiedName ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::shared_ptr<torch::jit::CompilationUnit> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=std::shared_ptr<torch::jit::CompilationUnit> ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=std::shared_ptr<torch::jit::CompilationUnit> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=std::shared_ptr<torch::jit::CompilationUnit> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<std::shared_ptr<torch::jit::CompilationUnit>>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/ivalue.h(1338): note: 参见对正在编译的 类 模板 实例化 "c10::optional<std::shared_ptr<torch::jit::CompilationUnit>>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::shared_ptr<torch::jit::CompilationUnit> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::weak_ptr<torch::jit::CompilationUnit> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=std::weak_ptr<torch::jit::CompilationUnit> ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=std::weak_ptr<torch::jit::CompilationUnit> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=std::weak_ptr<torch::jit::CompilationUnit> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<std::weak_ptr<torch::jit::CompilationUnit>>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/ivalue.h(1339): note: 参见对正在编译的 类 模板 实例化 "c10::optional<std::weak_ptr<torch::jit::CompilationUnit>>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::weak_ptr<torch::jit::CompilationUnit> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::vector<c10::ShapeSymbol,std::allocator<c10::ShapeSymbol>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=std::vector<c10::ShapeSymbol,std::allocator<c10::ShapeSymbol>> ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=std::vector<c10::ShapeSymbol,std::allocator<c10::ShapeSymbol>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=std::vector<c10::ShapeSymbol,std::allocator<c10::ShapeSymbol>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<std::vector<c10::ShapeSymbol,std::allocator<_Ty>>>" 的引用 with [ _Ty=c10::ShapeSymbol ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/jit_type.h(482): note: 参 见对正在编译的 类 模板 实例化 "c10::optional<std::vector<c10::ShapeSymbol,std::allocator<_Ty>>>" 的引用 with [ _Ty=c10::ShapeSymbol ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::vector<c10::ShapeSymbol,std::allocator<c10::ShapeSymbol>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::vector<c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type,std::allocator<c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=std::vector<c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type,std::allocator<c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type>> ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=std::vector<c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type,std::allocator<c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=std::vector<c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type,std::allocator<c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<std::vector<T,std::allocator<_Ty>>>" 的引用 with [ T=c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type, _Ty=c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/jit_type.h(441): note: 参 见对正在编译的 类 模板 实例化 "c10::optional<std::vector<T,std::allocator<_Ty>>>" 的引用 with [ T=c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type, _Ty=c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::vector<c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type,std::allocator<c10::impl::ScalarTypeToCPPType<c10::ScalarType::Bool>::type>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::vector<c10::optional<c10::Stride>,std::allocator<c10::optional<c10::Stride>>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=std::vector<c10::optional<c10::Stride>,std::allocator<c10::optional<c10::Stride>>> ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=std::vector<c10::optional<c10::Stride>,std::allocator<c10::optional<c10::Stride>>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=std::vector<c10::optional<c10::Stride>,std::allocator<c10::optional<c10::Stride>>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<std::vector<c10::optional<c10::Stride>,std::allocator<_Ty>>>" 的引用 with [ _Ty=c10::optional<c10::Stride> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/jit_type.h(567): note: 参 见对正在编译的 类 模板 实例化 "c10::optional<std::vector<c10::optional<c10::Stride>,std::allocator<_Ty>>>" 的引用 with [ _Ty=c10::optional<c10::Stride> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/jit_type.h(843): note: 参 见对正在编译的 类 模板 实例化 "c10::VaryingShape<c10::Stride>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::vector<c10::optional<c10::Stride>,std::allocator<c10::optional<c10::Stride>>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::vector<c10::optional<int64_t>,std::allocator<c10::optional<int64_t>>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=std::vector<c10::optional<int64_t>,std::allocator<c10::optional<int64_t>>> ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=std::vector<c10::optional<int64_t>,std::allocator<c10::optional<int64_t>>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=std::vector<c10::optional<int64_t>,std::allocator<c10::optional<int64_t>>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<std::vector<c10::optional<int64_t>,std::allocator<_Ty>>>" 的引用 with [ _Ty=c10::optional<int64_t> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/jit_type.h(567): note: 参 见对正在编译的 类 模板 实例化 "c10::optional<std::vector<c10::optional<int64_t>,std::allocator<_Ty>>>" 的引用 with [ _Ty=c10::optional<int64_t> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/jit_type.h(613): note: 参 见对正在编译的 类 模板 实例化 "c10::VaryingShape<int64_t>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::vector<c10::optional<int64_t>,std::allocator<c10::optional<int64_t>>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::vector<int64_t,std::allocator<int64_t>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=std::vector<int64_t,std::allocator<int64_t>> ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=std::vector<int64_t,std::allocator<int64_t>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=std::vector<int64_t,std::allocator<int64_t>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<std::vector<int64_t,std::allocator<_Ty>>>" 的引用 with [ _Ty=int64_t ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/jit_type.h(726): note: 参 见对正在编译的 类 模板 实例化 "c10::optional<std::vector<int64_t,std::allocator<_Ty>>>" 的引用 with [ _Ty=int64_t ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::vector<int64_t,std::allocator<int64_t>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=c10::impl::InlineStreamGuard<c10::impl::VirtualGuardImpl> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=c10::impl::InlineStreamGuard<c10::impl::VirtualGuardImpl> ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=c10::impl::InlineStreamGuard<c10::impl::VirtualGuardImpl> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=c10::impl::InlineStreamGuard<c10::impl::VirtualGuardImpl> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<c10::impl::InlineStreamGuard<c10::impl::VirtualGuardImpl>>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/core/impl/InlineStreamGuard.h(197): note: 参见对正在编译的 类 模板 实例化 "c10::optional<c10::impl::InlineStreamGuard<c10::impl::VirtualGuardImpl>>" 的 引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/core/StreamGuard.h(139): note: 参见对正在编译的 类 模板 实例化 "c10::impl::InlineOptionalStreamGuard<c10::impl::VirtualGuardImpl>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/jit_type.h(1945): note: 参见对正在编译的 类 模板 实例化 "c10::detail::getTypePtr_<c10::IntArrayRef>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=c10::impl::InlineStreamGuard<c10::impl::VirtualGuardImpl> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=c10::impl::VirtualGuardImpl ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=c10::impl::VirtualGuardImpl ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=c10::impl::VirtualGuardImpl ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=c10::impl::VirtualGuardImpl ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<c10::impl::VirtualGuardImpl>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/core/impl/InlineStreamGuard.h(232): note: 参见对正在编译的 类 模板 实例化 "c10::optional<T>" 的引用 with [ T=c10::impl::VirtualGuardImpl ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/core/StreamGuard.h(162): note: 参见对正在编译的 类 模板 实例化 "c10::impl::InlineMultiStreamGuard<c10::impl::VirtualGuardImpl>" 的引用 C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=c10::impl::VirtualGuardImpl ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(198): warning C4624: “c10::constexpr_storage_t<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::vector<c10::ivalue::Future::WeakStorage,std::allocator<c10::ivalue::Future::WeakStorage>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(397): note: 参见对正在编译的 类 模板 实例化 "c10::constexpr_storage_t<T>" 的引用 with [ T=std::vector<c10::ivalue::Future::WeakStorage,std::allocator<c10::ivalue::Future::WeakStorage>> ] C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\type_traits(842): note: 参见对正在编译的 类 模板 实例化 "c10::trivially_copyable_optimization_optional_base<T>" 的引用 with [ T=std::vector<c10::ivalue::Future::WeakStorage,std::allocator<c10::ivalue::Future::WeakStorage>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(528): note: 参见对正在编译的 类 模板 实例化 "std::is_copy_constructible<c10::trivially_copyable_optimization_optional_base<T>>" 的引用 with [ T=std::vector<c10::ivalue::Future::WeakStorage,std::allocator<c10::ivalue::Future::WeakStorage>> ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(540): note: 参见对正在编译的 别名 模板 实例化 "c10::OptionalBase<std::vector<c10::ivalue::Future::WeakStorage,std::allocator<_Ty>>>" 的 引用 with [ _Ty=c10::ivalue::Future::WeakStorage ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\ATen/core/ivalue_inl.h(834): note: 参见对正在编译的 类 模板 实例化 "c10::optional<std::vector<c10::ivalue::Future::WeakStorage,std::allocator<_Ty>>>" 的引 用 with [ _Ty=c10::ivalue::Future::WeakStorage ] C:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\c10/util/Optional.h(432): warning C4624: “c10::trivially_copyable_optimization_optional_base<T>”: 已将析构函数隐式定义为“已删除” with [ T=std::vector<c10::ivalue::Future::WeakStorage,std::allocator<c10::ivalue::Future::WeakStorage>> ] "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.3\bin\nvcc" -c F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu -o build\temp.win-amd64-3.8\Release\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.obj -IF:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src -IC:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include -IC:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\torch\csrc\api\include -IC:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\TH -IC:\Users\QML\AppData\Local\conda\conda\envs\pytorch\lib\site-packages\torch\include\THC "-IC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.3\include" -IC:\Users\QML\AppData\Local\conda\conda\envs\pytorch\include -IC:\Users\QML\AppData\Local\conda\conda\envs\pytorch\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt" -Xcudafe --diag_suppress=dll_interface_conflict_dllexport_assumed -Xcudafe --diag_suppress=dll_interface_conflict_none_assumed -Xcudafe --diag_suppress=field_without_dll_interface -Xcudafe --diag_suppress=base_class_has_different_dll_interface -Xcompiler /EHsc -Xcompiler /wd4190 -Xcompiler /wd4018 -Xcompiler /wd4275 -Xcompiler /wd4267 -Xcompiler /wd4244 -Xcompiler /wd4251 -Xcompiler /wd4819 -Xcompiler /MD -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_BFLOAT16_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr -DCUDA_HAS_FP16=1 -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=MultiScaleDeformableAttention -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_75,code=compute_75 -gencode=arch=compute_75,code=sm_75 --use-local-env ms_deform_attn_cuda.cu C:/Users/QML/AppData/Local/conda/conda/envs/pytorch/lib/site-packages/torch/include\c10/macros/Macros.h(143): warning C4067: 预处理器指令后有意外标记 - 应输入换行符 C:/Users/QML/AppData/Local/conda/conda/envs/pytorch/lib/site-packages/torch/include\c10/core/SymInt.h(84): warning: integer conversion resulted in a change of sign F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(127): error: identifier "grad_output_n" is undefined F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: type name is not allowed F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: expected an expression F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: identifier "per_sample_loc_size" is undefined F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: identifier "per_attn_weight_size" is undefined F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: identifier "grad_sampling_loc" is undefined F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: type name is not allowed F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: expected an expression F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: identifier "grad_attn_weight" is undefined F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: type name is not allowed F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: expected an expression F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: no instance of function template "ms_deformable_col2im_cuda" matches the argument list argument types are: (c10::cuda::CUDAStream, <error-type>, double *, int64_t *, int64_t *, <error-type>, <error-type>, const int, const int, const int, const int, const int, const int, const int, double *, <error-type>, <error-type>) F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: type name is not allowed F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: expected an expression F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: identifier "per_sample_loc_size" is undefined F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: identifier "per_attn_weight_size" is undefined F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: identifier "grad_sampling_loc" is undefined F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: type name is not allowed F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: expected an expression F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: identifier "grad_attn_weight" is undefined F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: type name is not allowed F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: expected an expression F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(128): error: no instance of function template "ms_deformable_col2im_cuda" matches the argument list argument types are: (c10::cuda::CUDAStream, <error-type>, float *, int64_t *, int64_t *, <error-type>, <error-type>, const int, const int, const int, const int, const int, const int, const int, float *, <error-type>, <error-type>) F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(145): error: identifier "grad_sampling_loc" is undefined F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(145): error: identifier "grad_attn_weight" is undefined F:/code/UniRGB-IR-main/detection/projects/ViTDet/vitdet/ops/src\cuda/ms_deform_im2col_cuda.cuh(258): warning: variable "q_col" was declared but never referenced detected during: instantiation of "void ms_deformable_im2col_gpu_kernel(int, const scalar_t *, const int64_t *, const int64_t *, const scalar_t *, const scalar_t *, int, int, int, int, int, int, int, scalar_t *) [with scalar_t=double]" (943): here instantiation of "void ms_deformable_im2col_cuda(cudaStream_t, const scalar_t *, const int64_t *, const int64_t *, const scalar_t *, const scalar_t *, int, int, int, int, int, int, int, scalar_t *) [with scalar_t=double]" F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(64): here F:/code/UniRGB-IR-main/detection/projects/ViTDet/vitdet/ops/src\cuda/ms_deform_im2col_cuda.cuh(258): warning: variable "q_col" was declared but never referenced detected during: instantiation of "void ms_deformable_im2col_gpu_kernel(int, const scalar_t *, const int64_t *, const int64_t *, const scalar_t *, const scalar_t *, int, int, int, int, int, int, int, scalar_t *) [with scalar_t=float]" (943): here instantiation of "void ms_deformable_im2col_cuda(cudaStream_t, const scalar_t *, const int64_t *, const int64_t *, const scalar_t *, const scalar_t *, int, int, int, int, int, int, int, scalar_t *) [with scalar_t=float]" F:\code\UniRGB-IR-main\detection\projects\ViTDet\vitdet\ops\src\cuda\ms_deform_attn_cuda.cu(64): here 25 errors detected in the compilation of "F:/code/UniRGB-IR-main/detection/projects/ViTDet/vitdet/ops/src/cuda/ms_deform_attn_cuda.cu". error: command 'C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.3\\bin\\nvcc.exe' failed with exit code 1
最新发布
07-23
void CappDlg::OnBnClickedAdmittanceControl() { // TODO: 在此添加控件通知处理程序代码 if (!m_bStiffnessControlActive) { if (!PathFileExists(_T("initial_stiffness_params.txt"))) { AfxMessageBox(_T("请先运行Python程序生成初始刚度参数")); return; } // 通知Python std::ofstream doneFile("control_done_signal.txt"); doneFile << "1"; doneFile.close(); StartStiffnessControl(); } else { StopStiffnessControl(); } } void CappDlg::OnBnClickedRotateyaxisIncremental() { //TODO: 在此添加控件通知处理程序代码 short ncid; ncid = TestOpenComm(0, 0); if (ncid < 0) { AfxMessageBox(_T("无法打开设备通信!")); return; } double deltaPose[12] = { 0,0,0,tx,ty,tz,0,0,0,0,0,0 }; // 初始化全0 // 2. 以最小角速度(0.1°/s)执行增量运动 short rv = BscImov( ncid, "VR", // 角速度模式(单位°/s) 0.1, // 0.1°/s(文档允许的最小值) "BASE", // 基于工具坐标系旋转 sToolno, // 工具号 deltaPose // 增量位姿 ); // 3. 错误处理 if (rv != 0) { char errMsg[256] = { 0 }; BscGetError(ncid); } rv = TestCloseComm(ncid); } void CappDlg::StartFileWatcher() { m_fileWatcherThread = std::thread([this]() { while (m_bFileWatcherRunning) { // 1. 检查初始参数 if (!m_bInitialParamsLoaded && PathFileExists(_T("initial_stiffness_params.txt"))) { std::lock_guard<std::mutex> lock(m_fileMutex); CStdioFile file; if (file.Open(_T("initial_stiffness_params.txt"), CFile::modeRead)) { CString strParams; file.ReadString(strParams); CT2CA convertedString(strParams); if (sscanf_s(convertedString, "%lf,%lf,%lf", &m_dStiffness[0], &m_dStiffness[1], &m_dStiffness[2]) == 3) { m_bInitialParamsLoaded = true; m_bParamsUpdated = true; CString strMsg; strMsg.Format(_T("初始刚度参数加载成功: %.1f, %.1f, %.1f"), m_dStiffness[0], m_dStiffness[1], m_dStiffness[2]); OutputDebugString(strMsg); // 通知Python std::ofstream doneFile("control_done_signal.txt"); doneFile << "1"; doneFile.close(); } file.Close(); //DeleteFile(_T("initial_stiffness_params.txt")); } } // 2. 检查新参数 if (PathFileExists(_T("new_stiffness_params.txt"))) { std::lock_guard<std::mutex> lock(m_fileMutex); CStdioFile file; if (file.Open(_T("new_stiffness_params.txt"), CFile::modeRead)) { CString strParams; file.ReadString(strParams); CT2CA convertedString(strParams); if (sscanf_s(convertedString, "%lf,%lf,%lf", &m_dStiffness[0], &m_dStiffness[1], &m_dStiffness[2]) == 3) { m_bParamsUpdated = true; CString strMsg; strMsg.Format(_T("新刚度参数接收: %.1f, %.1f, %.1f"), m_dStiffness[0], m_dStiffness[1], m_dStiffness[2]); OutputDebugString(strMsg); // 通知Python std::ofstream doneFile("control_done_signal.txt"); doneFile << "1"; doneFile.close(); } file.Close(); DeleteFile(_T("new_stiffness_params.txt")); } } // 3. 检查重置信号 if (PathFileExists(_T("reset_signal.txt"))) { std::lock_guard<std::mutex> lock(m_fileMutex); // 输出重置信息 OutputDebugString(_T("[INFO] 收到重置信号,开始重置机器人")); DeleteFile(_T("reset_signal.txt")); /*if (m_bStiffnessControlActive) { m_bStiffnessControlActive = false; if (m_stiffnessControlThread.joinable()) { m_stiffnessControlThread.join(); } OutputDebugString(_T("[INFO] 控制线程已停止")); }*/ ResetRobot(); SaveRobotState(); // 通知Python重置完成 std::ofstream doneFile("control_done_signal.txt"); doneFile << "1"; doneFile.close(); //// 更新UI显示 //GetDlgItem(IDC_ADMITTANCE_CONTROL)->SetWindowText(_T("启动变刚度控制")); //OutputDebugString(_T("[INFO] 机器人复位流程完成")); } Sleep(100); // 100ms检查一次 } }); } void CappDlg::SaveRobotStateAsync(const double* torque, const double* pose) { // 复制数据到局部变量 double localTorque[3], localPose[3]; memcpy(localTorque, torque, sizeof(localTorque)); memcpy(localPose, pose, sizeof(localPose)); // 异步保存 std::thread([=]() { std::lock_guard<std::mutex> lock(m_fileMutex); // 先写入临时文件 CString tempFile = _T("robot_state.tmp"); std::ofstream outfile(tempFile); if (outfile.is_open()) { outfile << localTorque[0] << "," << localTorque[1] << "," << localTorque[2] << "," << localPose[0] << "," << localPose[1] << "," << localPose[2]; outfile.close(); // 原子性替换文件 if (!::MoveFileEx(tempFile, _T("robot_state.csv"), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { OutputDebugString(_T("[ERROR] 无法更新状态文件")); } // 通知Python状态已就绪 std::ofstream readyFile("state_ready_signal.txt"); readyFile << "1"; readyFile.close(); } }).detach(); } void CappDlg::SaveRobotState() { // 使用互斥锁保护共享数据 std::lock_guard<std::mutex> lock(m_mutex); // 如果通信端口忙,则跳过本次保存 if (m_bCommInUse) { OutputDebugString(_T("[INFO] 延迟保存状态:通信端口正忙")); return; } // 获取当前状态 double torque[3], pose[3]; GetTorqueData(torque); memcpy(pose, current_orientation, sizeof(pose)); // 异步保存 SaveRobotStateAsync(torque, pose); } void CappDlg::StartStiffnessControl() { if (!m_bStiffnessControlActive) { m_bStiffnessControlActive = true; m_stiffnessControlThread = std::thread(&CappDlg::StiffnessControlThread, this); // 更新按钮文本 GetDlgItem(IDC_ADMITTANCE_CONTROL)->SetWindowText(_T("停止变刚度控制")); } } void CappDlg::StopStiffnessControl() { if (m_bStiffnessControlActive) { m_bStiffnessControlActive = false; if (m_stiffnessControlThread.joinable()) { m_stiffnessControlThread.join(); } // 更新按钮文本 GetDlgItem(IDC_ADMITTANCE_CONTROL)->SetWindowText(_T("启动变刚度控制")); } } void CappDlg::StiffnessControlThread() { const double dt = 0.005; // 控制周期5ms double de[3] = { 0 }; double dde[3] = { 0 }; double last_orientation[3] = { 0 }; // 线程启动时打开连接 short nCid = SafeOpenComm(); if (nCid < 0) { OutputDebugString(_T("[ERROR] 控制线程启动失败:无法连接机器人")); return; } while (m_bStiffnessControlActive) { // 增加连接状态检查 if (m_nRobotCid < 0) { SafeCloseComm(); m_nRobotCid = SafeOpenComm(); if (m_nRobotCid < 0) { Sleep(1000); continue; } } // 检查连接有效性 if (nCid < 0) { nCid = SafeOpenComm(); if (nCid < 0) { Sleep(static_cast<DWORD>(dt * 1000)); continue; } } // 带重试的姿态获取 double dPos[12] = { 0 }; WORD rconf, toolno; bool bSuccess = false; for (int i = 0; i < 3 && !bSuccess; i++) { if (BscIsRobotPos(nCid, "BASE", 0, &rconf, &toolno, dPos) == 0) { bSuccess = true; // 更新当前姿态 current_orientation[0] = dPos[3]; current_orientation[1] = dPos[4]; current_orientation[2] = dPos[5]; // 获取力矩数据 GetTorqueData(dPos_force); // 计算调整量 bool orientation_changed = ( fabs(current_orientation[0] - last_orientation[0]) > 0.1 || fabs(current_orientation[1] - last_orientation[1]) > 0.1 || fabs(current_orientation[2] - last_orientation[2]) > 0.1); if (m_bParamsUpdated || orientation_changed) { double adjust[3]; for (int i = 0; i < 3; i++) { adjust[i] = OrientationControl(i); adjust[i] = clamp(adjust[i], -0.5, 0.5); dPos[3 + i] += adjust[i]; } // 发送运动指令 BscMovj(nCid, 0.3, "BASE", 0, 0, dPos); m_bParamsUpdated = false; memcpy(last_orientation, current_orientation, sizeof(last_orientation)); // 异步保存状态 SaveRobotStateAsync(dPos_force + 3, current_orientation); } } else if (i == 2) { // 最后一次尝试失败 OutputDebugString(_T("[ERROR] 连续获取姿态失败")); SafeCloseComm(); nCid = -1; } } Sleep(static_cast<DWORD>(dt * 1000)); } // 线程结束时关闭连接 SafeCloseComm(); } double CappDlg::OrientationControl(int axis) { // 1. 获取当前力矩 double tau = dPos_force[3 + axis]; // tx,ty,tz // 2. 计算姿态误差 double e = current_orientation[axis] - m_dTargetOrientation[axis]; // 3. 二阶系统计算 de[axis] += dt * dde[axis]; e += dt * de[axis]; dde[axis] = (tau - m_dDamping[axis] * de[axis] - m_dStiffness[axis] * e) / m_dInertia[axis]; return e; } void CappDlg::GetTorqueData(double* torque) { // 从传感器获取力矩数据 Sensor sensor; std::vector<float> data = sensor.getMeasurement(); for (int i = 0; i < 3; i++) { torque[i] = data[i+3] / 1000000.0; //数据需要转换 } } void CappDlg::OnDestroy() { // 停止所有线程 m_bRunning = false; m_bStiffnessControlActive = false; m_bFileWatcherRunning = false; // 等待线程结束 if (m_stiffnessControlThread.joinable()) { m_stiffnessControlThread.join(); } if (m_fileWatcherThread.joinable()) { m_fileWatcherThread.join(); } // 清理信号文件 DeleteFile(_T("control_done_signal.txt")); DeleteFile(_T("state_ready_signal.txt")); DeleteFile(_T("reset_signal.txt")); CDialogEx::OnDestroy(); } void CappDlg::OnBnClickedBtnReset() { // TODO: 在此添加控件通知处理程序代码 double dPos[12] = { 896, 13, -259, 175, 5, 0 }; // 重置位置 short nCid = TestOpenComm(0, 0); if (nCid >= 0) { BscMovj(nCid, 0.1, "BASE", 0, 0, dPos); TestCloseComm(nCid); } } //void CappDlg::ResetRobot() //{ // double dPos[12] = { 896, 13, -259, 175, 5, 0 }; // 重置位置 // short nCid = TestOpenComm(0, 0); // if (nCid >= 0) { // BscMovj(nCid, 0.1, "BASE", 0, 0, dPos); // TestCloseComm(nCid); // } //} void CappDlg::ResetRobot() { // 设置复位状态 m_bIsResetting = true; m_bResetCompleted = false; OutputDebugString(_T("[INFO] 开始机器人复位流程")); // 先停止所有使用通信端口的线程 StopStiffnessControl(); // 确保通信端口关闭 SafeCloseComm(); // 定义安全的初始位置(根据实际需求调整) double dPos[12] = { 896, 13, -259, 180, 0, 0 }; // 位置和姿态值 // 使用C++11的随机数生成器,比rand()更安全 std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> dis_rx(175.0, 179.0); std::uniform_real_distribution<> dis_ry(1.0, 5.0); dPos[3] = dis_rx(gen); // rx dPos[4] = dis_ry(gen); // ry dPos[5] = 0; // rz (固定) // 记录随机生成的位置 CString strRandomPos; strRandomPos.Format(_T("[INFO] 随机生成的复位位置: [%.2f, %.2f, %.2f, %.2f, %.2f, %.2f]"), dPos[0], dPos[1], dPos[2], dPos[3], dPos[4], dPos[5]); OutputDebugString(strRandomPos); // 打开通信连接 short nCid = TestOpenComm(0, 0); if (nCid >= 0) { // 以较低速度移动到初始位置,确保安全 short result = BscMovj(nCid, 0.1, "BASE", 0, 0, dPos); if (result == 0) { OutputDebugString(_T("[INFO] 复位命令已发送,等待机器人移动到初始位置")); // 等待机器人完成移动(根据实际机器人速度调整等待时间) Sleep(15000); // 等待15秒 // 验证复位后的位置 double currentPos[12] = { 0 }; WORD rconf, toolno; if (BscIsRobotPos(nCid, "BASE", 0, &rconf, &toolno, currentPos) == 0) { CString strMsg; strMsg.Format(_T("[INFO] 机器人已复位到位置: [%.2f, %.2f, %.2f, %.2f, %.2f, %.2f]"), currentPos[0], currentPos[1], currentPos[2], currentPos[3], currentPos[4], currentPos[5]); OutputDebugString(strMsg); // 检查复位是否成功(角度误差是否在容差范围内) double reset_errors[3] = { CalculateAngleError(currentPos[3], m_dTargetOrientation[0]), CalculateAngleError(currentPos[4], m_dTargetOrientation[1]), CalculateAngleError(currentPos[5], m_dTargetOrientation[2]) }; bool reset_successful = true; for (int i = 0; i < 3; i++) { if (reset_errors[i] > 5.0) { // 复位后允许的最大误差(度) reset_successful = false; break; } } if (reset_successful) { OutputDebugString(_T("[INFO] 机器人复位成功")); m_bResetCompleted = true; } else { OutputDebugString(_T("[WARN] 机器人复位后角度误差仍较大")); m_bResetCompleted = false; } } else { OutputDebugString(_T("[WARN] 复位后无法获取当前位置")); m_bResetCompleted = false; } } else { OutputDebugString(_T("[ERROR] 复位命令发送失败")); m_bResetCompleted = false; } // 关闭通信连接 SafeCloseComm(); // 复位完成后立即关闭 } else { OutputDebugString(_T("[ERROR] 无法打开通信连接进行复位")); m_bResetCompleted = false; } // 无论复位是否成功,都完成复位流程 m_bIsResetting = false; if (m_bStiffnessControlActive) { StartStiffnessControl(); } } // 安全打开连接(确保全局唯一) //short CappDlg::SafeOpenComm() //{ // // 如果已有有效连接,直接返回 // if (m_nRobotCid >= 0) { // return m_nRobotCid; // } // // // 设置连接使用标志 // if (m_bCommInUse.exchange(true)) { // OutputDebugString(_T("[WARN] 通信端口正忙,等待...")); // return -1; // } // // // 带重试的连接逻辑 // short nCid = -1; // for (int i = 0; i < MAX_RETRY; i++) { // nCid = TestOpenComm(0, 0); // if (nCid >= 0) { // m_nRobotCid = nCid; // OutputDebugString(_T("[INFO] 机器人连接成功")); // break; // } // OutputDebugString(_T("[WARN] 连接尝试失败,重试...")); // Sleep(RETRY_DELAY_MS); // } // // m_bCommInUse = false; // // if (nCid < 0) { // OutputDebugString(_T("[ERROR] 连接失败:达到最大重试次数")); // } // return nCid; //} short CappDlg::SafeOpenComm() { std::lock_guard<std::mutex> lock(m_commMutex); // 硬件初始化冷却期(复位后至少等待10秒) static std::chrono::time_point<std::chrono::steady_clock> lastResetTime; auto now = std::chrono::steady_clock::now(); if (now - lastResetTime < std::chrono::seconds(10)) { OutputDebugString(_T("[INFO] 处于复位冷却期,暂不连接")); return -1; } // 指数退避重试(最大等待5秒) int retryDelay = 500; // 初始500ms for (int i = 0; i < 15; i++) { // 增加重试次数 m_nRobotCid = TestOpenComm(0, 0); if (m_nRobotCid >= 0) { OutputDebugString(_T("[INFO] 连接成功")); return m_nRobotCid; } Sleep(retryDelay); retryDelay = min(retryDelay * 2, 5000); // 上限5秒 } return -1; } void CappDlg::SafeCloseComm() { std::lock_guard<std::mutex> lock(m_commMutex); if (m_nRobotCid >= 0) { TestCloseComm(m_nRobotCid); m_nRobotCid = -1; OutputDebugString(_T("[INFO] 机器人连接已关闭")); } } double CappDlg::CalculateAngleError(double current, double target) { double error = current - target; // 将误差标准化到[-180°, 180°] while (error > 180.0) { error -= 360.0; } while (error < -180.0) { error += 360.0; } return fabs(error); }以上是我的MFC程序 import numpy as np import pandas as pd import gymnasium as gym from gymnasium import spaces import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.distributions import Normal from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import time import skfuzzy as fuzz from skfuzzy import control as ctrl import os import logging import matplotlib.pyplot as plt from collections import deque import logging from logging.handlers import RotatingFileHandler import datetime import os # 创建日志目录 log_dir = "training_logs" os.makedirs(log_dir, exist_ok=True) # 带时间戳的日志文件名 timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") log_filename = os.path.join(log_dir, f'stiffness_control_{timestamp}.log') # 基本配置 - 控制台输出 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[logging.StreamHandler()] ) # 添加文件日志 - 带轮转功能 file_handler = RotatingFileHandler( log_filename, maxBytes=10*1024*1024, # 10MB backupCount=5, encoding='utf-8' ) file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')) logging.getLogger().addHandler(file_handler) # 设置更详细的文件日志级别 file_handler.setLevel(logging.DEBUG) # 日志记录 logging.info("日志系统初始化完成,日志将保存到: %s", log_filename) # 配置日志 #logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s') # 文件监控类 class StiffnessWatcher(FileSystemEventHandler): def __init__(self, env): super().__init__() self.env = env self.updated = False def on_modified(self, event): if event.is_directory: return if event.src_path.endswith("stiffness_state.csv"): self.updated = True logging.debug("检测到状态文件更新") # 机器人刚度控制环境 class StiffnessControlEnv(gym.Env): def __init__(self): super(StiffnessControlEnv, self).__init__() self.target_dir = r"F:\lry\weizi\app" os.makedirs(self.target_dir, exist_ok=True) # 信号文件路径 self.control_done_signal = os.path.join(self.target_dir, "control_done_signal.txt") self.state_ready_signal = os.path.join(self.target_dir, "state_ready_signal.txt") self.reset_signal = os.path.join(self.target_dir, "reset_signal.txt") self.initial_params_file = os.path.join(self.target_dir, "initial_stiffness_params.txt") self.new_params_file = os.path.join(self.target_dir, "new_stiffness_params.txt") self.state_file = os.path.join(self.target_dir, "robot_state.csv") # 清除旧信号文件 self.cleanup_previous_files() self.state_log_file = os.path.join(self.target_dir, "arm_state_log.csv") self._init_state_log() # 初始化状态日志 # 目标姿态: rx=180°, ry=0°, rz=0° self.target_orientation = np.array([180.0, 0.0, 0.0], dtype=np.float32) self.max_angle_error = 20.0 # 最大允许角度误差(度) # 动作空间: 三个轴的刚度参数[K_rx, K_ry, K_rz] self.action_space = spaces.Box( low=np.array([50, 50, 50], dtype=np.float32), high=np.array([500, 500, 500], dtype=np.float32), dtype=np.float32 ) # 状态空间: 力矩(tx, ty, tz) + 姿态(rx, ry, rz) self.observation_space = spaces.Box( low=np.array([-2.0, -2.0, -2.0, -180.0, -30.0, -10.0], dtype=np.float32), high=np.array([2.0, 2.0, 2.0, 180.0, 30.0, 10.0], dtype=np.float32), dtype=np.float32 ) self.state = np.zeros(6, dtype=np.float32) self.current_step = 0 self.max_steps = 200 self.last_error = np.inf self.last_torque = np.zeros(3, dtype=np.float32) # 创建模糊奖励系统 self.fuzzy_reward_system = self.create_fuzzy_system() # 文件监控 self.watcher = StiffnessWatcher(self) self.observer = Observer() self.observer.schedule(self.watcher, path=self.target_dir, recursive=True) self.observer.start() logging.info("环境初始化完成,开始监控文件夹") def _init_state_log(self): """初始化机械臂状态日志文件""" with open(self.state_log_file, 'w') as f: f.write("timestamp,step,tx,ty,tz,rx,ry,rz,target_rx,target_ry,target_rz\n") def _log_arm_state(self, step, state, action=None): """ 记录机械臂状态到日志文件和终端 :param step: 当前步数 :param state: 状态数组 [tx,ty,tz,rx,ry,rz] :param action: 当前动作 [K_rx, K_ry, K_rz] (可选) """ timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") tx, ty, tz, rx, ry, rz = state rx_display = self.to_180_degrees(rx) # 写入CSV日志 with open(self.state_log_file, 'a') as f: f.write(f"{timestamp},{step},{tx:.4f},{ty:.4f},{tz:.4f}," f"{rx:.2f},{ry:.2f},{rz:.2f}\n") # f"{self.target_orientation[0]}," # f"{self.target_orientation[1]}," # f"{self.target_orientation[2]}\n") # 实时控制台输出 status_msg = (f"机械臂状态 [Step {step}]:\n" f" - 力矩(tx,ty,tz): {tx:.3f}, {ty:.3f}, {tz:.3f} N·m\n" f" - 姿态(rx,ry,rz): {rx_display:.2f}, {ry:.2f}, {rz:.2f} °\n") # f" - 目标姿态: {self.target_orientation[0]:.2f}, " # f"{self.target_orientation[1]:.2f}, {self.target_orientation[2]:.2f} °") if action is not None: status_msg += f"\n - 当前刚度参数: {action[0]:.1f}, {action[1]:.1f}, {action[2]:.1f} N·m/rad" logging.info(status_msg) print(f"\n{'-'*40}\n{status_msg}\n{'-'*40}") # 控制台分隔线显示 def to_360_degrees(self, angle): """将-180°~180°的角度转换为0°~360°""" angle = float(angle) if angle < -180 or angle > 180: logging.warning(f"输入角度超出范围: {angle}°,将被标准化到-180°~180°") angle = (angle + 180) % 360 - 180 return (angle + 360) % 360 def to_180_degrees(self, angle): """将0°~360°的角度转换回-180°~180°(用于输出)""" angle = float(angle) if angle < 0 or angle > 360: logging.warning(f"输入角度超出范围: {angle}°,将被标准化到0°~360°") angle = angle % 360 return (angle + 180) % 360 - 180 def calculate_angle_error(self, current, target): """计算两个角度之间的最短误差,考虑周期性(-180°和180°是同一点)""" error = current - target # 将误差标准化到[-180°, 180°] error = (error + 180) % 360 - 180 return abs(error) def cleanup_previous_files(self): """清除之前的信号文件""" for file in [self.control_done_signal, self.state_ready_signal, self.reset_signal, self.initial_params_file, self.new_params_file]: if os.path.exists(file): try: os.remove(file) except Exception as e: logging.warning(f"无法删除旧文件 {file}: {e}") def create_fuzzy_system(self): # 定义模糊变量 torque_range = np.arange(0, 2.1, 0.1) orientation_error_range = np.arange(0, 30.1, 0.1) reward_range = np.arange(0, 2.1, 0.1) # 输入变量 torque = ctrl.Antecedent(torque_range, 'torque') error = ctrl.Antecedent(orientation_error_range, 'error') # 输出变量 reward = ctrl.Consequent(reward_range, 'reward') # 定义隶属函数 torque['VS'] = fuzz.trimf(torque_range, [0, 0, 0.5]) torque['S'] = fuzz.trimf(torque_range, [0, 0.5, 1.0]) torque['M'] = fuzz.trimf(torque_range, [0.5, 1.0, 1.5]) torque['L'] = fuzz.trimf(torque_range, [1.0, 1.5, 2.0]) torque['VL'] = fuzz.trapmf(torque_range, [1.5, 2.0, 2.0, 2.0]) error['VS'] = fuzz.trimf(orientation_error_range, [0, 0, 3]) error['S'] = fuzz.trimf(orientation_error_range, [0, 3, 6]) error['M'] = fuzz.trimf(orientation_error_range, [3, 6, 10]) error['L'] = fuzz.trimf(orientation_error_range, [6, 10, 20]) error['VL'] = fuzz.trapmf(orientation_error_range, [10, 20, 30, 30]) reward['VL'] = fuzz.trimf(reward_range, [0, 0, 0.5]) reward['L'] = fuzz.trimf(reward_range, [0, 0.5, 1.0]) reward['M'] = fuzz.trimf(reward_range, [0.5, 1.0, 1.5]) reward['H'] = fuzz.trimf(reward_range, [1.0, 1.5, 2.0]) reward['VH'] = fuzz.trapmf(reward_range, [1.5, 2.0, 2.0, 2.0]) # 定义模糊规则 rules = [ ctrl.Rule(torque['VS'] & error['VS'], reward['VH']), ctrl.Rule(torque['S'] & error['VS'], reward['H']), ctrl.Rule(torque['M'] & error['VS'], reward['M']), ctrl.Rule(torque['L'] & error['VS'], reward['L']), ctrl.Rule(torque['VL'] & error['VS'], reward['VL']), ctrl.Rule(torque['VS'] & error['S'], reward['H']), ctrl.Rule(torque['S'] & error['S'], reward['H']), ctrl.Rule(torque['M'] & error['S'], reward['M']), ctrl.Rule(torque['L'] & error['S'], reward['L']), ctrl.Rule(torque['VL'] & error['S'], reward['VL']), ctrl.Rule(torque['VS'] & error['M'], reward['M']), ctrl.Rule(torque['S'] & error['M'], reward['M']), ctrl.Rule(torque['M'] & error['M'], reward['L']), ctrl.Rule(torque['L'] & error['M'], reward['L']), ctrl.Rule(torque['VL'] & error['M'], reward['VL']), ctrl.Rule(torque['VS'] & error['L'], reward['L']), ctrl.Rule(torque['S'] & error['L'], reward['L']), ctrl.Rule(torque['M'] & error['L'], reward['VL']), ctrl.Rule(torque['L'] & error['L'], reward['VL']), ctrl.Rule(torque['VL'] & error['L'], reward['VL']), ctrl.Rule(torque['VS'] & error['VL'], reward['VL']), ctrl.Rule(torque['S'] & error['VL'], reward['VL']), ctrl.Rule(torque['M'] & error['VL'], reward['VL']), ctrl.Rule(torque['L'] & error['VL'], reward['VL']), ctrl.Rule(torque['VL'] & error['VL'], reward['VL']), ] control_system = ctrl.ControlSystem(rules) return ctrl.ControlSystemSimulation(control_system) def reset(self): """重置环境并与MFC同步""" initial_params_path = os.path.join(self.target_dir, "initial_stiffness_params.txt") if not os.path.exists(initial_params_path): default_params = "300.0, 300.0, 300.0" # 默认刚度值 with open(initial_params_path, 'w') as f: f.write(default_params) logging.info(f"已自动生成初始参数文件: {default_params}") # 1. 发送重置信号 self.safe_write_file(self.reset_signal, "1") logging.info("已发送重置信号,等待MFC响应...") # 2. 等待MFC确认重置完成 if not self.wait_for_signal(self.control_done_signal, timeout=150.0): logging.error("MFC重置响应超时") raise TimeoutError("MFC reset timeout") # 3. 检查初始参数文件 if not os.path.exists(self.initial_params_file): logging.error("初始刚度参数文件不存在,请先生成初始参数") raise FileNotFoundError("initial_stiffness_params.txt not found") # 4. 读取初始参数(示例值,实际应从文件读取) with open(self.initial_params_file, 'r') as f: params = f.read().strip() logging.info(f"已加载初始刚度参数: {params}") #os.remove(self.initial_params_file) # 5. 读取初始状态 state = self.read_state(self.state_file) logging.info(f"初始状态: {state}") self._log_arm_state(0, state) # 初始状态记为step 0 return state, {} def safe_write_file(self, path, content): """安全写入文件,带有重试机制""" max_retries = 3 for attempt in range(max_retries): try: temp_path = path + ".tmp" with open(temp_path, "w") as f: f.write(content) if os.name == 'nt': if os.path.exists(path): os.remove(path) os.rename(temp_path, path) else: os.replace(temp_path, path) return True except Exception as e: logging.warning(f"写入文件失败 (尝试 {attempt+1}/{max_retries}): {e}") time.sleep(0.1) logging.error(f"写入文件失败: {path}") return False def read_state(self, state_path): """安全读取状态文件""" max_retries = 3 for attempt in range(max_retries): try: if not os.path.exists(state_path): raise FileNotFoundError(f"状态文件不存在: {state_path}") with open(state_path, 'r') as f: content = f.read().strip() if not content: raise ValueError("状态文件为空") data = [float(x) for x in content.split(',')] data[3] = self.to_360_degrees(data[3]) # 将-180°~180°转换为0°~360° if len(data) != 6: raise ValueError(f"无效数据长度: {len(data)}") return np.array(data, dtype=np.float32) except Exception as e: if attempt == max_retries - 1: logging.error(f"读取状态文件失败: {e}") return np.zeros(6, dtype=np.float32) time.sleep(0.5) def step(self, action): """执行一步动作""" # 1. 发送刚度参数 params_str = f"{action[0]:.2f},{action[1]:.2f},{action[2]:.2f}" self.safe_write_file(self.new_params_file, params_str) logging.info(f"已发送刚度参数: {params_str}") # 2. 等待MFC确认参数接收 if not self.wait_for_signal(self.control_done_signal, timeout=55.0): logging.warning("MFC参数接收确认超时") return self.state, -10, True, False, {} # 3. 等待状态更新 if not self.wait_for_signal(self.state_ready_signal, timeout=15.0): logging.warning("状态更新超时") return self.state, -10, True, False, {} # 4. 读取新状态 new_state = self.read_state(self.state_file) # 5. 计算角度误差(考虑rx的特殊性) rx, ry, rz = new_state[3:6] rx_error = self.calculate_angle_error(rx, self.target_orientation[0]) ry_error = self.calculate_angle_error(ry, self.target_orientation[1]) rz_error = self.calculate_angle_error(rz, self.target_orientation[2]) angle_errors = np.array([rx_error, ry_error, rz_error]) # 6. 检查角度误差是否超限 error_exceeded = np.any(angle_errors > self.max_angle_error) # 7. 计算奖励 reward = self.calculate_reward(new_state) # 8. 确定完成标志(结合原有逻辑和角度误差) done = error_exceeded or np.all(angle_errors < 0.5) or (self.current_step >= self.max_steps) # 9. 如果误差超限,执行复位 if error_exceeded: logging.warning(f"角度误差超限: {angle_errors} > {self.max_angle_error},触发复位") self._reset_robot() reward -= 100 # 惩罚误差超限 # 10. 更新状态 self.state = new_state self.current_step += 1 self._log_arm_state(self.current_step, new_state, action) # 11. 返回结果 return new_state, reward, done, False, { "error": angle_errors, "torque": new_state[:3], "orientation": new_state[3:6] } def _reset_robot(self): """执行机器人复位流程""" # 发送重置信号 self.safe_write_file("reset_signal.txt", "1") # 等待MFC响应 if not self.wait_for_signal("control_done_signal.txt", timeout=150): logging.error("等待MFC重置超时") # 重置内部计数器 self.current_step = 0 def wait_for_signal(self, signal_path, timeout=10.0): """等待信号文件出现并删除它""" start_time = time.time() while time.time() - start_time < timeout: if os.path.exists(signal_path): try: os.remove(signal_path) return True except Exception as e: logging.warning(f"删除信号文件失败: {e}") time.sleep(0.1) time.sleep(0.2) # 避免CPU占用过高 return False def wait_for_update(self): """仅通过修改时间(mtime)检测文件更新,并打印文件内容到日志""" timeout = 10.0 # 超时时间10秒 start_time = time.time() state_path = os.path.join(self.target_dir, "stiffness_state.csv") # 记录初始修改时间,处理文件不存在的情况 initial_mtime = 0 if os.path.exists(state_path): initial_mtime = os.path.getmtime(state_path) logging.debug(f"初始文件修改时间: {initial_mtime}") while time.time() - start_time < timeout: if os.path.exists(state_path): current_mtime = os.path.getmtime(state_path) # 检查修改时间是否变化(添加微小阈值避免浮点数误差) if current_mtime > initial_mtime + 1e-6: # 读取文件内容并打印到日志 try: with open(state_path, 'r') as f: content = f.read().strip() logging.info(f"状态文件已更新,内容: {content}") # 关键新增:打印文件内容 except Exception as e: logging.warning(f"读取更新后的文件内容失败: {e}") logging.debug(f"文件修改时间更新: 旧={initial_mtime} → 新={current_mtime}") time.sleep(0.1) # 等待文件系统刷新 return True time.sleep(0.2) # 轮询间隔200ms logging.warning(f"等待状态更新超时(超时时间:{timeout}秒)") return False # def wait_for_update(self): # """仅通过修改时间(mtime)检测文件更新,提高检测灵敏度""" # timeout = 10.0 # 延长超时时间至10秒,给机械臂更多响应时间 # start_time = time.time() # state_path = os.path.join(self.target_dir, "stiffness_state.csv") # # 记录初始修改时间,处理文件不存在的情况 # initial_mtime = 0 # if os.path.exists(state_path): # initial_mtime = os.path.getmtime(state_path) # logging.debug(f"初始文件修改时间: {initial_mtime}") # while time.time() - start_time < timeout: # if os.path.exists(state_path): # current_mtime = os.path.getmtime(state_path) # # 关键修改:仅检查修改时间是否变化,且设置一个小的阈值避免浮点数误差 # if current_mtime > initial_mtime + 1e-6: # 添加微小阈值,避免精度误差导致的误判 # logging.debug(f"文件已更新,新修改时间: {current_mtime}") # time.sleep(0.1) # 等待文件系统完全刷新 # return True # time.sleep(0.2) # 轮询间隔调整为200ms,平衡性能和响应速度 # logging.warning(f"等待状态更新超时(超时时间:{timeout}秒)") # return False def calculate_reward(self, state): """计算奖励,综合考虑力矩、姿态误差和误差变化""" torque = state[0:3] orientation = state[3:6] # 计算当前误差(考虑rx的周期性) rx_error = self.calculate_angle_error(orientation[0], self.target_orientation[0]) error = np.array([ rx_error, abs(orientation[1] - self.target_orientation[1]), abs(orientation[2] - self.target_orientation[2]) ]) current_error = np.linalg.norm(error) # 模糊奖励 self.fuzzy_reward_system.input['torque'] = np.mean(np.abs(torque)) self.fuzzy_reward_system.input['error'] = current_error self.fuzzy_reward_system.compute() base_reward = self.fuzzy_reward_system.output['reward'] # 初始化改进奖励 improvement_reward = 0.0 # 只有在不是第一次计算时才计算改进奖励 if hasattr(self, 'last_error') and not np.isinf(self.last_error): error_diff = self.last_error - current_error if error_diff > 0: # 误差减小 improvement_reward = 2.0 * error_diff else: # 误差增大 improvement_reward = 0.5 * error_diff # 注意这里已经是负值 # 更新last_error和last_torque self.last_error = current_error self.last_torque = torque.copy() # 其他奖励组件保持不变... goal_reward = 5.0 if np.all(error < 5.0) else 0.0 error_penalty = -0.2 * current_error if current_error > 15 else 0 step_penalty = -0.01 stability_reward = 0.2 if np.linalg.norm(torque - self.last_torque) < 0.1 else 0 # 总奖励 total_reward = base_reward + improvement_reward + goal_reward + error_penalty + step_penalty + stability_reward logging.info(f"奖励组成: 基础={base_reward:.4f}, 改进={improvement_reward:.4f}, " f"目标={goal_reward:.4f}, 误差惩罚={error_penalty:.4f}, " f"步数={step_penalty:.4f}, 稳定={stability_reward:.4f}") return total_reward def close(self): self.observer.stop() self.observer.join() logging.info("环境已关闭") # 策略网络 class PolicyNetwork(nn.Module): def __init__(self, state_dim, action_dim, hidden_dim=128): super(PolicyNetwork, self).__init__() self.fc1 = nn.Linear(state_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, hidden_dim) # 均值和标准差层 self.mean_layer = nn.Linear(hidden_dim, action_dim) self.log_std_layer = nn.Linear(hidden_dim, action_dim) # 初始化权重 self.apply(self._init_weights) def _init_weights(self, module): if isinstance(module, nn.Linear): nn.init.kaiming_normal_(module.weight, a=0.01) if module.bias is not None: module.bias.data.zero_() def forward(self, x): x = F.leaky_relu(self.fc1(x), 0.01) x = F.leaky_relu(self.fc2(x), 0.01) # 计算均值和标准差 mean = self.mean_layer(x) log_std = self.log_std_layer(x) # 限制标准差范围,避免探索性过大或过小 log_std = torch.clamp(log_std, -20, 2) std = log_std.exp() return mean, std def get_action(self, state): state = torch.FloatTensor(state).unsqueeze(0) mean, std = self.forward(state) # 创建正态分布 dist = Normal(mean, std) action = dist.sample() # 确保动作在有效范围内 action = torch.clamp(action, torch.FloatTensor([50, 50, 50]), torch.FloatTensor([500, 500, 500])) # 计算对数概率 log_prob = dist.log_prob(action).sum(-1) return action.detach().numpy()[0], log_prob.detach().numpy()[0] def evaluate(self, state, action): mean, std = self.forward(state) dist = Normal(mean, std) # 计算对数概率和熵 action_logprobs = dist.log_prob(action).sum(-1) dist_entropy = dist.entropy().sum(-1) return action_logprobs, dist_entropy # 价值网络 class ValueNetwork(nn.Module): def __init__(self, state_dim, hidden_dim=128): super(ValueNetwork, self).__init__() self.fc1 = nn.Linear(state_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, hidden_dim) self.value_layer = nn.Linear(hidden_dim, 1) # 初始化权重 self.apply(self._init_weights) def _init_weights(self, module): if isinstance(module, nn.Linear): nn.init.kaiming_normal_(module.weight, a=0.01) if module.bias is not None: module.bias.data.zero_() def forward(self, x): x = F.leaky_relu(self.fc1(x), 0.01) x = F.leaky_relu(self.fc2(x), 0.01) value = self.value_layer(x) return value # PPO代理 class PPO: def __init__(self, state_dim, action_dim, lr=3e-4, gamma=0.99, eps_clip=0.2, value_coef=0.5, entropy_coef=0.01, hidden_dim=128): self.gamma = gamma self.eps_clip = eps_clip self.value_coef = value_coef self.entropy_coef = entropy_coef # 策略网络和价值网络 self.policy = PolicyNetwork(state_dim, action_dim, hidden_dim) self.value = ValueNetwork(state_dim, hidden_dim) # 优化器 self.policy_optimizer = optim.Adam(self.policy.parameters(), lr=lr) self.value_optimizer = optim.Adam(self.value.parameters(), lr=lr) # 存储轨迹 self.states = [] self.actions = [] self.logprobs = [] self.rewards = [] self.is_terminals = [] def select_action(self, state): action, log_prob = self.policy.get_action(state) return action, log_prob def store_transition(self, state, action, log_prob, reward, done): self.states.append(state) self.actions.append(action) self.logprobs.append(log_prob) self.rewards.append(reward) self.is_terminals.append(done) def update(self, epochs=10): # 转换为张量 states = torch.FloatTensor(self.states) actions = torch.FloatTensor(self.actions) old_logprobs = torch.FloatTensor(self.logprobs) # 计算回报 returns = [] discounted_return = 0 for reward, is_terminal in zip(reversed(self.rewards), reversed(self.is_terminals)): if is_terminal: discounted_return = 0 discounted_return = reward + (self.gamma * discounted_return) returns.insert(0, discounted_return) returns = torch.FloatTensor(returns) # 标准化回报 returns = (returns - returns.mean()) / (returns.std() + 1e-8) # 优化策略和价值网络 for _ in range(epochs): # 获取当前策略的对数概率和熵 logprobs, entropy = self.policy.evaluate(states, actions) # 计算策略比率 ratio = torch.exp(logprobs - old_logprobs.detach()) # 计算优势函数 values = self.value(states).squeeze() advantage = returns - values.detach() # 标准化优势 advantage = (advantage - advantage.mean()) / (advantage.std() + 1e-8) # 计算策略损失 surr1 = ratio * advantage surr2 = torch.clamp(ratio, 1-self.eps_clip, 1+self.eps_clip) * advantage policy_loss = -torch.min(surr1, surr2).mean() # 计算价值损失 value_loss = F.mse_loss(values, returns) # 计算总损失 loss = policy_loss + self.value_coef * value_loss - self.entropy_coef * entropy.mean() # 更新策略网络 self.policy_optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(self.policy.parameters(), 0.5) # 梯度裁剪 self.policy_optimizer.step() # 更新价值网络 self.value_optimizer.zero_grad() value_loss.backward() nn.utils.clip_grad_norm_(self.value.parameters(), 0.5) # 梯度裁剪 self.value_optimizer.step() # 清空轨迹 self.states.clear() self.actions.clear() self.logprobs.clear() self.rewards.clear() self.is_terminals.clear() # 训练函数 def train_ppo(env, total_episodes=1000, max_steps_per_episode=200, update_timestep=2000, save_interval=100, log_interval=10, render_interval=50): state_dim = env.observation_space.shape[0] action_dim = env.action_space.shape[0] # 创建PPO代理 agent = PPO(state_dim, action_dim, lr=3e-4, gamma=0.99, eps_clip=0.2, value_coef=0.5, entropy_coef=0.01, hidden_dim=128) # 记录训练过程 episode_rewards = [] avg_rewards = [] best_reward = -np.inf # 训练循环 global_timestep = 0 for episode in range(total_episodes): state, _ = env.reset() episode_reward = 0 for step in range(max_steps_per_episode): global_timestep += 1 # 选择动作 action, log_prob = agent.select_action(state) # 执行动作 next_state, reward, terminated, truncated, info = env.step(action) done = terminated or truncated # 存储转换 agent.store_transition(state, action, log_prob, reward, done) # 更新状态 state = next_state episode_reward += reward # 检查是否需要更新策略 if global_timestep % update_timestep == 0: agent.update() logging.info(f"更新策略: 全局步数={global_timestep}") # 检查是否完成 if done: break # 记录奖励 episode_rewards.append(episode_reward) avg_reward = np.mean(episode_rewards[-10:]) avg_rewards.append(avg_reward) # 保存最佳模型 if avg_reward > best_reward: best_reward = avg_reward torch.save(agent.policy.state_dict(), 'best_stiffness_policy.pth') logging.info(f"保存最佳模型: 平均奖励={avg_reward:.2f}") # 定期保存模型 if (episode + 1) % save_interval == 0: torch.save(agent.policy.state_dict(), f'stiffness_policy_episode_{episode+1}.pth') # 打印训练信息 if (episode + 1) % log_interval == 0: logging.info(f"Episode {episode+1}/{total_episodes} - " f"奖励: {episode_reward:.2f}, 平均奖励: {avg_reward:.2f}, " f"步数: {step+1}, 误差: {info['error'].round(2)}") # 绘制学习曲线 if (episode + 1) % 50 == 0: plt.figure(figsize=(10, 5)) plt.plot(episode_rewards, alpha=0.5, label='单轮奖励') plt.plot(avg_rewards, label='10轮平均奖励') plt.xlabel('轮次') plt.ylabel('奖励') plt.title('PPO训练进度') plt.legend() plt.grid(True) plt.savefig('training_curve.png') plt.close() # 保存最终模型 torch.save(agent.policy.state_dict(), 'final_stiffness_policy.pth') logging.info("训练完成,模型已保存") return agent, episode_rewards, avg_rewards # 测试训练好的策略 def test_policy(env, policy_path='best_stiffness_policy.pth', episodes=5): state_dim = env.observation_space.shape[0] action_dim = env.action_space.shape[0] # 加载策略网络 policy = PolicyNetwork(state_dim, action_dim) policy.load_state_dict(torch.load(policy_path)) policy.eval() for episode in range(episodes): state, _ = env.reset() done = False episode_reward = 0 steps = 0 logging.info(f"\n===== 测试第 {episode+1}/{episodes} 轮 =====") while not done: # 选择确定性动作(均值) with torch.no_grad(): state_tensor = torch.FloatTensor(state).unsqueeze(0) mean, _ = policy(state_tensor) action = mean.squeeze().numpy() # 执行动作 next_state, reward, terminated, truncated, info = env.step(action) done = terminated or truncated episode_reward += reward steps += 1 # 打印当前状态 logging.info(f"步骤 {steps}: 动作={action.round(2)}, 奖励={reward:.4f}, " f"误差={info['error'].round(2)}, 力矩={info['torque'].round(3)}") state = next_state logging.info(f"📊 第 {episode+1} 轮完成: 总奖励={episode_reward:.4f}, 总步数={steps}") # 主函数 if __name__ == "__main__": try: logging.info("===== 开始机器人刚度控制强化学习训练 =====") # 创建环境 env = StiffnessControlEnv() # 训练模型 agent, rewards, avg_rewards = train_ppo( env, total_episodes=500, max_steps_per_episode=200, update_timestep=2000, save_interval=50, log_interval=10 ) # 测试模型 test_policy(env) except KeyboardInterrupt: logging.info("训练被用户中断") finally: # 确保环境被正确关闭 if 'env' in locals() and env is not None: env.close() logging.info("程序已退出") 这是我的python程序 修改我的程序,我要求,先启动python程序但并不开始强化学习,直到MFC程序启动变刚度导纳控制后给python力矩和姿态信息,python收到后开始强化学习,把计算的刚度参数传递给MFC使机械臂开始调整姿态,当机械臂完成一次调整后把力矩和姿态信息再传给python计算新的刚度参数,当机械臂到达目标姿态时,MFC程序把力矩和姿态信息传给python后,证明一个回合结束,该开始下一回合,MFC程序使机械臂位置重置,重置完成后给python力矩和姿态信息开始新的回合,直至训练结束,要求尽量在我的程序基础上不修改太多,保证程序运行时尽量不出现线程阻塞或者无法连接机械臂的情况,修改保持原有程序的主要结构,只调整交互流程和控制逻辑。MFC程序负责主动控制机械臂和重置,Python程序专注于强化学习计算。
07-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值