diff --git a/.ci/unit_tests/Python_Engine_Test/Compute/Base.cs b/.ci/unit_tests/Python_Engine_Test/Compute/Base.cs new file mode 100644 index 00000000..3a165283 --- /dev/null +++ b/.ci/unit_tests/Python_Engine_Test/Compute/Base.cs @@ -0,0 +1,213 @@ +/* + * This file is part of the Buildings and Habitats object Model (BHoM) + * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. + * + * Each contributor holds copyright over their respective contributions. + * The project versioning (Git) records all such contribution source information. + * + * + * The BHoM is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3.0 of the License, or + * (at your option) any later version. + * + * The BHoM is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this code. If not, see . + */ + +using FluentAssertions; +using BH.oM.Python; +using BH.oM.Base.Debugging; +using System.Diagnostics; +using System.IO.Compression; +using EngineQuery = BH.Engine.Python.Query; + +namespace BH.Tests.Engine.Python.Compute +{ + public abstract class Base + { + protected string m_Root = null!; + protected PythonEnvironment m_Environment = null!; + private readonly Dictionary m_OriginalVariables = new(); + + [OneTimeSetUp] + public void EnsureManagedUV() + { + string? originalPath = Environment.GetEnvironmentVariable("PATH"); + try + { + BH.Engine.Base.Compute.ClearCurrentEvents(); + BH.Engine.Python.Compute.InstallUV(run: true); + File.Exists(EngineQuery.UVExecutable()).Should().BeTrue(); + AssertNoErrors(); + } + finally + { + Environment.SetEnvironmentVariable("PATH", originalPath); + BH.Engine.Base.Compute.ClearCurrentEvents(); + } + } + + [SetUp] + public void SetUp() + { + string name = "bhom_install_remove_" + Guid.NewGuid().ToString("N"); + m_Root = Path.Combine(EngineQuery.DirectoryEnvironments(), name); + Directory.CreateDirectory(m_Root); + m_Environment = new PythonEnvironment + { + Name = name, + Executable = Path.Combine(m_Root, ".venv", "Scripts", "python.exe") + }; + Run(EngineQuery.UVExecutable(), "venv", "--no-project", "--no-python-downloads", Path.Combine(m_Root, ".venv")); + SetVariable("JUPYTER_DATA_DIR", Path.Combine(m_Root, "jupyter")); + SetVariable("JUPYTER_PATH", Path.Combine(m_Root, "jupyter")); + SetVariable("UV_TOOL_DIR", Path.Combine(m_Root, "tools")); + SetVariable("UV_TOOL_BIN_DIR", Path.Combine(m_Root, "bin")); + SetVariable("UV_CACHE_DIR", Path.Combine(m_Root, "cache")); + string conflictingUV = Path.Combine(m_Root, "conflicting-uv"); + Directory.CreateDirectory(conflictingUV); + File.WriteAllText(Path.Combine(conflictingUV, "uv.cmd"), "@echo UV from PATH must not be used 1>&2\r\n@exit /b 99\r\n"); + SetVariable("PATH", conflictingUV + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH")); + BH.Engine.Base.Compute.ClearCurrentEvents(); + } + + [TearDown] + public void TearDown() + { + foreach (var variable in m_OriginalVariables) + Environment.SetEnvironmentVariable(variable.Key, variable.Value); + m_OriginalVariables.Clear(); + if (Directory.Exists(m_Root)) + Directory.Delete(m_Root, true); + BH.Engine.Base.Compute.ClearCurrentEvents(); + } + + protected void PreparePackageVersions() + { + CreateWheel("bhom_repeat_package", "1.0.0"); + CreateWheel("bhom_repeat_package", "2.0.0"); + SetVariable("UV_FIND_LINKS", Path.Combine(m_Root, "wheels")); + SetVariable("UV_OFFLINE", "true"); + } + + private void CreateWheel(string name, string version) + { + string wheels = Path.Combine(m_Root, "wheels"); + Directory.CreateDirectory(wheels); + using var archive = ZipFile.Open(Path.Combine(wheels, $"{name}-{version}-py3-none-any.whl"), ZipArchiveMode.Create); + string info = $"{name}-{version}.dist-info"; + var files = new Dictionary + { + [$"{name}.py"] = "def main():\n pass\n", + [$"{info}/METADATA"] = $"Metadata-Version: 2.1\nName: {name.Replace('_', '-')}\nVersion: {version}\n", + [$"{info}/WHEEL"] = "Wheel-Version: 1.0\nGenerator: BHoM-tests\nRoot-Is-Purelib: true\nTag: py3-none-any\n", + [$"{info}/entry_points.txt"] = $"[console_scripts]\n{name} = {name}:main\n" + }; + files[$"{info}/RECORD"] = string.Join("\n", files.Keys.Select(path => path + ",,")) + $"\n{info}/RECORD,,\n"; + foreach (var file in files) + { + using var writer = new StreamWriter(archive.CreateEntry(file.Key).Open()); + writer.Write(file.Value); + } + } + + protected string CreateLocalPackage(string folder) + { + string source = Path.Combine(m_Root, folder); + Directory.CreateDirectory(source); + File.WriteAllText(Path.Combine(source, "pyproject.toml"), + "[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n" + + "[project]\nname = \"bhom-local-package\"\nversion = \"1.0.0\"\n"); + File.WriteAllText(Path.Combine(source, "bhom_local_package.py"), "VALUE = 1\n"); + return source; + } + + protected void CreateProject() + { + File.WriteAllText(Path.Combine(m_Root, "pyproject.toml"), + "[project]\nname = \"bhom-test-project\"\nversion = \"1.0.0\"\nrequires-python = \">=3.10\"\ndependencies = []\n"); + } + + protected string PackageMetadata(string name, string version) + { + return Path.Combine(m_Root, ".venv", "Lib", "site-packages", $"{name}-{version}.dist-info", "METADATA"); + } + + protected void SetVariable(string name, string value) + { + if (!m_OriginalVariables.ContainsKey(name)) + m_OriginalVariables.Add(name, Environment.GetEnvironmentVariable(name)); + Environment.SetEnvironmentVariable(name, value); + } + + protected static void WithIsolatedDirectory(string directory, Action test) + { + string backup = directory + ".test-backup-" + Guid.NewGuid().ToString("N"); + bool existed = Directory.Exists(directory); + if (existed) + Directory.Move(directory, backup); + try + { + Directory.CreateDirectory(directory); + test(); + } + finally + { + try + { + if (Directory.Exists(directory)) + Directory.Delete(directory, true); + } + finally + { + if (existed) + Directory.Move(backup, directory); + } + } + } + + protected static void AssertNoErrors() + { + BH.Engine.Base.Query.CurrentEvents().Where(e => e.Type == EventType.Error).Select(e => e.Message).Should().BeEmpty(); + } + + protected static void AssertWarningWithoutErrors() + { + AssertNoErrors(); + BH.Engine.Base.Query.CurrentEvents().Should().Contain(e => e.Type == EventType.Warning); + } + + protected static string Run(string executable, params string[] arguments) + { + using var process = new Process + { + StartInfo = new ProcessStartInfo(executable) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + } + }; + foreach (string argument in arguments) + process.StartInfo.ArgumentList.Add(argument); + process.Start(); + Task stdout = process.StandardOutput.ReadToEndAsync(); + Task stderr = process.StandardError.ReadToEndAsync(); + if (!process.WaitForExit(120000)) + { + process.Kill(entireProcessTree: true); + Assert.Fail($"Test command timed out: {executable} {string.Join(" ", arguments)}"); + } + Task.WaitAll(stdout, stderr); + process.ExitCode.Should().Be(0, stderr.Result); + return stdout.Result.Trim(); + } + } +} diff --git a/.ci/unit_tests/Python_Engine_Test/Compute/Install.cs b/.ci/unit_tests/Python_Engine_Test/Compute/Install.cs new file mode 100644 index 00000000..e8952680 --- /dev/null +++ b/.ci/unit_tests/Python_Engine_Test/Compute/Install.cs @@ -0,0 +1,232 @@ +/* + * This file is part of the Buildings and Habitats object Model (BHoM) + * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. + * + * Each contributor holds copyright over their respective contributions. + * The project versioning (Git) records all such contribution source information. + * + * + * The BHoM is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3.0 of the License, or + * (at your option) any later version. + * + * The BHoM is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this code. If not, see . + */ + +using BH.oM.Python; +using FluentAssertions; +using EngineCompute = BH.Engine.Python.Compute; +using EngineQuery = BH.Engine.Python.Query; + +namespace BH.Tests.Engine.Python.Compute +{ + [NonParallelizable] + public class Install : Base + { + [Test] + public void InstallUV_InstallsPinnedVersion() + { + EngineCompute.InstallUV(run: true); + + Run(EngineQuery.UVExecutable(), "--version").Should().StartWith($"uv {EngineQuery.UVVersion()} "); + AssertNoErrors(); + } + + [Test] + public void InstallUV_SkipsWhenPinnedVersionPresent() + { + EngineCompute.InstallUV(run: true); + DateTime timestamp = File.GetLastWriteTimeUtc(EngineQuery.UVExecutable()); + + EngineCompute.InstallUV(run: true); + + File.GetLastWriteTimeUtc(EngineQuery.UVExecutable()).Should().Be(timestamp); + AssertNoErrors(); + } + + [Test] + public void InstallUV_DoesNotModifyPathOrInstallGlobalTools() + { + string? path = Environment.GetEnvironmentVariable("PATH"); + + EngineCompute.InstallUV(run: true); + + Environment.GetEnvironmentVariable("PATH").Should().Be(path); + Directory.Exists(Path.Combine(m_Root, "tools")).Should().BeFalse("no UV tools should be installed"); + AssertNoErrors(); + } + + [Test] + public void InstallUV_NotRunRecordsNote() + { + EngineCompute.InstallUV(run: false); + + BH.Engine.Base.Query.CurrentEvents().Should().Contain(e => e.Type == BH.oM.Base.Debugging.EventType.Note); + AssertNoErrors(); + } + + [Test] + public void UVEnvironmentVariables_KeepManagedFilesInToolsDirectory() + { + SetVariable("UV_PYTHON_INSTALL_DIR", ""); + SetVariable("UV_CACHE_DIR", ""); + + var variables = EngineQuery.UVEnvironmentVariables(); + + variables["UV_PYTHON_INSTALL_DIR"].Should().StartWith(EngineQuery.DirectoryTools()); + variables["UV_CACHE_DIR"].Should().StartWith(EngineQuery.DirectoryTools()); + variables["UV_NO_MODIFY_PATH"].Should().Be("1"); + } + + [Test] + public void UVEnvironmentVariables_RespectExistingValues() + { + SetVariable("UV_CACHE_DIR", Path.Combine(m_Root, "my-cache")); + + EngineQuery.UVEnvironmentVariables().Should().NotContainKey("UV_CACHE_DIR"); + } + + [Test] + public void InstallPackages_SkipsSatisfiedVersion() + { + PreparePackageVersions(); + EngineCompute.InstallPackages(m_Environment, ["bhom-repeat-package==1.0.0"], run: true); + string metadata = PackageMetadata("bhom_repeat_package", "1.0.0"); + DateTime timestamp = File.GetLastWriteTimeUtc(metadata); + + EngineCompute.InstallPackages(m_Environment, ["bhom-repeat-package>=1,<2"], run: true); + + File.GetLastWriteTimeUtc(metadata).Should().Be(timestamp); + AssertNoErrors(); + } + + [Test] + public void InstallPackages_ChangesUnsatisfiedVersion() + { + PreparePackageVersions(); + EngineCompute.InstallPackages(m_Environment, ["bhom-repeat-package==1.0.0"], run: true); + + EngineCompute.InstallPackages(m_Environment, ["bhom-repeat-package==2.0.0"], run: true); + + File.Exists(PackageMetadata("bhom_repeat_package", "2.0.0")).Should().BeTrue(); + File.Exists(PackageMetadata("bhom_repeat_package", "1.0.0")).Should().BeFalse(); + AssertNoErrors(); + } + + [Test] + public void InstallPackages_RegistersAlreadyInstalledProjectDependency() + { + PreparePackageVersions(); + EngineCompute.InstallPackages(m_Environment, ["bhom-repeat-package==1.0.0"], run: true); + string metadata = PackageMetadata("bhom_repeat_package", "1.0.0"); + DateTime timestamp = File.GetLastWriteTimeUtc(metadata); + CreateProject(); + + EngineCompute.InstallPackages(m_Environment, ["bhom-repeat-package==1.0.0"], run: true); + + File.ReadAllText(Path.Combine(m_Root, "pyproject.toml")).Should().Contain("bhom-repeat-package==1.0.0"); + File.GetLastWriteTimeUtc(metadata).Should().Be(timestamp); + AssertNoErrors(); + } + + [Test] + public void InstallPackageLocal_SkipsSameUnchangedEditableSource() + { + string source = CreateLocalPackage("source with spaces"); + EngineCompute.InstallPackageLocal(m_Environment, source, run: true); + string metadata = PackageMetadata("bhom_local_package", "1.0.0"); + File.Exists(metadata).Should().BeTrue(); + DateTime timestamp = File.GetLastWriteTimeUtc(metadata); + + EngineCompute.InstallPackageLocal(m_Environment, source, run: true); + + File.GetLastWriteTimeUtc(metadata).Should().Be(timestamp); + AssertNoErrors(); + } + + [Test] + public void InstallPackageLocal_ReplacesDifferentEditableSource() + { + string first = CreateLocalPackage("first"); + string second = CreateLocalPackage("second"); + EngineCompute.InstallPackageLocal(m_Environment, first, run: true); + + EngineCompute.InstallPackageLocal(m_Environment, second, run: true); + + string directUrl = Path.Combine(Path.GetDirectoryName(PackageMetadata("bhom_local_package", "1.0.0"))!, "direct_url.json"); + File.ReadAllText(directUrl).Should().Contain(new Uri(second + Path.DirectorySeparatorChar).AbsoluteUri.TrimEnd('/')); + AssertNoErrors(); + } + + [Test] + public void InstallPackageLocal_UpdatesChangedVersion() + { + string source = CreateLocalPackage("local"); + EngineCompute.InstallPackageLocal(m_Environment, source, run: true); + string project = Path.Combine(source, "pyproject.toml"); + File.WriteAllText(project, File.ReadAllText(project).Replace("1.0.0", "2.0.0")); + + EngineCompute.InstallPackageLocal(m_Environment, source, run: true); + + File.Exists(PackageMetadata("bhom_local_package", "2.0.0")).Should().BeTrue(); + File.Exists(PackageMetadata("bhom_local_package", "1.0.0")).Should().BeFalse(); + AssertNoErrors(); + } + + [Test] + public void InstallPackageLocal_RegistersProjectDependency() + { + string source = CreateLocalPackage("local"); + EngineCompute.InstallPackageLocal(m_Environment, source, run: true); + CreateProject(); + + EngineCompute.InstallPackageLocal(m_Environment, source, run: true); + + File.ReadAllText(Path.Combine(m_Root, "pyproject.toml")).Should().Contain("bhom-local-package"); + AssertNoErrors(); + } + + [Test] + public void InstallJupyterKernel_DoesNotModifyProjectToml() + { + CreateProject(); + string toml = Path.Combine(m_Root, "pyproject.toml"); + string before = File.ReadAllText(toml); + + EngineCompute.InstallJupyterKernel(m_Environment); + + File.ReadAllText(toml).Should().Be(before); + File.Exists(Path.Combine(m_Root, "jupyter", "kernels", m_Environment.Name, "kernel.json")).Should().BeTrue(); + AssertNoErrors(); + } + + [Test] + public void InstallPackages_MissingEnvironmentRecordsError() + { + EngineCompute.InstallPackages(new PythonEnvironment { Name = m_Environment.Name + "_missing", Executable = "missing.exe" }, ["anything"], run: true); + + BH.Engine.Base.Query.CurrentEvents().Should().Contain(e => e.Type == BH.oM.Base.Debugging.EventType.Error); + } + + [Test] + public void InstallJupyterKernel_SkipsExistingRegistration() + { + EngineCompute.InstallJupyterKernel(m_Environment); + string kernel = Path.Combine(m_Root, "jupyter", "kernels", m_Environment.Name, "kernel.json"); + File.Exists(kernel).Should().BeTrue(); + DateTime timestamp = File.GetLastWriteTimeUtc(kernel); + + EngineCompute.InstallJupyterKernel(m_Environment); + + File.GetLastWriteTimeUtc(kernel).Should().Be(timestamp); + AssertNoErrors(); + } + } +} diff --git a/.ci/unit_tests/Python_Engine_Test/Compute/Remove.cs b/.ci/unit_tests/Python_Engine_Test/Compute/Remove.cs new file mode 100644 index 00000000..e5298e74 --- /dev/null +++ b/.ci/unit_tests/Python_Engine_Test/Compute/Remove.cs @@ -0,0 +1,171 @@ +/* + * This file is part of the Buildings and Habitats object Model (BHoM) + * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. + * + * Each contributor holds copyright over their respective contributions. + * The project versioning (Git) records all such contribution source information. + * + * + * The BHoM is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3.0 of the License, or + * (at your option) any later version. + * + * The BHoM is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this code. If not, see . + */ + +using FluentAssertions; +using System.IO; +using EngineCompute = BH.Engine.Python.Compute; +using EngineQuery = BH.Engine.Python.Query; + +namespace BH.Tests.Engine.Python.Compute +{ + [NonParallelizable] + public class Remove : Base + { + [Test] + public void RemoveKernel_WarnsWhenEnvironmentDoesNotExist() + { + EngineCompute.RemoveJupyterKernel(m_Environment.Name + "_missing", run: true); + + AssertWarningWithoutErrors(); + } + + [Test] + public void RemoveKernel_WarnsWhenKernelDoesNotExist() + { + EngineCompute.RemoveJupyterKernel(m_Environment.Name, run: true); + + AssertWarningWithoutErrors(); + } + + [Test] + public void RemoveKernel_RemovesExistingKernelThenWarnsOnRepeat() + { + EngineCompute.InstallJupyterKernel(m_Environment); + AssertNoErrors(); + BH.Engine.Base.Compute.ClearCurrentEvents(); + + EngineCompute.RemoveJupyterKernel(m_Environment.Name, run: true); + + Directory.Exists(Path.Combine(m_Root, "jupyter", "kernels", m_Environment.Name)).Should().BeFalse(); + AssertNoErrors(); + EngineCompute.RemoveJupyterKernel(m_Environment.Name, run: true); + AssertWarningWithoutErrors(); + } + + [Test] + public void RemoveVirtualEnvironment_WarnsWhenEnvironmentDoesNotExist() + { + EngineCompute.RemoveVirtualEnvironment(m_Environment.Name + "_missing", run: true); + + AssertWarningWithoutErrors(); + } + + [Test] + public void RemoveVirtualEnvironment_RemovesEnvironmentWithoutKernelThenWarnsOnRepeat() + { + EngineCompute.RemoveVirtualEnvironment(m_Environment.Name, run: true); + + Directory.Exists(Path.Combine(m_Root, ".venv")).Should().BeFalse(); + AssertWarningWithoutErrors(); + BH.Engine.Base.Compute.ClearCurrentEvents(); + EngineCompute.RemoveVirtualEnvironment(m_Environment.Name, run: true); + AssertWarningWithoutErrors(); + } + + [Test] + public void RemoveUV_WarnsWhenManagedUVDoesNotExist() + { + CheckUVRemoval(managedUVExists: false); + } + + [Test] + public void RemoveUV_RemovesManagedToolsAndIgnoresExternalUV() + { + CheckUVRemoval(managedUVExists: true); + } + + [Test] + public void RemoveEverything_RemovesAllEnvironmentsAndUVButKeepsCode() + { + string uv = EngineQuery.UVExecutable(); + string environments = Path.Combine(m_Root, "extensions"); + SetVariable(TestEnvironment.ExtensionsVariable, environments); + File.Copy(uv, EngineQuery.UVExecutable()); + + string[] names = ["toolkit_a", "toolkit_b"]; + foreach (string name in names) + { + string directory = Path.Combine(environments, name); + Directory.CreateDirectory(directory); + File.WriteAllText(Path.Combine(directory, "pyproject.toml"), "code"); + Run(uv, "venv", "--no-project", "--no-python-downloads", Path.Combine(directory, ".venv")); + } + Directory.CreateDirectory(Path.Combine(environments, "code_only")); + + EngineCompute.RemoveEverything(run: true); + + foreach (string name in names) + { + Directory.Exists(Path.Combine(environments, name, ".venv")).Should().BeFalse(); + File.Exists(Path.Combine(environments, name, "pyproject.toml")).Should().BeTrue("toolkit code is retained"); + } + Directory.Exists(Path.Combine(environments, "code_only")).Should().BeTrue(); + Directory.Exists(Path.Combine(environments, "tools")).Should().BeFalse(); + AssertNoErrors(); + } + + [Test] + public void RemoveEverything_NotRunRemovesNothing() + { + EngineCompute.RemoveEverything(run: false); + + Directory.Exists(Path.Combine(m_Root, ".venv")).Should().BeTrue(); + File.Exists(EngineQuery.UVExecutable()).Should().BeTrue(); + BH.Engine.Base.Query.CurrentEvents().Should().Contain(e => e.Type == BH.oM.Base.Debugging.EventType.Note && e.Message.Contains(m_Environment.Name)); + } + + private void CheckUVRemoval(bool managedUVExists) + { + string toolsDirectory = EngineQuery.DirectoryTools(); + string externalDirectory = Path.Combine(m_Root, "external-uv"); + Directory.CreateDirectory(externalDirectory); + string externalUV = Path.Combine(externalDirectory, "uv.exe"); + File.Copy(EngineQuery.UVExecutable(), externalUV); + byte[] externalBytes = File.ReadAllBytes(externalUV); + SetVariable("PATH", externalDirectory + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH")); + + WithIsolatedDirectory(toolsDirectory, () => + { + string marker = Path.Combine(toolsDirectory, "other-tool.txt"); + File.WriteAllText(marker, "preserve when UV is missing"); + if (managedUVExists) + File.Copy(externalUV, EngineQuery.UVExecutable()); + + EngineCompute.RemoveUV(run: true); + + if (managedUVExists) + { + Directory.Exists(toolsDirectory).Should().BeFalse(); + AssertNoErrors(); + BH.Engine.Base.Query.CurrentEvents().Should().BeEmpty(); + } + else + { + File.Exists(marker).Should().BeTrue(); + AssertWarningWithoutErrors(); + } + File.ReadAllBytes(externalUV).Should().Equal(externalBytes); + Run(externalUV, "--version").Should().StartWith("uv "); + }); + } + } +} diff --git a/.ci/unit_tests/Python_Engine_Test/Compute/Run.cs b/.ci/unit_tests/Python_Engine_Test/Compute/Run.cs new file mode 100644 index 00000000..bd0c1824 --- /dev/null +++ b/.ci/unit_tests/Python_Engine_Test/Compute/Run.cs @@ -0,0 +1,91 @@ +/* + * This file is part of the Buildings and Habitats object Model (BHoM) + * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. + * + * Each contributor holds copyright over their respective contributions. + * The project versioning (Git) records all such contribution source information. + * + * + * The BHoM is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3.0 of the License, or + * (at your option) any later version. + * + * The BHoM is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this code. If not, see . + */ + +using BH.oM.Base.Debugging; +using FluentAssertions; +using System.Diagnostics; +using System.Text.RegularExpressions; +using EngineCompute = BH.Engine.Python.Compute; +using EngineQuery = BH.Engine.Python.Query; + +namespace BH.Tests.Engine.Python.Compute +{ + [NonParallelizable] + public class Run + { + [SetUp] + [TearDown] + public void CleanUp() + { + BH.Engine.Base.Compute.ClearCurrentEvents(); + } + + [TestCase(0)] + [TestCase(7)] + public void RunCommandStdout_ReturnsBothStreamsAndExitCode(int exitCode) + { + SynchronizationContext? original = SynchronizationContext.Current; + try + { + SynchronizationContext.SetSynchronizationContext(new NonPumpingContext()); + var result = EngineCompute.RunCommandStdout( + $"(for /L %i in (1,1,2000) do @(echo output& echo diagnostic 1>&2)) & exit /b {exitCode}"); + + result.Should().NotBeNull("failed commands must still return both streams and their exit code"); + result.Item1.Split('\n').Should().HaveCount(2000); + result.Item2.Split('\n').Should().HaveCount(2000); + result.Item1.Should().StartWith("output").And.EndWith("output"); + result.Item2.Should().StartWith("diagnostic").And.EndWith("diagnostic"); + result.Item3.Should().Be(exitCode); + BH.Engine.Base.Query.CurrentEvents().Any(e => e.Type == EventType.Error).Should().Be(exitCode != 0); + } + finally + { + SynchronizationContext.SetSynchronizationContext(original); + } + } + + [Test] + public void RunCommandStdout_TimeoutRetainsBothStreams() + { + Stopwatch timer = Stopwatch.StartNew(); + var result = EngineCompute.RunCommandStdout( + "echo started & echo diagnostic 1>&2 & powershell.exe -NoProfile -NonInteractive -Command \"Start-Sleep -Seconds 30\"", + timeoutMinutes: 0.02); + + result.Should().NotBeNull("timeouts must still return captured streams and exit code -1"); + result.Item1.Should().Be("started"); + result.Item2.Should().Be("diagnostic"); + result.Item3.Should().Be(-1); + timer.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(10)); + BH.Engine.Base.Query.CurrentEvents().Should().Contain(e => e.Type == EventType.Error && e.Message.Contains("timeout")); + } + + private sealed class NonPumpingContext : SynchronizationContext + { + public override void Post(SendOrPostCallback callback, object? state) + { + throw new InvalidOperationException("The command runner captured the host synchronization context."); + } + } + } +} diff --git a/.ci/unit_tests/Python_Engine_Test/Compute/RunPytest.cs b/.ci/unit_tests/Python_Engine_Test/Compute/RunPytest.cs new file mode 100644 index 00000000..37c68f0e --- /dev/null +++ b/.ci/unit_tests/Python_Engine_Test/Compute/RunPytest.cs @@ -0,0 +1,93 @@ +/* + * This file is part of the Buildings and Habitats object Model (BHoM) + * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. + * + * Each contributor holds copyright over their respective contributions. + * The project versioning (Git) records all such contribution source information. + * + * + * The BHoM is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3.0 of the License, or + * (at your option) any later version. + * + * The BHoM is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this code. If not, see . + */ + +using BH.oM.Base.Debugging; +using FluentAssertions; +using EngineCompute = BH.Engine.Python.Compute; +using EngineQuery = BH.Engine.Python.Query; + +namespace BH.Tests.Engine.Python.Compute +{ + [NonParallelizable] + public class RunPytest : Base + { + private void PrepareTests() + { + // pytest comes from the shared UV cache (set up by TestEnvironment), so this is fast after the first run + SetVariable("UV_CACHE_DIR", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "uv", "cache")); + Run(EngineQuery.UVExecutable(), "pip", "install", "--python", m_Environment.Executable, "pytest"); + Directory.CreateDirectory(Path.Combine(m_Root, "tests")); + File.WriteAllText(Path.Combine(m_Root, "tests", "test_sample.py"), + "import os\n\n" + + "def test_passes():\n assert True\n\n" + + "def test_fails():\n assert False, 'expected failure'\n\n" + + "def test_analytics_disabled():\n assert os.environ.get('DISABLE_BHOM_ANALYTICS') == '1'\n"); + } + + [Test] + public void RunPytest_ReportsFailures() + { + PrepareTests(); + + var result = EngineCompute.RunPytest(m_Root, run: true); + + result.Should().NotBeNull(); + result.Item1.Should().BeFalse(); + result.Item2.Should().Be(1); + result.Item3.Should().Contain("expected failure").And.Contain("1 failed, 2 passed"); + File.Exists(result.Item4).Should().BeTrue(); + File.ReadAllText(result.Item4).Should().Contain("test_fails"); + } + + [Test] + public void RunPytest_PassesArgumentsAndAcceptsEnvironment() + { + PrepareTests(); + + var result = EngineCompute.RunPytest(m_Environment, "-k \"passes or analytics\"", run: true); + + result.Item1.Should().BeTrue(result.Item3); + result.Item2.Should().Be(0); + result.Item3.Should().Contain("2 passed"); + AssertNoErrors(); + } + + [Test] + public void RunPytest_NotRunRecordsNote() + { + EngineCompute.RunPytest(m_Root, run: false).Should().BeNull(); + + BH.Engine.Base.Query.CurrentEvents().Should().Contain(e => e.Type == EventType.Note && e.Message.Contains("pytest")); + } + + [Test] + public void RunPytest_MissingEnvironmentRecordsError() + { + string directory = Path.Combine(m_Root, "no_venv"); + Directory.CreateDirectory(directory); + + EngineCompute.RunPytest(directory, run: true).Should().BeNull(); + + BH.Engine.Base.Query.CurrentEvents().Should().Contain(e => e.Type == EventType.Error && e.Message.Contains("No virtual environment")); + } + } +} diff --git a/.ci/unit_tests/Python_Engine_Test/Compute/VirtualEnvironment.cs b/.ci/unit_tests/Python_Engine_Test/Compute/VirtualEnvironment.cs new file mode 100644 index 00000000..6497ed98 --- /dev/null +++ b/.ci/unit_tests/Python_Engine_Test/Compute/VirtualEnvironment.cs @@ -0,0 +1,275 @@ +/* + * This file is part of the Buildings and Habitats object Model (BHoM) + * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. + * + * Each contributor holds copyright over their respective contributions. + * The project versioning (Git) records all such contribution source information. + * + * + * The BHoM is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3.0 of the License, or + * (at your option) any later version. + * + * The BHoM is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this code. If not, see . + */ + +using BH.oM.Base.Debugging; +using BH.oM.Python; +using FluentAssertions; +using EngineCompute = BH.Engine.Python.Compute; +using EngineQuery = BH.Engine.Python.Query; + +namespace BH.Tests.Engine.Python.Compute +{ + [NonParallelizable] + public class VirtualEnvironment + { + private readonly Dictionary m_OriginalVariables = []; + private string m_TestDirectory = null!; + private string m_Name = null!; + private string m_Directory = null!; + + [OneTimeSetUp] + public void SetUpTools() + { + m_TestDirectory = Path.Combine(Path.GetTempPath(), "bhom_lifecycle_" + Guid.NewGuid().ToString("N")); + foreach (string variable in new[] { "UV_TOOL_DIR", "UV_TOOL_BIN_DIR", "JUPYTER_DATA_DIR", "JUPYTER_PATH" }) + { + m_OriginalVariables[variable] = Environment.GetEnvironmentVariable(variable); + Environment.SetEnvironmentVariable(variable, Path.Combine(m_TestDirectory, variable)); + } + } + + [SetUp] + public void SetUp() + { + m_Name = "bhom_lifecycle_" + Guid.NewGuid().ToString("N"); + m_Directory = Path.Combine(EngineQuery.DirectoryEnvironments(), m_Name); + BH.Engine.Base.Compute.ClearCurrentEvents(); + } + + [TearDown] + public void CleanUpEnvironment() + { + if (EngineQuery.VirtualEnvironmentExists(m_Name)) + EngineCompute.RemoveVirtualEnvironment(m_Name, run: true); + if (Directory.Exists(m_Directory)) + Directory.Delete(m_Directory, true); + BH.Engine.Base.Compute.ClearCurrentEvents(); + } + + [OneTimeTearDown] + public void CleanUpTools() + { + foreach (var variable in m_OriginalVariables) + Environment.SetEnvironmentVariable(variable.Key, variable.Value); + if (Directory.Exists(m_TestDirectory)) + Directory.Delete(m_TestDirectory, true); + } + + [Test] + public void VirtualEnvironment_FromTargetVersion_CreatesReloadsAndRemovesEnvironmentAndKernel() + { + PythonEnvironment venv = EngineCompute.VirtualEnvironment("3.11", m_Name); + venv.Should().NotBeNull(); + File.Exists(venv.Executable).Should().BeTrue(); + EngineQuery.Version(venv).Should().StartWith("3.11."); + EngineCompute.RunPythonString(venv, "import ipykernel; print('ready')").Should().Be("ready"); + EngineCompute.VirtualEnvironment("3.11", m_Name, reload: true).Executable.Should().Be(venv.Executable); + File.Exists(KernelFile()).Should().BeTrue(); + + EngineCompute.RemoveVirtualEnvironment(m_Name, run: true); + + Directory.Exists(Path.Combine(m_Directory, ".venv")).Should().BeFalse(); + File.Exists(KernelFile()).Should().BeFalse(); + AssertNoErrors(); + } + + [Test] + public void VirtualEnvironment_FromTOML_CreatesReloadsAndRemovesEnvironmentAndKernel() + { + string packageDirectory = Path.Combine(m_Directory, "src", m_Name); + Directory.CreateDirectory(packageDirectory); + File.WriteAllText(Path.Combine(packageDirectory, "__init__.py"), ""); + File.WriteAllText(Path.Combine(m_Directory, "README.md"), ""); + string tomlFile = Path.Combine(m_Directory, "pyproject.toml"); + File.WriteAllText(tomlFile, + $"[project]\nname = '{m_Name}'\nversion = '0.1.0' # project version\nreadme = 'README.md'\n" + + "requires-python = '>=3.11,<3.12'\ndependencies = []\n" + + "[build-system]\nrequires = ['hatchling']\nbuild-backend = 'hatchling.build'\n" + + "[tool.bhom]\nversion = 'leave-this-alone'\n"); + + PythonEnvironment venv = EngineCompute.VirtualEnvironment(tomlFile, reload: false); + venv.Should().NotBeNull(); + string version = BH.Engine.Base.Query.BHoMVersion(); + File.ReadAllText(tomlFile).Should().Contain($"version = '{version}' # project version") + .And.Contain("version = 'leave-this-alone'"); + EngineCompute.RunPythonString(venv, + $"import importlib.metadata; print(importlib.metadata.version('{m_Name}'))").Should().Be(version); + + EngineCompute.VirtualEnvironment(tomlFile, reload: false).Should().NotBeNull(); + File.Exists(Path.Combine(packageDirectory, "__init__.py")).Should().BeTrue(); + + // a redeployed (unstamped) TOML is re-stamped on reload, and the installed metadata follows + File.WriteAllText(tomlFile, File.ReadAllText(tomlFile).Replace($"version = '{version}'", "version = '999.999.999'")); + EngineCompute.VirtualEnvironment(tomlFile, reload: true).Should().NotBeNull(); + File.ReadAllText(tomlFile).Should().Contain($"version = '{version}' # project version"); + EngineCompute.RunPythonString(venv, + $"import importlib.metadata; print(importlib.metadata.version('{m_Name}'))").Should().Be(version); + File.ReadAllText(tomlFile).Should().NotContain("ipykernel", "registering the kernel must not add dependencies"); + EngineCompute.VirtualEnvironment(tomlFile, reload: true).Executable.Should().Be(venv.Executable); + EngineCompute.RemoveVirtualEnvironment(m_Name, run: true); + + Directory.Exists(Path.Combine(m_Directory, ".venv")).Should().BeFalse(); + File.Exists(KernelFile()).Should().BeFalse(); + AssertNoErrors(); + } + + [Test] + public void VirtualEnvironment_FromTOML_StampsCRLFVersionWithoutComment() + { + string tomlFile = CreateToolkitFiles( + "[project]\r\nname = 'NAME'\r\nversion = \"0.1.0\"\r\nrequires-python = '>=3.10'\r\n" + + "[tool.uv.sources]\r\nmissing_toolkit = { path = \"../Missing_Toolkit\", editable = true }\r\n"); + + // the missing dependency stops creation before syncing, after the version has been stamped + EngineCompute.VirtualEnvironment(tomlFile).Should().BeNull(); + + File.ReadAllText(tomlFile).Should().Contain($"version = \"{BH.Engine.Base.Query.BHoMVersion()}\"\r\nrequires-python"); + } + + [Test] + public void VirtualEnvironment_FromTOML_MissingDependencyToolkitRecordsError() + { + string tomlFile = CreateToolkitFiles( + "[project]\nname = 'NAME'\nversion = '0.1.0'\n\n" + + "[tool.uv.sources]\nmissing_toolkit = { path = \"../Missing_Toolkit\", editable = true }\n"); + + EngineCompute.VirtualEnvironment(tomlFile).Should().BeNull(); + + BH.Engine.Base.Query.CurrentEvents().Should().Contain(e => e.Type == EventType.Error && e.Message.Contains("missing_toolkit")); + EngineQuery.VirtualEnvironmentExists(m_Name).Should().BeFalse(); + } + + [Test] + public void VirtualEnvironment_FromTOML_StampsDeployedDependencyVersion() + { + string dependency = Path.Combine(EngineQuery.DirectoryEnvironments(), m_Name + "_dependency"); + Directory.CreateDirectory(dependency); + try + { + File.WriteAllText(Path.Combine(dependency, "pyproject.toml"), "[project]\nname = 'dep'\nversion = '999.999.999' # placeholder\n"); + string tomlFile = CreateToolkitFiles( + "[project]\nname = 'NAME'\nversion = '0.1.0'\n\n" + + $"[tool.uv.sources]\ndep = {{ path = \"../{m_Name}_dependency\", editable = true }}\n" + + "other = { path = \"../Missing\" }\n"); + + EngineCompute.VirtualEnvironment(tomlFile).Should().BeNull(); // "other" is missing + + File.ReadAllText(Path.Combine(dependency, "pyproject.toml")) + .Should().Contain($"version = '{BH.Engine.Base.Query.BHoMVersion()}' # placeholder"); + } + finally + { + Directory.Delete(dependency, true); + } + } + + [Test] + public void VirtualEnvironment_FromTOML_MissingTransitiveDependencyRecordsErrorWithChain() + { + // this toolkit -> middle (deployed) -> deep_toolkit (missing) + string middle = Path.Combine(EngineQuery.DirectoryEnvironments(), m_Name + "_middle"); + Directory.CreateDirectory(middle); + try + { + File.WriteAllText(Path.Combine(middle, "pyproject.toml"), + "[project]\nname = 'middle'\nversion = '999.999.999'\n\n" + + "[tool.uv.sources]\ndeep_toolkit = { path = \"../Deep_Toolkit\", editable = true }\n"); + string tomlFile = CreateToolkitFiles( + "[project]\nname = 'NAME'\nversion = '0.1.0'\n\n" + + $"[tool.uv.sources]\nmiddle = {{ path = \"../{m_Name}_middle\", editable = true }}\n"); + + EngineCompute.VirtualEnvironment(tomlFile).Should().BeNull(); + + BH.Engine.Base.Query.CurrentEvents().Should().Contain(e => e.Type == EventType.Error + && e.Message.Contains("deep_toolkit") + && e.Message.Contains($"{m_Name} -> middle -> deep_toolkit")); + EngineQuery.VirtualEnvironmentExists(m_Name).Should().BeFalse(); + File.ReadAllText(Path.Combine(middle, "pyproject.toml")) + .Should().Contain($"version = '{BH.Engine.Base.Query.BHoMVersion()}'", "deployed toolkits along the chain are stamped"); + } + finally + { + Directory.Delete(middle, true); + } + } + + [Test] + public void VirtualEnvironment_FromTOML_CircularDependencyIsCheckedOnce() + { + // this toolkit <-> middle, and middle also needs a missing toolkit (so creation stops before syncing) + string middle = Path.Combine(EngineQuery.DirectoryEnvironments(), m_Name + "_middle"); + Directory.CreateDirectory(middle); + try + { + File.WriteAllText(Path.Combine(middle, "pyproject.toml"), + "[project]\nname = 'middle'\nversion = '0.1.0'\n\n" + + $"[tool.uv.sources]\nback = {{ path = \"../{m_Name}\", editable = true }}\n" + + "missing = { path = \"../Missing\" }\n"); + string tomlFile = CreateToolkitFiles( + "[project]\nname = 'NAME'\nversion = '0.1.0'\n\n" + + $"[tool.uv.sources]\nmiddle = {{ path = \"../{m_Name}_middle\", editable = true }}\n"); + + EngineCompute.VirtualEnvironment(tomlFile).Should().BeNull(); + + BH.Engine.Base.Query.CurrentEvents().Where(e => e.Type == EventType.Error) + .Should().ContainSingle(e => e.Message.Contains("missing")); + } + finally + { + Directory.Delete(middle, true); + } + } + + [Test] + public void VirtualEnvironment_FromTOML_OutsideEnvironmentsDirectoryRecordsError() + { + string outside = Path.Combine(m_TestDirectory, m_Name); + Directory.CreateDirectory(outside); + string tomlFile = Path.Combine(outside, "pyproject.toml"); + File.WriteAllText(tomlFile, "[project]\nname = 'x'\nversion = '0.1.0'\n"); + + EngineCompute.VirtualEnvironment(tomlFile).Should().BeNull(); + + BH.Engine.Base.Query.CurrentEvents().Should().Contain(e => e.Type == EventType.Error && e.Message.Contains("must be deployed")); + } + + private string CreateToolkitFiles(string toml) + { + Directory.CreateDirectory(Path.Combine(m_Directory, "src", m_Name)); + File.WriteAllText(Path.Combine(m_Directory, "src", m_Name, "__init__.py"), ""); + File.WriteAllText(Path.Combine(m_Directory, "README.md"), ""); + string tomlFile = Path.Combine(m_Directory, "pyproject.toml"); + File.WriteAllText(tomlFile, toml.Replace("NAME", m_Name)); + return tomlFile; + } + + private string KernelFile() + { + return Path.Combine(Environment.GetEnvironmentVariable("JUPYTER_DATA_DIR")!, "kernels", m_Name, "kernel.json"); + } + + private static void AssertNoErrors() + { + BH.Engine.Base.Query.CurrentEvents().Where(e => e.Type == EventType.Error).Select(e => e.Message).Should().BeEmpty(); + } + } +} diff --git a/.ci/unit_tests/Python_Engine_Test/PythonToolkit.cs b/.ci/unit_tests/Python_Engine_Test/PythonToolkit.cs new file mode 100644 index 00000000..16509c2f --- /dev/null +++ b/.ci/unit_tests/Python_Engine_Test/PythonToolkit.cs @@ -0,0 +1,145 @@ +/* + * This file is part of the Buildings and Habitats object Model (BHoM) + * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. + * + * Each contributor holds copyright over their respective contributions. + * The project versioning (Git) records all such contribution source information. + * + * + * The BHoM is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3.0 of the License, or + * (at your option) any later version. + * + * The BHoM is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this code. If not, see . + */ + +using BH.oM.Base.Debugging; +using BH.oM.Python; +using FluentAssertions; +using EngineCompute = BH.Engine.Python.Compute; +using EngineQuery = BH.Engine.Python.Query; + +namespace BH.Tests.Engine.Python +{ + /// + /// End-to-end tests of the full toolkit workflow, run in order against the isolated BHoM Python directory: + /// deploy Python_Toolkit, create its environment, run its Python tests from C#, then scaffold a downstream toolkit + /// that depends on it and create and test that toolkit's own environment. + /// These need network access (or a warm UV cache) and take a few minutes: filter them with --filter "Category!=Integration". + /// + [NonParallelizable] + [Category("Integration")] + [TestFixture] + public class PythonToolkit + { + private const string DownstreamName = "Smoke_Toolkit"; + private readonly Dictionary m_OriginalVariables = new(); + private static PythonEnvironment? m_Root; + + [OneTimeSetUp] + public void IsolateJupyter() + { + string jupyter = Path.Combine(TestEnvironment.Root, "jupyter"); + foreach (string variable in new[] { "JUPYTER_DATA_DIR", "JUPYTER_PATH" }) + { + m_OriginalVariables[variable] = Environment.GetEnvironmentVariable(variable); + Environment.SetEnvironmentVariable(variable, jupyter); + } + } + + [OneTimeTearDown] + public void RestoreJupyter() + { + foreach (var variable in m_OriginalVariables) + Environment.SetEnvironmentVariable(variable.Key, variable.Value); + } + + [SetUp] + public void ClearEvents() + { + BH.Engine.Base.Compute.ClearCurrentEvents(); + } + + [Test, Order(1)] + public void InstallPythonToolkitVenv_CreatesEnvironment() + { + TestEnvironment.DeployPythonToolkit(); + + m_Root = EngineCompute.InstallPythonToolkitVenv(run: true, reload: false); + + AssertNoErrors(); + m_Root.Should().NotBeNull(); + File.Exists(m_Root!.Executable).Should().BeTrue(); + EngineCompute.RunPythonString(m_Root, "import python_toolkit.bhom.analytics, matplotlib; print('ok')").Should().Be("ok"); + File.ReadAllText(Path.Combine(EngineQuery.DirectoryEnvironments(), "Python_Toolkit", "pyproject.toml")) + .Should().Contain($"version = \"{BH.Engine.Base.Query.BHoMVersion()}\""); + } + + [Test, Order(2)] + public void RunPytest_PythonToolkitTestsPass() + { + Assume.That(m_Root, Is.Not.Null, "requires the Python_Toolkit environment"); + + var result = EngineCompute.RunPytest(m_Root!, "-m \"not slow\"", run: true); + + TestContext.Progress.WriteLine(result.Item3); + result.Item1.Should().BeTrue("pytest must pass:\n{0}", result.Item3); + File.Exists(result.Item4).Should().BeTrue(); + AssertNoErrors(); + } + + [Test, Order(3)] + public void CreateToolkit_DownstreamToolkitBuildsAndPassesItsTests() + { + Assume.That(m_Root, Is.Not.Null, "requires the Python_Toolkit environment"); + string directory = Path.Combine(EngineQuery.DirectoryEnvironments(), DownstreamName); + string pythonVersion = string.Join(".", EngineQuery.Version(m_Root!)!.Split(".").Take(2)); + + var created = EngineCompute.CreateToolkit(DownstreamName, directory, pythonVersion, run: true); + + created.Item1.Should().BeTrue(created.Item2); + created.Item2.Should().Contain("Next steps"); + File.Exists(Path.Combine(directory, "src", "smoke_toolkit", "example.py")).Should().BeTrue(); + + // the downstream toolkit resolves Python_Toolkit from the deployed location, in its own environment + PythonEnvironment venv = EngineCompute.VirtualEnvironment(Path.Combine(directory, "pyproject.toml"), reload: false); + AssertNoErrors(); + venv.Should().NotBeNull(); + venv.Executable.Should().StartWith(directory); + EngineCompute.RunPythonString(venv, "import smoke_toolkit.example as e; print(e.add(1, 2))").Should().Be("3"); + + var tests = EngineCompute.RunPytest(venv, run: true); + tests.Item1.Should().BeTrue(tests.Item3); + } + + [Test, Order(4)] + public void RemoveEverything_CleansUp() + { + Assume.That(m_Root, Is.Not.Null, "requires the Python_Toolkit environment"); + string uvBackup = Path.Combine(TestEnvironment.Root, "uv.backup.exe"); + File.Copy(EngineQuery.UVExecutable(), uvBackup, true); + + EngineCompute.RemoveEverything(run: true); + + EngineQuery.VirtualEnvironmentExists("Python_Toolkit").Should().BeFalse(); + EngineQuery.VirtualEnvironmentExists(DownstreamName).Should().BeFalse(); + File.Exists(Path.Combine(EngineQuery.DirectoryEnvironments(), "Python_Toolkit", "pyproject.toml")).Should().BeTrue(); + AssertNoErrors(); + + // restore UV for any fixtures that run afterwards + File.Copy(uvBackup, EngineQuery.UVExecutable(), true); + } + + private static void AssertNoErrors() + { + BH.Engine.Base.Query.CurrentEvents().Where(e => e.Type == EventType.Error).Select(e => e.Message).Should().BeEmpty(); + } + } +} diff --git a/.ci/unit_tests/Python_Engine_Test/Python_Engine_Test.csproj b/.ci/unit_tests/Python_Engine_Test/Python_Engine_Test.csproj new file mode 100644 index 00000000..017e01f0 --- /dev/null +++ b/.ci/unit_tests/Python_Engine_Test/Python_Engine_Test.csproj @@ -0,0 +1,41 @@ + + + + net9.0 + latest + enable + enable + false + BH.Tests.Engine.Python + + + + + + + + + + + + + + + + + + + $(ProgramData)\BHoM\Assemblies\BHoM.dll + True + + + $(ProgramData)\BHoM\Assemblies\BHoM_Engine.dll + True + + + + + + + + diff --git a/.ci/unit_tests/Python_Engine_Test/Query/Directory.cs b/.ci/unit_tests/Python_Engine_Test/Query/Directory.cs new file mode 100644 index 00000000..1552c1e2 --- /dev/null +++ b/.ci/unit_tests/Python_Engine_Test/Query/Directory.cs @@ -0,0 +1,84 @@ +/* + * This file is part of the Buildings and Habitats object Model (BHoM) + * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. + * + * Each contributor holds copyright over their respective contributions. + * The project versioning (Git) records all such contribution source information. + * + * + * The BHoM is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3.0 of the License, or + * (at your option) any later version. + * + * The BHoM is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this code. If not, see . + */ + +using FluentAssertions; +using EngineQuery = BH.Engine.Python.Query; + +namespace BH.Tests.Engine.Python.Query +{ + [NonParallelizable] + public class Directory_Tests + { + [Test] + public void DirectoryExtensions_IsNextToTheBHoMInstallation() + { + string expected = Path.Combine(Directory.GetParent(BH.Engine.Base.Query.BHoMFolder())!.FullName, "Extensions"); + + EngineQuery.DirectoryExtensions().Should().Be(expected); + } + + [Test] + public void DirectoryEnvironments_DefaultsToExtensionsPython() + { + string? redirected = Environment.GetEnvironmentVariable(TestEnvironment.ExtensionsVariable); + try + { + Environment.SetEnvironmentVariable(TestEnvironment.ExtensionsVariable, null); + + string expected = Path.Combine(EngineQuery.DirectoryExtensions(), "Python"); + Assume.That(Directory.Exists(expected), "BHoM must be installed (the default folder is not created by this test)"); + + EngineQuery.DirectoryEnvironments().Should().Be(expected); + } + finally + { + Environment.SetEnvironmentVariable(TestEnvironment.ExtensionsVariable, redirected); + } + } + + [Test] + public void DirectoryEnvironments_HonoursOverrideAndCreatesIt() + { + string? redirected = Environment.GetEnvironmentVariable(TestEnvironment.ExtensionsVariable); + string custom = Path.Combine(TestEnvironment.Root, "custom_" + Guid.NewGuid().ToString("N")); + try + { + Environment.SetEnvironmentVariable(TestEnvironment.ExtensionsVariable, custom); + + EngineQuery.DirectoryEnvironments().Should().Be(custom); + Directory.Exists(custom).Should().BeTrue(); + EngineQuery.DirectoryTools().Should().Be(Path.Combine(custom, "tools")); + EngineQuery.UVExecutable().Should().Be(Path.Combine(custom, "tools", "uv.exe")); + } + finally + { + Environment.SetEnvironmentVariable(TestEnvironment.ExtensionsVariable, redirected); + } + } + + [Test] + public void TestsAreIsolatedFromProgramData() + { + EngineQuery.DirectoryEnvironments().Should().StartWith(TestEnvironment.Root); + } + } +} diff --git a/.ci/unit_tests/Python_Engine_Test/TestEnvironment.cs b/.ci/unit_tests/Python_Engine_Test/TestEnvironment.cs new file mode 100644 index 00000000..9d64be95 --- /dev/null +++ b/.ci/unit_tests/Python_Engine_Test/TestEnvironment.cs @@ -0,0 +1,145 @@ +/* + * This file is part of the Buildings and Habitats object Model (BHoM) + * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. + * + * Each contributor holds copyright over their respective contributions. + * The project versioning (Git) records all such contribution source information. + * + * + * The BHoM is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3.0 of the License, or + * (at your option) any later version. + * + * The BHoM is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this code. If not, see . + */ + +using System.Diagnostics; +using EngineQuery = BH.Engine.Python.Query; + +namespace BH.Tests.Engine.Python +{ + /// + /// Runs once around every test in this assembly. All BHoM Python directories are redirected to a temporary folder + /// (via BHOM_PYTHON_EXTENSIONS_DIR), so tests never read or modify the real %ProgramData%\BHoM installation. + /// + [SetUpFixture] + public class TestEnvironment + { + public const string ExtensionsVariable = "BHOM_PYTHON_EXTENSIONS_DIR"; + + private static readonly Dictionary m_Original = new(); + + /// The temporary folder standing in for %ProgramData%\BHoM\Extensions\Python. + public static string Root { get; private set; } = null!; + + /// The repository's Python_Engine/Python folder (the Python_Toolkit source). + public static string PythonSource + { + get + { + DirectoryInfo? directory = new(TestContext.CurrentContext.TestDirectory); + while (directory != null && !File.Exists(Path.Combine(directory.FullName, "Python_Engine", "Python", "pyproject.toml"))) + directory = directory.Parent; + if (directory == null) + throw new DirectoryNotFoundException("The repository's Python_Engine/Python folder could not be found."); + return Path.Combine(directory.FullName, "Python_Engine", "Python"); + } + } + + [OneTimeSetUp] + public void RedirectBHoMPythonDirectories() + { + Root = Path.Combine(Path.GetTempPath(), "bhom_python_tests_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(Root); + Set(ExtensionsVariable, Root); + + // Reuse the user's own UV interpreter store and cache (rather than the per-run tools folder) so tests do not + // download Python and packages on every run. These are respected by Query.UVEnvironmentVariables(). + string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + SetIfUnset("UV_PYTHON_INSTALL_DIR", Path.Combine(appData, "uv", "python")); + SetIfUnset("UV_CACHE_DIR", Path.Combine(localAppData, "uv", "cache")); + + SeedUV(); + } + + [OneTimeTearDown] + public void RestoreBHoMPythonDirectories() + { + foreach (var variable in m_Original) + Environment.SetEnvironmentVariable(variable.Key, variable.Value); + m_Original.Clear(); + + try + { + if (Directory.Exists(Root)) + Directory.Delete(Root, true); + } + catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) + { + TestContext.Progress.WriteLine($"Could not fully remove {Root}: {ex.Message}"); + } + } + + /// Copy the Python_Toolkit source into the redirected directory, as the build's deploy step would. + public static string DeployPythonToolkit() + { + string target = Path.Combine(EngineQuery.DirectoryEnvironments(), "Python_Toolkit"); + CopyDirectory(PythonSource, target); + return target; + } + + private static void CopyDirectory(string source, string target) + { + Directory.CreateDirectory(target); + foreach (string file in Directory.GetFiles(source)) + { + string name = Path.GetFileName(file); + if (name == "uv.lock" || name.EndsWith(".pyc") || name == ".pytest_results.xml") + continue; + File.Copy(file, Path.Combine(target, name), true); + } + foreach (string directory in Directory.GetDirectories(source)) + { + string name = Path.GetFileName(directory); + if (name.StartsWith(".") || (name.StartsWith("__") && name.EndsWith("__")) || name == "_build" || name == "autoapi") + continue; + CopyDirectory(directory, Path.Combine(target, name)); + } + } + + // Copy an installed UV of the pinned version, if one exists, to avoid downloading it for every test run. + private static void SeedUV() + { + string installed = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "BHoM", "Extensions", "Python", "tools", "uv.exe"); + if (!File.Exists(installed)) + return; + + using Process process = Process.Start(new ProcessStartInfo(installed, "--version") { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true })!; + string version = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + if (version.StartsWith($"uv {EngineQuery.UVVersion()} ")) + File.Copy(installed, EngineQuery.UVExecutable(), true); + } + + private static void Set(string name, string value) + { + if (!m_Original.ContainsKey(name)) + m_Original[name] = Environment.GetEnvironmentVariable(name); + Environment.SetEnvironmentVariable(name, value); + } + + private static void SetIfUnset(string name, string value) + { + if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(name))) + Set(name, value); + } + } +} diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml new file mode 100644 index 00000000..c07e6a59 --- /dev/null +++ b/.github/workflows/python.yml @@ -0,0 +1,59 @@ +# Python quality gate for Python_Engine/Python: formatting, linting and tests. +# Runs alongside the BHoM CI (ci-beta.yml), which covers the C# projects. + +name: Python + +on: + pull_request: + branches: + - develop + paths: + - "Python_Engine/Python/**" + - ".github/workflows/python.yml" + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +defaults: + run: + working-directory: Python_Engine/Python + +jobs: + lint: + runs-on: windows-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v6 + with: + version: "0.13.10" # keep in sync with BH.Engine.Python.Query.UVVersion() + - run: uv sync --all-extras + - run: uv run ruff format --check . + - run: uv run ruff check --output-format=github . + + test: + runs-on: windows-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + # the supported floor (every downstream toolkit installs this package) and a newer version + python: ["3.10", "3.12"] + env: + UV_PYTHON: ${{ matrix.python }} + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v6 + with: + version: "0.13.10" + - name: Core is standard-library only + run: | + uv sync --no-dev + uv run --no-dev python -c "import python_toolkit.bhom.analytics, python_toolkit.bhom.run_wrapped, python_toolkit.scaffold" + - run: uv sync --all-extras + - name: Tests (including slow end-to-end scaffold test) + run: uv run pytest --cov --cov-report=term-missing + - name: Docs build + if: matrix.python == '3.10' + run: uv run --all-extras --group docs sphinx-build -b html docs docs/_build/html diff --git a/.gitignore b/.gitignore index 48d3a171..cc63ef37 100644 --- a/.gitignore +++ b/.gitignore @@ -94,7 +94,12 @@ Alligator/Alligator_REMOTE_9848.csproj # VSCode User File # #################### -.vscode/ +# shared workspace configuration is committed; anything else in .vscode is personal +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json # User defined files # ###################### @@ -147,7 +152,8 @@ instance/ .scrapy # Sphinx documentation -docs/_build/ +**/docs/_build/ +**/docs/autoapi # PyBuilder .pybuilder/ @@ -216,5 +222,14 @@ dmypy.json # Cython debug symbols cython_debug/ -# unignored files -!example.sql +# Additional directories to ignore +.benchmarks/ + +# UV +uv.lock + +# Ruff +.ruff_cache/ + +# pytest results written by BH.Engine.Python.Compute.RunPytest +.pytest_results.xml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..f3bc251b --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,18 @@ +# Format and lint Python with the shared BHoM ruff standard (Python_Engine/Python/ruff.toml) on every commit. +# Install the hooks once with: uv run --project Python_Engine/Python pre-commit install +# The hooks use the project's own ruff (via uv), so the version always matches the one used in CI and VS Code. +repos: + - repo: local + hooks: + - id: ruff-format + name: ruff format + entry: uv run --project Python_Engine/Python ruff format + language: system + types_or: [python, pyi] + files: ^Python_Engine/Python/ + - id: ruff-check + name: ruff check + entry: uv run --project Python_Engine/Python ruff check --fix --exit-non-zero-on-fix + language: system + types_or: [python, pyi] + files: ^Python_Engine/Python/ diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 00000000..5251a7ea --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,9 @@ +{ + "recommendations": [ + "ms-dotnettools.csdevkit", + "ms-python.python", + "ms-python.debugpy", + "charliermarsh.ruff", + "tamasfe.even-better-toml" + ] +} diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..2aad0181 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,26 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Python: current file", + "type": "debugpy", + "request": "launch", + "program": "${file}", + "cwd": "${workspaceFolder}/Python_Engine/Python", + "python": "${workspaceFolder}/Python_Engine/Python/.venv/Scripts/python.exe", + "console": "integratedTerminal", + "justMyCode": true + }, + { + "name": "Python: pytest current file", + "type": "debugpy", + "request": "launch", + "module": "pytest", + "args": ["${file}", "-x", "-vv"], + "cwd": "${workspaceFolder}/Python_Engine/Python", + "python": "${workspaceFolder}/Python_Engine/Python/.venv/Scripts/python.exe", + "console": "integratedTerminal", + "justMyCode": false + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..8a0a76c7 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,35 @@ +{ + // C# (C# Dev Kit) + "dotnet.defaultSolution": "Python_Toolkit.sln", + + // Python: use the toolkit's uv-managed environment (create it with the "Python: sync" task) + "python.defaultInterpreterPath": "${workspaceFolder}/Python_Engine/Python/.venv/Scripts/python.exe", + "python.testing.pytestEnabled": true, + "python.testing.unittestEnabled": false, + "python.testing.cwd": "${workspaceFolder}/Python_Engine/Python", + "python.testing.pytestArgs": ["tests"], + + // Formatting/linting with the shared BHoM ruff standard (Python_Engine/Python/ruff.toml) + "[python]": { + "editor.defaultFormatter": "charliermarsh.ruff", + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.fixAll.ruff": "explicit", + "source.organizeImports.ruff": "explicit" + } + }, + + "files.exclude": { + "**/__pycache__": true, + "**/.pytest_cache": true, + "**/.ruff_cache": true + }, + "search.exclude": { + "**/.venv": true, + "**/bin": true, + "**/obj": true, + "Build": true, + "**/docs/_build": true, + "**/docs/autoapi": true + } +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 00000000..6468ed63 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,95 @@ +{ + // Build/test tasks: run with Ctrl+Shift+B (build) or "Tasks: Run Test Task". + // C# builds use BHoMSkipDeploy=true so nothing is copied into %ProgramData%\BHoM, except "C#: build and deploy". + "version": "2.0.0", + "options": { + "shell": { + "executable": "powershell.exe", + "args": ["-NoProfile", "-Command"] + } + }, + "tasks": [ + { + "label": "C#: build", + "type": "shell", + "command": "dotnet build Python_Toolkit.sln -p:BHoMSkipDeploy=true", + "group": { "kind": "build", "isDefault": true }, + "problemMatcher": "$msCompile" + }, + { + "label": "C#: build and deploy to BHoM", + "detail": "Builds Debug and copies the assemblies and Python code into %ProgramData%\\BHoM, as Visual Studio does.", + "type": "shell", + "command": "dotnet build Python_Toolkit.sln -c Debug", + "group": "build", + "problemMatcher": "$msCompile" + }, + { + "label": "C#: test", + "detail": "Unit tests (isolated from %ProgramData%; excludes the slower end-to-end Integration tests).", + "type": "shell", + "command": "dotnet test .ci/unit_tests/Python_Engine_Test/Python_Engine_Test.csproj --filter \"Category!=Integration\"", + "group": { "kind": "test", "isDefault": true }, + "problemMatcher": "$msCompile" + }, + { + "label": "C#: test (integration)", + "detail": "End-to-end: create the Python_Toolkit environment, run its pytest suite from C#, scaffold and test a downstream toolkit.", + "type": "shell", + "command": "dotnet test .ci/unit_tests/Python_Engine_Test/Python_Engine_Test.csproj --filter \"Category=Integration\" --logger \"console;verbosity=normal\"", + "group": "test", + "problemMatcher": "$msCompile" + }, + { + "label": "Python: sync", + "detail": "Create/update Python_Engine/Python/.venv with all extras and the dev tools.", + "type": "shell", + "command": "uv sync --all-extras", + "options": { "cwd": "${workspaceFolder}/Python_Engine/Python" }, + "problemMatcher": [] + }, + { + "label": "Python: test", + "type": "shell", + "command": "uv run pytest -m \"not slow\"", + "options": { "cwd": "${workspaceFolder}/Python_Engine/Python" }, + "group": "test", + "problemMatcher": [] + }, + { + "label": "Python: test (all, with coverage)", + "type": "shell", + "command": "uv run pytest --cov --cov-report=term-missing", + "options": { "cwd": "${workspaceFolder}/Python_Engine/Python" }, + "group": "test", + "problemMatcher": [] + }, + { + "label": "Python: format and lint", + "type": "shell", + "command": "uv run ruff format .; uv run ruff check --fix .", + "options": { "cwd": "${workspaceFolder}/Python_Engine/Python" }, + "problemMatcher": [] + }, + { + "label": "Python: build docs", + "type": "shell", + "command": "uv run --all-extras --group docs sphinx-build -b html docs docs/_build/html", + "options": { "cwd": "${workspaceFolder}/Python_Engine/Python" }, + "problemMatcher": [] + }, + { + "label": "Python: new toolkit", + "detail": "Scaffold a new BHoM Python toolkit from the standard template.", + "type": "shell", + "command": "uv run bhom-new-toolkit ${input:toolkitName} --output \"${input:toolkitOutput}\" --python ${input:pythonVersion}", + "options": { "cwd": "${workspaceFolder}/Python_Engine/Python" }, + "problemMatcher": [] + } + ], + "inputs": [ + { "id": "toolkitName", "type": "promptString", "description": "Toolkit name (e.g. Wind_Toolkit)" }, + { "id": "toolkitOutput", "type": "promptString", "description": "Folder to create it in (e.g. C:/repos/Wind_Toolkit/Wind_Toolkit_Engine/Python)" }, + { "id": "pythonVersion", "type": "promptString", "description": "Python version", "default": "3.10" } + ] +} diff --git a/Python_Engine/Compute/BasePythonEnvironment.cs b/Python_Engine/Compute/BasePythonEnvironment.cs deleted file mode 100644 index 8ec03656..00000000 --- a/Python_Engine/Compute/BasePythonEnvironment.cs +++ /dev/null @@ -1,86 +0,0 @@ -/* - * This file is part of the Buildings and Habitats object Model (BHoM) - * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. - * - * Each contributor holds copyright over their respective contributions. - * The project versioning (Git) records all such contribution source information. - * - * - * The BHoM is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3.0 of the License, or - * (at your option) any later version. - * - * The BHoM is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this code. If not, see . - */ - -using BH.oM.Base.Attributes; -using BH.oM.Python; -using BH.oM.Python.Enums; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.IO; -using System.Linq; - -namespace BH.Engine.Python -{ - public static partial class Compute - { - [Description("Retrieve or reinstall the base Python Environment for BHoM workflows.")] - [Input("version", "The target version of python to be installed or retrieved.")] - [Input("reload", "Reload the base Python environment rather than recreating it, if it already exists.")] - [Input("run", "Start the installation/retrieval of the BHoM Base Python Environment.")] - [Output("env", "The base Python Environment for all BHoM workflows.")] - public static PythonEnvironment BasePythonEnvironment( - PythonVersion version = PythonVersion.v3_10, - bool reload = true, - bool run = false - ) - { - if (!run) - { - return null; - } - - if (!Directory.Exists(Query.DirectoryEnvironments())) - { - // create PythonEnvironments directory if it doesnt already exist - Directory.CreateDirectory(Query.DirectoryEnvironments()); - } - - // determine whether the base environment already exists - string targetExecutable = Path.Combine(Query.DirectoryBaseEnvironment(version), "python.exe"); - bool exists = File.Exists(targetExecutable); - - if (exists && reload) - { - PythonEnvironment env = new PythonEnvironment() { Name = Query.ToolkitName(), Executable = targetExecutable }; - UpdateBHoMPackages(env); - return env; - } - - if (exists && !reload) - // remove all existing environments and kernels - RemoveEverything(); - - // download and run the installer for the target Python version - string exe = version.DownloadPythonVersion(); - - // install essential packages into base environment - InstallPackages(exe, new List() { "virtualenv", "jupyterlab", "black", "pylint" }); - InstallPackageLocal(exe, Path.Combine(Query.DirectoryCode(), Query.ToolkitName())); - - return new PythonEnvironment() { Name = Query.ToolkitName(), Executable = exe }; - } - } -} - - - diff --git a/Python_Engine/Compute/CreateToolkit.cs b/Python_Engine/Compute/CreateToolkit.cs new file mode 100644 index 00000000..5a7e2ed8 --- /dev/null +++ b/Python_Engine/Compute/CreateToolkit.cs @@ -0,0 +1,114 @@ +/* + * This file is part of the Buildings and Habitats object Model (BHoM) + * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. + * + * Each contributor holds copyright over their respective contributions. + * The project versioning (Git) records all such contribution source information. + * + * + * The BHoM is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3.0 of the License, or + * (at your option) any later version. + * + * The BHoM is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this code. If not, see . + */ + +using BH.oM.Base; +using BH.oM.Base.Attributes; +using BH.oM.Python; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; + +namespace BH.Engine.Python +{ + public static partial class Compute + { + [Description("Create a new BHoM Python toolkit (pyproject.toml, source package, tests and documentation) from the standard template. " + + "The new toolkit depends on Python_Toolkit (and any other given toolkits) from the BHoM Python environments directory, extends the shared ruff configuration, and is ready for `uv sync`. " + + "This runs python_toolkit.scaffold using the Python_Toolkit environment, which must already be installed (see InstallPythonToolkitVenv).")] + [Input("name", "The toolkit name, e.g. \"Wind_Toolkit\". The Python package will be its lower-case form, e.g. \"wind_toolkit\".")] + [Input("targetDirectory", "The (new or empty) folder to create the toolkit in, typically /_Engine/Python.")] + [Input("pythonVersion", "The major.minor Python version the toolkit uses, e.g. \"3.11\" (3.10 or later).")] + [Input("dependencies", "Other BHoM Python toolkits this toolkit depends on, by name (e.g. \"LadybugTools_Toolkit\"). Python_Toolkit is always included.")] + [Input("extras", "Optional Python_Toolkit extras to depend on: \"plot\", \"ui\" and/or \"clr\".")] + [Input("run", "Set to True to create the toolkit.")] + [MultiOutput(0, "success", "True if the toolkit was created.")] + [MultiOutput(1, "output", "The scaffold output, including the next steps to wire the toolkit into BHoM.")] + public static Output CreateToolkit(string name, string targetDirectory, string pythonVersion = "3.10", List dependencies = null, List extras = null, bool run = false) + { + if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(targetDirectory)) + { + Base.Compute.RecordError("A toolkit name and target directory are required."); + return null; + } + + string arguments = $"-m python_toolkit.scaffold \"{name}\" --output \"{Path.GetFullPath(targetDirectory)}\" --python \"{pythonVersion}\" --extensions-dir \"{Query.DirectoryEnvironments()}\""; + foreach (string dependency in (dependencies ?? new List()).Where(d => !string.IsNullOrWhiteSpace(d))) + arguments += $" --depends-on \"{dependency}\""; + foreach (string extra in (extras ?? new List()).Where(e => !string.IsNullOrWhiteSpace(e))) + arguments += $" --extras \"{extra}\""; + + if (!run) + { + Base.Compute.RecordNote($"The following will be executed using the {Query.ToolkitName()} environment: python {arguments}"); + return null; + } + + if (!Query.VirtualEnvironmentExists(Query.ToolkitName())) + { + Base.Compute.RecordError($"The {Query.ToolkitName()} environment is required to create toolkits. Install it first using InstallPythonToolkitVenv."); + return null; + } + + PythonEnvironment venv = Query.VirtualEnvironment(Query.ToolkitName()); + Output result = RunCommandStdout($"\"{venv.Executable}\" {arguments}"); + + return new Output + { + Item1 = result.Item3 == 0, + Item2 = result.Item3 == 0 ? result.Item1 : result.Item2, + }; + } + + /***************************************************/ + + [Description("Build a toolkit's HTML documentation with Sphinx, from the docstrings in its source code. Output is written to /docs/_build/html.")] + [Input("toolkitDirectory", "The directory containing the toolkit's pyproject.toml and docs/conf.py.")] + [Input("run", "Set to True to build the documentation.")] + [Output("index", "The path to the built documentation's index.html, or null on failure.")] + public static string BuildDocumentation(string toolkitDirectory, bool run = false) + { + if (string.IsNullOrWhiteSpace(toolkitDirectory) || !File.Exists(Path.Combine(toolkitDirectory, "docs", "conf.py"))) + { + Base.Compute.RecordError($"No Sphinx configuration (docs/conf.py) was found in {toolkitDirectory}."); + return null; + } + + toolkitDirectory = Path.GetFullPath(toolkitDirectory); + string output = Path.Combine(toolkitDirectory, "docs", "_build", "html"); + string arguments = $"run --all-extras --group docs sphinx-build -b html docs \"{output}\""; + + if (!run) + { + Base.Compute.RecordNote($"The following will be executed from \"{toolkitDirectory}\": uv {arguments}"); + return null; + } + + InstallUV(true); + if (RunUV(arguments, startDirectory: toolkitDirectory, timeoutMinutes: 30).Item3 != 0) + return null; + + string index = Path.Combine(output, "index.html"); + return File.Exists(index) ? index : null; + } + } +} diff --git a/Python_Engine/Compute/Download.cs b/Python_Engine/Compute/Download.cs deleted file mode 100644 index 054f03aa..00000000 --- a/Python_Engine/Compute/Download.cs +++ /dev/null @@ -1,152 +0,0 @@ -/* - * This file is part of the Buildings and Habitats object Model (BHoM) - * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. - * - * Each contributor holds copyright over their respective contributions. - * The project versioning (Git) records all such contribution source information. - * - * - * The BHoM is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3.0 of the License, or - * (at your option) any later version. - * - * The BHoM is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this code. If not, see . - */ - -using BH.oM.Base.Attributes; -using BH.oM.Python.Enums; -using System; -using System.ComponentModel; -using System.Diagnostics; -using System.IO; -using System.Reflection; -using System.Xml.Linq; - -namespace BH.Engine.Python -{ - public static partial class Compute - { - [Description("Download a file from a Url.")] - [Input("fileUrl", "The file to download.")] - [Input("targetDirectory", "The destination directory to download the file to.")] - [Input("filename", "An optional input to rename the downloaded file.")] - [Input("overwrite", "An optional input to overwrite the file if it already exists, otherwise if it does then return the existing file.")] - [Output("filePath", "The path to the downloaded file.")] - public static string DownloadFile( - string fileUrl, - string targetDirectory, - string filename = null, - bool overwrite = true - ) - { - if (string.IsNullOrWhiteSpace(fileUrl)) - { - BH.Engine.Base.Compute.RecordError($"The fileUrl cannot be null or empty."); - return null; - } - - - if (string.IsNullOrWhiteSpace(targetDirectory)) - { - BH.Engine.Base.Compute.RecordError($"The targetDirectory cannot be null or empty."); - return null; - } - - - if (!Directory.Exists(targetDirectory)) - { - BH.Engine.Base.Compute.RecordError($"The targetDirectory \"{targetDirectory}\" does not exist."); - return null; - } - - - if (string.IsNullOrWhiteSpace(filename)) - filename = Path.GetFileName(fileUrl); - - string filePath = Path.Combine(targetDirectory, filename); - - if (File.Exists(filePath)) - { - if (!overwrite) - return filePath; - File.Delete(filePath); - } - - using (var client = new System.Net.WebClient()) - { - client.DownloadFile(fileUrl, filePath); - } - - return filePath; - } - - /******************************************************/ - - [Description("Download and install a specified version of python, and return the executable for it.")] - [Input("version", "The version of python to download.")] - [Output("pythonExecutable", "The executable (python.exe) for the python version that was installed.")] - public static string DownloadPythonVersion(this PythonVersion version) - { - string url = version.EmbeddableURL(); - - string basePath = Path.Combine(Query.DirectoryBaseEnvironment(version)); - - if (File.Exists(Path.Combine(basePath, "python.exe"))) - return Path.Combine(basePath, "python.exe"); - - if (!Directory.Exists(basePath)) - Directory.CreateDirectory(basePath); - else - { - Directory.Delete(basePath, true); //if there are any files here already for some reason, remove them. - Directory.CreateDirectory(basePath); - } - - string installerFile = DownloadFile(url, basePath, "installer.exe"); - - using (Process install = new Process() - { - StartInfo = new ProcessStartInfo() - { - FileName = installerFile, - Arguments = $"/passive InstallAllUsers=0 InstallLauncherAllUsers=0 Include_launcher=0 Shortcuts=0 AssociateFiles=0 Include_tools=0 Include_test=0 TargetDir={Modify.AddQuotesIfRequired(basePath)}", - RedirectStandardError = true, - UseShellExecute = false, - } - }) - { - install.StartInfo.Environment["PYTHONHOME"] = ""; - install.Start(); - string stderr = install.StandardError.ReadToEnd(); - install.WaitForExit(); - if (install.ExitCode != 0) - { - BH.Engine.Base.Compute.RecordError($"Error installing python: {stderr}"); - return null; - } - } - - string pythonExePath = Path.Combine(basePath, "python.exe"); - - // It is possible for the installer to exit with ExitCode==0 without installing Python in the requested location. This can happen if the same version of Python appears to be installed elsewhere on the system. It can also happen if there was a 'dodgy' uninstall of a previous version. We've been unable to figure out where the installer is actually looking for existing installs. To fix dodgy uninstalls, run the installer again for the target version of Python (download links within EmbeddableURL.cs) and run a combination of 'repair' and 'uninstall' until it's gone. Installing the py launcher (via 'modify' in the installer) before attempting to uninstall could also help. - - if (!File.Exists(pythonExePath)) - { - BH.Engine.Base.Compute.RecordError($"The Python installer appears to have completed successfully, but \n{pythonExePath} does not exist. \nThis usually means that Python {version} already exists on your machine, but in a different location. \nThis toolkit is therefore unable to run any Python commands right now. \nTry uninstalling Python {version} from your system before running this BHoM method again."); - return null; - } - - return pythonExePath; - } - } -} - - - diff --git a/Python_Engine/Compute/Install.cs b/Python_Engine/Compute/Install.cs index 7b7f0c91..cd536b49 100644 --- a/Python_Engine/Compute/Install.cs +++ b/Python_Engine/Compute/Install.cs @@ -20,165 +20,223 @@ * along with this code. If not, see . */ +using BH.oM.Base; using BH.oM.Base.Attributes; using BH.oM.Python; using System; using System.Collections.Generic; using System.ComponentModel; -using System.Diagnostics; using System.IO; -using System.Xml.Linq; +using System.Linq; namespace BH.Engine.Python { public static partial class Compute { - [Description("Install a list of packages to a given Python executable.")] - [Input("executable", "The Python executable to install the packages to.")] - [Input("packages", "The packages to install.")] - public static void InstallPackages( - string executable, - List packages - ) + [Description("Install the pinned version of UV (see Query.UVVersion) into the BHoM tools directory. UV installations elsewhere (e.g. on PATH) are never used, and the process PATH is not modified. If UV is already present at the pinned version, nothing happens.")] + [Input("run", "Set to True to install UV.")] + public static void InstallUV(bool run = false) { - if (!File.Exists(executable)) - { - BH.Engine.Base.Compute.RecordError("Python executable not found at " + executable); - } + string uvExecutable = Query.UVExecutable(); + string version = Query.UVVersion(); - if (packages.Count == 0) + if (!run) { - BH.Engine.Base.Compute.RecordError("No packages to install."); + Base.Compute.RecordNote($"UV {version} will be installed to {uvExecutable} if it is not already present."); + return; } - string packagesString = string.Join(" ", packages); - System.Diagnostics.Process process = new System.Diagnostics.Process() - { - StartInfo = new System.Diagnostics.ProcessStartInfo() - { - FileName = executable, - Arguments = $"-m pip install --no-warn-script-location {packagesString}", - UseShellExecute = false, - RedirectStandardError = true - } - }; - process.StartInfo.Environment["PYTHONHOME"] = ""; - using (Process p = Process.Start(process.StartInfo)) - { - string standardError = p.StandardError.ReadToEnd(); - p.WaitForExit(); - if (p.ExitCode != 0) - BH.Engine.Base.Compute.RecordError($"Error installing packages [{packagesString}].\n{standardError}"); - } + if (File.Exists(uvExecutable) && InstalledUVVersion(uvExecutable) == version) + return; + + string toolsDirectory = Query.DirectoryTools(); + string command = "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \"$ErrorActionPreference = 'Stop'; " + + $"$env:UV_INSTALL_DIR = '{toolsDirectory.Replace("'", "''")}'; $env:UV_NO_MODIFY_PATH = '1'; " + + $"irm https://astral.sh/uv/{version}/install.ps1 | iex\""; + if (RunCommand(command, true, null, 10, null).Item3 != 0) + return; + + string installed = File.Exists(uvExecutable) ? InstalledUVVersion(uvExecutable) : null; + if (installed != version) + Base.Compute.RecordError($"UV installation did not produce UV {version} at {uvExecutable} (found: {installed ?? "nothing"})."); } - [Description("Install a list of packages to a given Python executable.")] - [Input("environment", "The Python environment to install the packages to.")] - [Input("packages", "The packages to install.")] - public static void InstallPackages( - this PythonEnvironment environment, - List packages - ) + /***************************************************/ + + private static string InstalledUVVersion(string uvExecutable) { - InstallPackages(environment.Executable, packages); + // output takes the form "uv 0.13.10 (e3e7c1eac 2026-11-24 x86_64-pc-windows-msvc)" + Output result = RunCommand($"\"{uvExecutable}\" --version", true, null, 1, null); + if (result.Item3 != 0) + return null; + + string[] parts = result.Item1.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + return parts.Length > 1 ? parts[1] : null; } - [Description("Install packages from a requirements.txt file to a given Python executable.")] - [Input("executable", "The Python executable to install the packages to.")] - [Input("requirements", "The requirements.txt file to install.")] - public static void InstallRequirements( - string executable, - string requirements - ) + /***************************************************/ + + [Description("Register a Jupyter kernel for a given venv unless that kernel already exists. If ipykernel is missing it is installed into the environment without modifying any project pyproject.toml.")] + [Input("venv", "The Python environment to register as a kernel.")] + public static void InstallJupyterKernel(this PythonEnvironment venv) { - if (!File.Exists(executable)) + if (venv == null || !File.Exists(venv.Executable)) { - BH.Engine.Base.Compute.RecordError($"Python executable not found at {executable}"); + Base.Compute.RecordError("A valid Python environment is required to install a Jupyter kernel."); + return; } - if (!File.Exists(requirements)) + if (JupyterKernelExists(venv, venv.Name, true) != false) + return; + + // uv pip install (rather than uv add) never modifies the project's pyproject.toml + if (RunUV($"pip install --python \"{venv.Executable}\" ipykernel").Item3 != 0) + return; + + string directory = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(venv.Executable))); + string cmd = $"\"{venv.Executable}\" -m ipykernel install --user --name \"{venv.Name}\" --display-name \"{venv.Name}\""; + RunCommandStdout(command: cmd, startDirectory: directory); + } + + /***************************************************/ + + [PreviousVersion("9.3", "BH.Engine.Python.Compute.InstallPackages(BH.oM.Python.PythonEnvironment, System.Collections.Generic.List)")] + [Description("Install a list of packages to a given Python executable. UV retains satisfied versions and registers project dependencies when applicable.")] + [Input("venv", "The Python environment to install the packages to.")] + [Input("packages", "The packages to install.")] + [Input("run", "Run this method.")] + public static void InstallPackages( + this PythonEnvironment venv, + List packages, + bool run = false + ) + { + if (venv == null || packages == null || packages.Count == 0) { - BH.Engine.Base.Compute.RecordError($"requirements.txt not found at {requirements}"); + Base.Compute.RecordError("A Python environment and at least one package are required."); + return; } - - System.Diagnostics.Process process = new System.Diagnostics.Process() + string directory = Query.VirtualEnvironmentDirectory(venv.Name); + if (directory == null) + return; + bool isProject = File.Exists(Path.Combine(directory, "pyproject.toml")); + + string uvCommand = isProject ? "add" : "pip install"; + string arguments = $"{uvCommand} --python \"{venv.Executable}\" {string.Join(" ", packages.Select(package => $"\"{package}\""))}"; + string cmd = $"\"{Query.UVExecutable()}\" {arguments}"; + + if (run) { - StartInfo = new System.Diagnostics.ProcessStartInfo() - { - FileName = executable, - Arguments = $"-m pip install --no-warn-script-location -r {Modify.AddQuotesIfRequired(requirements)}", - UseShellExecute = false, - RedirectStandardError = true, - } - }; - process.StartInfo.Environment["PYTHONHOME"] = ""; - using (Process p = Process.Start(process.StartInfo)) + RunUV(arguments, startDirectory: directory); + } + else { - string standardError = p.StandardError.ReadToEnd(); - p.WaitForExit(); - if (p.ExitCode != 0) - BH.Engine.Base.Compute.RecordError($"Error installing packages from {requirements}.\n{standardError}"); + Base.Compute.RecordNote($"The following command will be executed from \"{directory}\": {cmd}"); } } - [Description("Install packages from a requirements.txt file to a given Python environment.")] - [Input("environment", "The Python environment to install the packages to.")] - [Input("requirements", "The requirements.txt file to install.")] - public static void InstallRequirements( - this PythonEnvironment environment, - string requirements - ) - { - InstallRequirements(environment.Executable, requirements); - } - - - [Description("Install a local Python package to a given Python executable.")] - [Input("executable", "The Python executable to install the package to.")] + [PreviousVersion("9.3", "BH.Engine.Python.Compute.InstallPackageLocal(BH.oM.Python.PythonEnvironment, System.String)")] + [Description("Install a local editable Python package. An unchanged installation from the same directory is retained; project dependencies are still registered.")] + [Input("venv", "The Python environment to install the packages to.")] [Input("packageDirectory", "The package to install.")] + [Input("run", "Run this method.")] public static void InstallPackageLocal( - string executable, - string packageDirectory + this PythonEnvironment venv, + string packageDirectory, + bool run = false ) { - if (!File.Exists(executable)) + if (!Directory.Exists(packageDirectory)) { - BH.Engine.Base.Compute.RecordError("Python executable not found at " + executable); + Base.Compute.RecordError($"{packageDirectory} not found."); + return; } - - System.Diagnostics.Process process = new System.Diagnostics.Process() + + if (venv == null) + { + Base.Compute.RecordError("A Python environment is required."); + return; + } + + packageDirectory = Path.GetFullPath(packageDirectory); + string directory = Query.VirtualEnvironmentDirectory(venv.Name); + if (directory == null) + return; + bool isProject = File.Exists(Path.Combine(directory, "pyproject.toml")); + + string uvCommand = isProject ? "add" : "pip install"; + string arguments = $"{uvCommand} --python \"{venv.Executable}\" --editable \"{packageDirectory}\""; + string cmd = $"\"{Query.UVExecutable()}\" {arguments}"; + + if (run) { - StartInfo = new System.Diagnostics.ProcessStartInfo() + if (!isProject) { - FileName = executable, - Arguments = $"-m pip install --no-warn-script-location -e {Modify.AddQuotesIfRequired(packageDirectory)}", - UseShellExecute = false, - RedirectStandardError = true, + // Explicit local paths are otherwise always reinstalled by UV. + string script = "import importlib.metadata as m,json,pathlib,sys; " + + "p=pathlib.Path(sys.argv[1]).resolve(); " + + "sources=[p/f for f in ('pyproject.toml','setup.py','setup.cfg') if (p/f).exists()]; " + + "print(any((lambda u: u.get('dir_info',{}).get('editable',False) and " + + "u.get('url','').rstrip('/').lower()==p.as_uri().rstrip('/').lower() and " + + "all(f.stat().st_mtime<=pathlib.Path(d.locate_file(x)).stat().st_mtime for f in sources))" + + "(json.loads(d.read_text('direct_url.json') or '{}')) " + + "for d in m.distributions() for x in (d.files or []) if str(x).endswith('.dist-info/METADATA')))"; + var installed = RunCommandStdout( + $"\"{venv.Executable}\" -c \"{script}\" \"{packageDirectory}\"", startDirectory: directory); + if (installed.Item3 != 0) + return; + if (installed.Item1 == "True") + return; + if (installed.Item1 != "False") + { + Base.Compute.RecordError($"Could not check the local package installation in {venv.Name}."); + return; + } } - }; - process.StartInfo.Environment["PYTHONHOME"] = ""; - using (Process p = Process.Start(process.StartInfo)) + RunUV(arguments, startDirectory: directory); + } + else { - string standardError = p.StandardError.ReadToEnd(); - p.WaitForExit(); - if (p.ExitCode != 0) - BH.Engine.Base.Compute.RecordError($"Error installing package from \"{packageDirectory}\".\n{standardError}"); + Base.Compute.RecordNote($"The following command will be executed from \"{directory}\": {cmd}"); } } - [Description("Install a local Python package to a given Python environment.")] - [Input("environment", "The Python environment to install the packages to.")] - [Input("packageDirectory", "The package to install.")] - public static void InstallPackageLocal( - this PythonEnvironment environment, - string packageDirectory + private static bool? JupyterKernelExists(PythonEnvironment venv, string name, bool requireMatchingExecutable = false) + { + string script = "import importlib.util,pathlib,sys; " + + "available=importlib.util.find_spec('jupyter_client') is not None; " + + "manager=__import__('jupyter_client.kernelspec',fromlist=['KernelSpecManager']).KernelSpecManager() if available else None; " + + "exists=available and sys.argv[1].lower() in manager.find_kernel_specs(); " + + "print(exists and (sys.argv[2]=='False' or " + + "pathlib.Path(manager.get_kernel_spec(sys.argv[1].lower()).argv[0]).resolve()==pathlib.Path(sys.executable).resolve()))"; + var result = RunCommandStdout($"\"{venv.Executable}\" -c \"{script}\" \"{name}\" {requireMatchingExecutable}"); + if (result.Item3 != 0) + return null; + if (result.Item1 == "True") + return true; + if (result.Item1 == "False") + return false; + + Base.Compute.RecordError($"Could not check whether Jupyter kernel {name} exists."); + return null; + } + + [Description("Install the Python_Toolkit Python venv.")] + [Input("run", "Run this method.")] + [Input("reload", "Reload the virtual environment rather than recreating it, if it already exists.")] + [Output("venv", "The resultant venv.")] + public static PythonEnvironment InstallPythonToolkitVenv( + bool run = false, + bool reload = true ) { - InstallPackageLocal(environment.Executable, packageDirectory); + string tomlFile = Path.Combine(Query.DirectoryEnvironments(), Query.ToolkitName(), "pyproject.toml"); + if (run) + { + return VirtualEnvironment(tomlFile: tomlFile, reload: reload); + } + return null; } } } - - - diff --git a/Python_Engine/Compute/Remove.cs b/Python_Engine/Compute/Remove.cs index 46adb528..33feec6d 100644 --- a/Python_Engine/Compute/Remove.cs +++ b/Python_Engine/Compute/Remove.cs @@ -21,123 +21,132 @@ */ using BH.oM.Base.Attributes; -using BH.oM.Python.Enums; +using BH.oM.Python; using System; using System.Collections.Generic; using System.ComponentModel; -using System.Diagnostics; using System.IO; +using System.Linq; namespace BH.Engine.Python { public static partial class Compute { - - [Description("Remove a named BHoM Python kernel.")] - [Input("kernelName", "The name of the kernel to remove.")] - public static void RemoveKernel(string kernelName) + [Description("Remove the named Python virtual environment. Missing environments produce a warning instead of an error. This will retain any code within that environment directory.")] + [Input("name", "The name of the Python virtual environment to remove.")] + [Input("run", "Run this method.")] + public static void RemoveVirtualEnvironment(string name, bool run = false) { - string kernelPath = Path.Combine(Query.DirectoryKernels(), kernelName.ToLower()); - if (Directory.Exists(kernelPath)) - Directory.Delete(kernelPath, true); - } + if (!Query.VirtualEnvironmentExists(name)) + { + Base.Compute.RecordWarning($"No Python environment named {name} exists."); + return; + } - [Description("Remove all BHoM Python kernels.")] - public static void RemoveAllKernels() - { - DirectoryInfo di = new DirectoryInfo(Query.DirectoryKernels()); - foreach (FileInfo file in di.EnumerateFiles()) + string venvDirectory = Path.Combine(Query.DirectoryEnvironments(), name, ".venv"); + + if (run) { - file.Delete(); + RemoveJupyterKernel(name, run); + try + { + Directory.Delete(venvDirectory, true); + } + catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) + { + Base.Compute.RecordError($"Failed to remove virtual environment directory {venvDirectory}: {ex.Message}"); + } } - foreach (DirectoryInfo dir in di.EnumerateDirectories()) + else { - dir.Delete(true); + Base.Compute.RecordNote($"The virtual environment at {venvDirectory} (and its Jupyter kernel) will be removed."); } } - [Description("Remove the named BHoM Python virtual environment.")] - [Input("envName", "The name of the BHoM Python virtual environment to remove.")] - public static void RemoveVirtualEnvironment(string envName) + [Description("Remove the named Jupyter kernel. Missing environments or kernels produce a warning instead of an error.")] + [Input("name", "The name of the Jupyer kernel to remove.")] + [Input("run", "Run this method.")] + public static void RemoveJupyterKernel(string name, bool run = false) { - string envPath = Path.Combine(Query.DirectoryEnvironments(), envName); - if (Directory.Exists(envPath)) - Directory.Delete(envPath, true); + if (!Query.VirtualEnvironmentExists(name)) + { + Base.Compute.RecordWarning($"No Python environment named {name} exists."); + return; + } - RemoveKernel(envName); - } + PythonEnvironment venv = Query.VirtualEnvironment(name); + bool? exists = JupyterKernelExists(venv, name); + if (exists != true) + { + if (exists == false) + Base.Compute.RecordWarning($"No Jupyter kernel named {name} exists."); + return; + } - [Description("Remove all BHoM Python virtual environments.")] - public static void RemoveAllVirtualEnvironments() - { - DirectoryInfo di = new DirectoryInfo(Query.DirectoryEnvironments()); - foreach (DirectoryInfo dir in di.EnumerateDirectories()) + string cmd = $"\"{venv.Executable}\" -m jupyter kernelspec uninstall \"{name.ToLowerInvariant()}\" -f"; + + if (run) { - if (dir.Name != Query.ToolkitName()) - { - RemoveVirtualEnvironment(dir.Name); - } - + RunCommandStdout(command: cmd, hideWindows: true); + } + else + { + Base.Compute.RecordNote($"The following command will be executed: {cmd}"); } } - [Description("Remove the base install for the python version specified.")] - [Input("version", "The base python version to remove.")] - public static void RemoveBaseVersion(PythonVersion version = PythonVersion.v3_10) + [Description("Remove UV from the BHoM tools directory. Missing installations produce a warning; installations elsewhere are not removed.")] + [Input("run", "Run this method.")] + public static void RemoveUV(bool run = false) { - string basePath = Path.Combine(Query.DirectoryEnvironments(), Query.ToolkitName(), version.ToString()); - string baseInstaller = Path.Combine(basePath, "installer.exe"); + string toolsDirectory = Query.DirectoryTools(); - // If the installer does not exist and the folder does - assume a bad/invalid install and just delete the entire folder. - if (!File.Exists(baseInstaller) && Directory.Exists(basePath)) + if (!File.Exists(Query.UVExecutable())) { - Directory.Delete(basePath, true); + Base.Compute.RecordWarning($"UV is not currently installed in {toolsDirectory}."); return; } - else if (!Directory.Exists(basePath)) - // If the base path doesn't exist there is nothing to remove. - return; - using (Process uninstall = new Process() + if (run) { - StartInfo = new ProcessStartInfo() + try { - FileName = baseInstaller, - Arguments = "/uninstall /passive", - RedirectStandardError = true, - UseShellExecute = false, + Directory.Delete(toolsDirectory, true); } - }) - { - uninstall.StartInfo.Environment["PYTHONHOME"] = ""; - uninstall.Start(); - string stderr = uninstall.StandardError.ReadToEnd(); - uninstall.WaitForExit(); - if (uninstall.ExitCode != 0) + catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { - BH.Engine.Base.Compute.RecordError($"Error uninstalling python: {stderr}"); - return; + Base.Compute.RecordError($"Failed to remove UV from {toolsDirectory}: {ex.Message}"); } } - - // Finally remove base folder as the installer may have missed something. - Directory.Delete(basePath, true); + else + { + Base.Compute.RecordNote($"UV and everything it manages (Python interpreters, package cache and tools) will be removed from {toolsDirectory}. Existing virtual environments depend on these interpreters and will need recreating."); + } } - [Description("Completely remove all BHoM-related Python environments and kernels.")] - public static void RemoveEverything() + [PreviousVersion("9.3", "BH.Engine.Python.Compute.RemoveEverything()")] + [Description("Completely remove all BHoM-related Python environments, kernels and tools (including UV and the Python interpreters it manages). Toolkit source code is retained.")] + [Input("run", "Run this method.")] + public static void RemoveEverything(bool run = false) { - RemoveAllVirtualEnvironments(); - - //remove all python versions installed in base directory. - foreach (PythonVersion e in Enum.GetValues(typeof(PythonVersion))) + string toolsDirectory = Query.DirectoryTools(); + List names = Directory.GetDirectories(Query.DirectoryEnvironments()) + .Where(directory => !string.Equals(Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar), toolsDirectory.TrimEnd(Path.DirectorySeparatorChar), StringComparison.OrdinalIgnoreCase)) + .Select(directory => Path.GetFileName(directory)) + .Where(name => Query.VirtualEnvironmentExists(name)) + .ToList(); + + if (!run) { - if (e != PythonVersion.Undefined) - RemoveBaseVersion(e); + Base.Compute.RecordNote($"The following environments will be removed: {string.Join(", ", names)}. UV and its managed tools will be removed from {toolsDirectory}."); + return; } + + foreach (string name in names) + RemoveVirtualEnvironment(name, run: true); + + if (File.Exists(Query.UVExecutable())) + RemoveUV(run: true); } } } - - - diff --git a/Python_Engine/Compute/RequirementsTxt.cs b/Python_Engine/Compute/RequirementsTxt.cs deleted file mode 100644 index 7084732d..00000000 --- a/Python_Engine/Compute/RequirementsTxt.cs +++ /dev/null @@ -1,91 +0,0 @@ -/* - * This file is part of the Buildings and Habitats object Model (BHoM) - * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. - * - * Each contributor holds copyright over their respective contributions. - * The project versioning (Git) records all such contribution source information. - * - * - * The BHoM is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3.0 of the License, or - * (at your option) any later version. - * - * The BHoM is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this code. If not, see . - */ - -using BH.oM.Base.Attributes; -using System; -using System.ComponentModel; -using System.Diagnostics; -using System.IO; - -namespace BH.Engine.Python -{ - public static partial class Compute - { - [Description("Create a requirements.txt file from an existing Python executable.")] - [Input("executable", "The path to the Python executable to create the requirements.txt file from.")] - [Input("targetPath", "The path to the requirements.txt file to create. If not specified, the file will be created in the same directory as the executable.")] - [Output("requirementsTxt", "The path to the requirements.txt file.")] - public static string RequirementsTxt( - string executable, - string targetPath = null - ) - { - if (!File.Exists(executable)) - { - BH.Engine.Base.Compute.RecordError($"The executable '{executable}' does not exist."); - return null; - } - - if (string.IsNullOrEmpty(targetPath)) - { - targetPath = Path.Combine(Path.GetDirectoryName(executable), "requirements.txt"); - } - else - { - if (!Directory.Exists(Path.GetDirectoryName(targetPath))) - { - BH.Engine.Base.Compute.RecordError($"The executable '{executable}' does not exist."); - return null; - } - } - - System.Diagnostics.Process process = new System.Diagnostics.Process() - { - StartInfo = new System.Diagnostics.ProcessStartInfo() - { - FileName = executable, - Arguments = $"-m pip freeze", - UseShellExecute = false, - RedirectStandardError = true, - RedirectStandardOutput = true - } - }; - - process.StartInfo.Environment["PYTHONHOME"] = ""; - using (Process p = Process.Start(process.StartInfo)) - { - StreamWriter sr = new StreamWriter(targetPath); - sr.Write(p.StandardOutput.ReadToEnd()); - string standardError = p.StandardError.ReadToEnd(); - p.WaitForExit(); - if (p.ExitCode != 0) - BH.Engine.Base.Compute.RecordError($"Error creating requirements.txt from \"{executable}\".\n{standardError}"); - sr.Close(); - } - - return targetPath; - } - } -} - - - diff --git a/Python_Engine/Compute/Run.cs b/Python_Engine/Compute/Run.cs index 7340e693..ceecc99b 100644 --- a/Python_Engine/Compute/Run.cs +++ b/Python_Engine/Compute/Run.cs @@ -20,10 +20,9 @@ * along with this code. If not, see . */ -using BH.oM.Base; using BH.oM.Base.Attributes; -using BH.oM.Python; -using BH.oM.Python.Enums; +using BH.oM.Base; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; @@ -35,51 +34,143 @@ namespace BH.Engine.Python { public static partial class Compute { - [Description("Run a command via CMD and return stdout.")] + [Description("Run a command via CMD and return both output streams and the exit code.")] [Input("command", "The command to be run.")] [Input("hideWindows", "Set to True to hide cmd windows.")] [Input("startDirectory", "The directory in which the command should be run.")] [Input("timeoutMinutes", "A number of minutes beyond which this command will timeout.")] - [Output("stdout", "The StandardOutput from the command that was run. If the process failed, then StandardError will be returned here instead.")] - public static string RunCommandStdout(string command, bool hideWindows = true, string startDirectory = null, double timeoutMinutes = 5) + [MultiOutput(0, "stdout", "The command's standard output, including on failure.")] + [MultiOutput(1, "stderr", "The command's standard error, including on success.")] + [MultiOutput(2, "exitCode", "The process exit code. Zero indicates success; -1 indicates a timeout.")] + public static Output RunCommandStdout( + string command, + bool hideWindows = true, + string startDirectory = null, + double timeoutMinutes = 5 + ) { - System.Diagnostics.Process process = new System.Diagnostics.Process(); + return RunCommand(command, hideWindows, startDirectory, timeoutMinutes, null); + } - string commandMode = "/K"; - if (hideWindows) + /***************************************************/ + /**** Private methods ****/ + /***************************************************/ + + // Run a command using the BHoM-managed UV executable and its environment variables. + private static Output RunUV(string arguments, string startDirectory = null, double timeoutMinutes = 15) + { + string command = $"\"{Query.UVExecutable()}\" {arguments}"; + return RunCommand(command, true, startDirectory, timeoutMinutes, Query.UVEnvironmentVariables()); + } + + /***************************************************/ + + private static Output RunCommand( + string command, + bool hideWindows, + string startDirectory, + double timeoutMinutes, + Dictionary environment + ) + { + if (string.IsNullOrWhiteSpace(startDirectory)) { - process.StartInfo.CreateNoWindow = true; - process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; - commandMode = "/C"; + startDirectory = Environment.CurrentDirectory; } - process.StartInfo.Environment["PYTHONHOME"] = ""; - process.StartInfo.FileName = "cmd.exe"; - process.StartInfo.RedirectStandardOutput = true; - process.StartInfo.RedirectStandardError = true; - process.StartInfo.UseShellExecute = false; - process.StartInfo.Arguments = $"{commandMode} {command}"; - process.Start(); - - // To avoid deadlocks, always read the output stream first and then wait. - string stdout = process.StandardOutput.ReadToEnd(); - string stderr = process.StandardError.ReadToEnd(); - - int millisecondsToWait = (int)timeoutMinutes * 60 * 1000; - process.WaitForExit(millisecondsToWait); - - if (process.ExitCode != 0) + + if (!Directory.Exists(startDirectory)) { - return stderr.Trim(); + throw new DirectoryNotFoundException( + string.Format("Working directory does not exist: '{0}'", startDirectory)); } - return stdout.Trim(); + using (Process process = new Process()) + { + process.StartInfo.FileName = "cmd.exe"; + process.StartInfo.Arguments = string.Format("/C \"{0}\"", command); + process.StartInfo.WorkingDirectory = startDirectory; + + process.StartInfo.UseShellExecute = false; + process.StartInfo.RedirectStandardOutput = true; + process.StartInfo.RedirectStandardError = true; + process.StartInfo.CreateNoWindow = hideWindows; + process.StartInfo.WindowStyle = hideWindows ? ProcessWindowStyle.Hidden : ProcessWindowStyle.Normal; + + // Avoid environment-variable interference. + process.StartInfo.EnvironmentVariables["PYTHONHOME"] = string.Empty; + process.StartInfo.EnvironmentVariables["PYTHONPATH"] = string.Empty; + if (environment != null) + { + foreach (KeyValuePair variable in environment) + process.StartInfo.EnvironmentVariables[variable.Key] = variable.Value; + } + + process.Start(); + + StreamReader stdoutReader = process.StandardOutput; + StreamReader stderrReader = process.StandardError; + + // Start reads without inheriting the host's UI synchronization context. + Task outputTask = Task.Run(async () => + { + Task stdoutTask = stdoutReader.ReadToEndAsync(); + Task stderrTask = stderrReader.ReadToEndAsync(); + + return await Task.WhenAll(stdoutTask, stderrTask).ConfigureAwait(false); + }); + + int timeoutMs = checked((int)(timeoutMinutes * 60 * 1000)); + + bool timedOut = !process.WaitForExit(timeoutMs); + if (timedOut) + { + // Kill descendants too, so inherited pipe handles cannot keep the reads open. + using (Process terminator = Process.Start(new ProcessStartInfo + { + FileName = "taskkill.exe", + Arguments = $"/PID {process.Id} /T /F", + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + })) + { + Task killStdout = terminator.StandardOutput.ReadToEndAsync(); + Task killStderr = terminator.StandardError.ReadToEndAsync(); + terminator.WaitForExit(); + Task.WaitAll(killStdout, killStderr); + if (terminator.ExitCode != 0 && !process.HasExited) + throw new InvalidOperationException($"Could not terminate timed-out command: {killStderr.GetAwaiter().GetResult()}"); + } + process.WaitForExit(); + BH.Engine.Base.Compute.RecordError(new TimeoutException(), $"Command exceeded timeout of {timeoutMinutes} minutes.\nCommand: {command}"); + } + + // Ensure async reads have completed. + string[] results = outputTask.GetAwaiter().GetResult(); + + string stdout = results[0].Trim(); + string stderr = results[1].Trim(); + + int exitCode = timedOut ? -1 : process.ExitCode; + + if (!timedOut && exitCode != 0) + { + string message = $"Failed to execute {command} (exit code {exitCode}).\n{stdout}\n{stderr}"; + BH.Engine.Base.Compute.RecordError( + exception: new InvalidOperationException(message), + message: message); + } + + return new Output { Item1 = stdout, Item2 = stderr, Item3 = exitCode }; + } } [Description("Run a string containing Python code and return the output. The string passed should end with a \"print\" statement, and other print statements within it should be captured within the script to ensure only a single output string is passed back to this method.")] - [Input("env", "The Python environment with which to run the Python script.")] + [Input("venv", "The Python environment with which to run the Python script.")] [Input("pythonString", "The string containing the Python script.")] [Output("result", "The stdout data from the executed Python script.")] - public static string RunPythonString(this oM.Python.PythonEnvironment env, string pythonString) + public static string RunPythonString(this oM.Python.PythonEnvironment venv, string pythonString) { if (!pythonString.Split('\n').Last().Contains("print")) { @@ -87,18 +178,20 @@ public static string RunPythonString(this oM.Python.PythonEnvironment env, strin } // place pythonScript into a temporary .py file to reference and run, then call using the passed environment - string scriptFile = Path.Combine(Path.GetTempPath(), "_BHoM_PythonScript.py"); - using (StreamWriter outputFile = new StreamWriter(scriptFile)) + // a unique file per call avoids collisions between concurrent calls + string scriptFile = Path.Combine(Path.GetTempPath(), $"_BHoM_PythonScript_{Guid.NewGuid():N}.py"); + File.WriteAllText(scriptFile, pythonString + Environment.NewLine); + + try { - outputFile.WriteLine(pythonString); + string cmd = $"\"{venv.Executable}\" \"{scriptFile}\""; + Output result = RunCommandStdout(command: cmd); + return result.Item3 == 0 ? result.Item1 : result.Item2; + } + finally + { + try { File.Delete(scriptFile); } catch (IOException) { } } - - string cmd = $"{Modify.AddQuotesIfRequired(env.Executable)} {scriptFile}"; - - return RunCommandStdout(cmd, hideWindows: true); } } } - - - diff --git a/Python_Engine/Compute/RunPytest.cs b/Python_Engine/Compute/RunPytest.cs new file mode 100644 index 00000000..c51ef841 --- /dev/null +++ b/Python_Engine/Compute/RunPytest.cs @@ -0,0 +1,107 @@ +/* + * This file is part of the Buildings and Habitats object Model (BHoM) + * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. + * + * Each contributor holds copyright over their respective contributions. + * The project versioning (Git) records all such contribution source information. + * + * + * The BHoM is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3.0 of the License, or + * (at your option) any later version. + * + * The BHoM is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this code. If not, see . + */ + +using BH.oM.Base; +using BH.oM.Base.Attributes; +using BH.oM.Python; +using System.ComponentModel; +using System.IO; + +namespace BH.Engine.Python +{ + public static partial class Compute + { + [Description("Run a toolkit's Python tests with pytest, using the toolkit's own virtual environment. The toolkit's pytest configuration (in its pyproject.toml) is used, and a JUnit XML report is written to /.pytest_results.xml.")] + [Input("toolkitDirectory", "The directory containing the toolkit's pyproject.toml and .venv, e.g. Path.Combine(Query.DirectoryEnvironments(), \"Python_Toolkit\").")] + [Input("arguments", "Additional pytest arguments, e.g. -m \"not slow\" or tests/test_core.py. Quote values with double quotes.")] + [Input("run", "Set to True to run the tests.")] + [Input("timeoutMinutes", "A number of minutes beyond which the test run is stopped.")] + [MultiOutput(0, "passed", "True if every collected test passed.")] + [MultiOutput(1, "exitCode", "The pytest exit code: 0 all passed, 1 some failed, 2 interrupted, 3 internal error, 4 usage error, 5 no tests collected, -1 timeout.")] + [MultiOutput(2, "output", "The pytest console output (stdout followed by stderr).")] + [MultiOutput(3, "report", "The path to the JUnit XML report, or null if none was written.")] + public static Output RunPytest(string toolkitDirectory, string arguments = "", bool run = false, double timeoutMinutes = 30) + { + if (string.IsNullOrWhiteSpace(toolkitDirectory) || !Directory.Exists(toolkitDirectory)) + { + Base.Compute.RecordError($"Toolkit directory not found: {toolkitDirectory}"); + return null; + } + + toolkitDirectory = Path.GetFullPath(toolkitDirectory); + string python = Path.Combine(toolkitDirectory, ".venv", "Scripts", "python.exe"); + string report = Path.Combine(toolkitDirectory, ".pytest_results.xml"); + string cmd = $"\"{python}\" -m pytest --junitxml=\"{report}\" {arguments}".Trim(); + + if (!run) + { + Base.Compute.RecordNote($"The following command will be executed from \"{toolkitDirectory}\": {cmd}"); + return null; + } + + if (!File.Exists(python)) + { + Base.Compute.RecordError($"No virtual environment was found at {Path.Combine(toolkitDirectory, ".venv")}. Create it first (e.g. using VirtualEnvironment)."); + return null; + } + + if (File.Exists(report)) + File.Delete(report); + + // tests must never write usage analytics to the real BHoM logs + System.Collections.Generic.Dictionary environment = new System.Collections.Generic.Dictionary { { "DISABLE_BHOM_ANALYTICS", "1" } }; + Output result = RunCommand(cmd, true, toolkitDirectory, timeoutMinutes, environment); + + return new Output + { + Item1 = result.Item3 == 0, + Item2 = result.Item3, + Item3 = string.IsNullOrEmpty(result.Item2) ? result.Item1 : result.Item1 + System.Environment.NewLine + result.Item2, + Item4 = File.Exists(report) ? report : null, + }; + } + + /***************************************************/ + + [Description("Run the Python tests of the toolkit that owns the given virtual environment. See RunPytest(string, string, bool, double).")] + [Input("venv", "A toolkit's Python environment.")] + [Input("arguments", "Additional pytest arguments, e.g. -m \"not slow\". Quote values with double quotes.")] + [Input("run", "Set to True to run the tests.")] + [Input("timeoutMinutes", "A number of minutes beyond which the test run is stopped.")] + [MultiOutput(0, "passed", "True if every collected test passed.")] + [MultiOutput(1, "exitCode", "The pytest exit code.")] + [MultiOutput(2, "output", "The pytest console output.")] + [MultiOutput(3, "report", "The path to the JUnit XML report, or null if none was written.")] + public static Output RunPytest(this PythonEnvironment venv, string arguments = "", bool run = false, double timeoutMinutes = 30) + { + if (venv == null || string.IsNullOrWhiteSpace(venv.Executable)) + { + Base.Compute.RecordError("A valid Python environment is required."); + return null; + } + + // /.venv/Scripts/python.exe + string toolkitDirectory = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(venv.Executable))); + return RunPytest(toolkitDirectory, arguments, run, timeoutMinutes); + } + } +} diff --git a/Python_Engine/Compute/UnzipFile.cs b/Python_Engine/Compute/UnzipFile.cs deleted file mode 100644 index 5c292a41..00000000 --- a/Python_Engine/Compute/UnzipFile.cs +++ /dev/null @@ -1,86 +0,0 @@ -/* - * This file is part of the Buildings and Habitats object Model (BHoM) - * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. - * - * Each contributor holds copyright over their respective contributions. - * The project versioning (Git) records all such contribution source information. - * - * - * The BHoM is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3.0 of the License, or - * (at your option) any later version. - * - * The BHoM is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this code. If not, see . - */ - -using BH.oM.Base.Attributes; -using System; -using System.ComponentModel; -using System.IO; - -namespace BH.Engine.Python -{ - public static partial class Compute - { - //This method is no longer used by python toolkit, and perhaps should be removed or moved to the file toolkit instead. - [Description("Extract the contents of an archive.")] - [Input("archivePath", "The archive to extract.")] - [Input("targetDirectory", "The destination directory to extract into.")] - [Input("targetName", "An optional input to rename the archive directory.")] - [Input("delete", "An optional input to delete the archive after extraction.")] - public static void UnzipFile( - string archivePath, - string targetDirectory, - string targetName = null, - bool delete = false - ) - { - if (string.IsNullOrWhiteSpace(archivePath)) - { - BH.Engine.Base.Compute.RecordError($"The archivePath cannot be null or empty."); - } - - if (string.IsNullOrWhiteSpace(targetDirectory)) - { - BH.Engine.Base.Compute.RecordError($"The targetDirectory cannot be null or empty."); - } - - if (!File.Exists(archivePath)) - { - BH.Engine.Base.Compute.RecordError($"The archivePath '{archivePath}' does not exist."); - } - - if (!Directory.Exists(targetDirectory)) - { - BH.Engine.Base.Compute.RecordError($"The targetDirectory '{targetDirectory}' does not exist."); - } - - if (string.IsNullOrWhiteSpace(targetName)) - { - targetName = Path.GetFileNameWithoutExtension(archivePath); - } - - string targetPath = Path.Combine(targetDirectory, targetName); - - if (Directory.Exists(targetPath)) - { - BH.Engine.Base.Compute.RecordError($"The targetPath '{targetPath}' already exists."); - } - - System.IO.Compression.ZipFile.ExtractToDirectory(archivePath, targetPath); - - if (delete) - File.Delete(archivePath); - } - } -} - - - diff --git a/Python_Engine/Compute/UpdateBHoMPackages.cs b/Python_Engine/Compute/UpdateBHoMPackages.cs index c1f3024f..1eb2bf54 100644 --- a/Python_Engine/Compute/UpdateBHoMPackages.cs +++ b/Python_Engine/Compute/UpdateBHoMPackages.cs @@ -20,91 +20,31 @@ * along with this code. If not, see . */ -using BH.oM.Base; using BH.oM.Base.Attributes; using BH.oM.Python; -using BH.oM.Python.Enums; -using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Diagnostics; using System.IO; -using System.Linq; -using System.Text; namespace BH.Engine.Python { public static partial class Compute { - [Description("Using the environment name (and version if the environment name is the base python environment), directly install/update missing BHoM packages.")] - [Input("environmentName", "The name of the environment to update.")] - [Input("version", "If the environment name is the name of the base python environment, the version that needs updating.")] - public static void UpdateBHoMPackages(this string environmentName, PythonVersion version = PythonVersion.Undefined) + [Description("Update the provided toolkit environment to match its pyproject.toml (and the latest versions of any BHoM toolkits it depends on) using UV.")] + [Input("venv", "The Python environment to update.")] + public static void UpdateBHoMPackages(this PythonEnvironment venv) { - //construct the expected PythonEnvironment and pass to UpdateBHoMPackages - PythonEnvironment env = new PythonEnvironment() + if (venv == null) { - Name = environmentName, - }; - - //python version is only used if the environment name is this toolkits name. - if (environmentName == Query.ToolkitName()) - { - if (version == PythonVersion.Undefined) - { - BH.Engine.Base.Compute.RecordError("The version must be specified when updating BHoM packages for a base python environment. No updates have occurred."); - return; - } - - env.Executable = Path.Combine(Query.DirectoryBaseEnvironment(version), "python.exe"); - } - else - env.Executable = Query.VirtualEnvironmentExecutable(environmentName); - - UpdateBHoMPackages(env); - } - - /***************************************************/ - - [Description("Using a PythonEnvironment, directly install/update missing BHoM packages.")] - [Input("environment", "The python environment to update.")] - public static void UpdateBHoMPackages(this PythonEnvironment environment) - { - if (!File.Exists(environment.Executable)) - { - BH.Engine.Base.Compute.RecordError($"Given environment or base install {environment.Executable} does not exist."); + Base.Compute.RecordError("A Python environment is required."); return; } - //`python -m pip list -e --format json` lists all environment packages that are editable installs. - //As all BHoM packages are editable installs, this handily lists all the packages that should be updated if necessary. - //side effect of updating other editable installs if they have changed, but I suspect this won't be a problem as anyone who has these would update packages manually instead. - System.Diagnostics.Process process = new System.Diagnostics.Process() - { - StartInfo = new System.Diagnostics.ProcessStartInfo() - { - FileName = environment.Executable, - Arguments = $"-m pip list -e --format json", - UseShellExecute = false, - RedirectStandardOutput = true, - } - }; - - process.StartInfo.Environment["PYTHONHOME"] = ""; - string stdOut; - - using (Process p = Process.Start(process.StartInfo)) - { - stdOut = p.StandardOutput.ReadToEnd(); - p.WaitForExit(); - } - - stdOut = stdOut.TrimEnd('\r', '\n'); - - IEnumerable objs = Serialiser.Convert.FromJsonArray(stdOut).OfType(); + string directory = Query.VirtualEnvironmentDirectory(venv.Name); + if (directory == null) + return; - foreach (CustomObject obj in objs) - InstallPackageLocal(environment, (string)obj.CustomData["editable_project_location"]); + InstallUV(true); + RunUV("sync --all-extras", startDirectory: directory); } } -} \ No newline at end of file +} diff --git a/Python_Engine/Compute/VirtualEnvironment.cs b/Python_Engine/Compute/VirtualEnvironment.cs index 6ed9dde7..4d9cc4a3 100644 --- a/Python_Engine/Compute/VirtualEnvironment.cs +++ b/Python_Engine/Compute/VirtualEnvironment.cs @@ -1,4 +1,4 @@ -/* +/* * This file is part of the Buildings and Habitats object Model (BHoM) * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. * @@ -20,120 +20,220 @@ * along with this code. If not, see . */ -using BH.Engine.Base; using BH.oM.Base.Attributes; using BH.oM.Python; -using BH.oM.Python.Enums; +using System; using System.Collections.Generic; using System.ComponentModel; -using System.Diagnostics; using System.IO; -using System.Linq; +using System.Text.RegularExpressions; namespace BH.Engine.Python { public static partial class Compute { - [Description("Install a Python Virtual Environment of a given version and name.")] + // matches a static `version = "x"` line, capturing any trailing comment so it can be preserved when re-stamping + private static readonly Regex m_VersionField = new Regex(@"(?m)^(?[ \t]*version[ \t]*=[ \t]*)(?['""])(?[^'""\r\n]*)\k(?[ \t]*(?:#[^\r\n]*)?)(?=\r?$)"); + + /***************************************************/ + + [Description("Create a Python Virtual Environment of a given version and name.")] [Input("version", "The version of Python to use for this environment.")] - [Input("name", "The name of this virtualenv.")] + [Input("name", "The name of this venv.")] [Input("reload", "Reload the virtual environment rather than recreating it, if it already exists.")] - [Output("env", "The exectuble for the resultant virtualenv.")] - public static PythonEnvironment VirtualEnvironment(this PythonVersion version, string name, bool reload = true) + [Output("venv", "The resultant venv.")] + public static PythonEnvironment VirtualEnvironment(string version, string name, bool reload = true) { - if (!Query.IsValidEnvironmentName(name)) + if (Query.VirtualEnvironmentExists(name)) { - BH.Engine.Base.Compute.RecordError("A BHoM Python virtual environment cannot cannot contain invalid filepath characters."); - return null; + if (reload) + { + PythonEnvironment existingVenv = new PythonEnvironment() { Executable = Query.VirtualEnvironmentExecutable(name), Name = name }; + string existingVersion = Query.Version(existingVenv); + if (existingVersion == null || (existingVersion != version && !existingVersion.StartsWith(version + ".", StringComparison.Ordinal))) + { + BH.Engine.Base.Compute.RecordError($"The requested environment already exists using Python {existingVersion}, but is being requested with Python {version}. Either provide a different name, a matching version, or remove the existing environment."); + return null; + } + return existingVenv; + } + else + { + RemoveVirtualEnvironment(name: name, run: true); + } } - if (version == PythonVersion.Undefined) - { - BH.Engine.Base.Compute.RecordError("Please provide a valid Python version."); + InstallUV(true); // ensure UV is installed + + string directory = Path.Combine(Query.DirectoryEnvironments(), name); + Directory.CreateDirectory(directory); + + if (RunUV($"venv \"{Path.Combine(directory, ".venv")}\" --python \"{version}\"", startDirectory: directory).Item3 != 0) return null; - } - string targetExecutable = Query.VirtualEnvironmentExecutable(name); - string targetDirectory = Query.VirtualEnvironmentDirectory(name); - string versionExecutable = Path.Combine(Query.DirectoryBaseEnvironment(version), "python.exe"); + PythonEnvironment venv = new PythonEnvironment() { Executable = Query.VirtualEnvironmentExecutable(name), Name = name }; - bool exists = Query.VirtualEnvironmentExists(name); + InstallJupyterKernel(venv: venv); - if (exists && reload) + return venv; + } + + [Description("Create (or update) a Python virtual environment from a toolkit's pyproject.toml, deployed in the BHoM Python environments directory (i.e. //pyproject.toml). " + + "The project's version is stamped with the current BHoM version, any local toolkit dependencies declared in [tool.uv.sources] are checked to be present, then the environment is synchronised using UV (including all extras and the default dependency groups) and registered as a Jupyter kernel.")] + [Input("tomlFile", "The path to a TOML file containing venv configuration.")] + [Input("reload", "Update the existing virtual environment in place (fast) rather than deleting and recreating it, if it already exists.")] + [Output("venv", "The resultant venv.")] + public static PythonEnvironment VirtualEnvironment(string tomlFile, bool reload = true) + { + if (string.IsNullOrWhiteSpace(tomlFile) || !File.Exists(tomlFile)) { - PythonEnvironment env = new PythonEnvironment() { Name = name, Executable = targetExecutable }; - UpdateBHoMPackages(env); - return env; + Base.Compute.RecordError($"TOML file not found at {tomlFile}"); + return null; } - if (exists && !reload) + tomlFile = Path.GetFullPath(tomlFile); + string directory = Path.GetDirectoryName(tomlFile); + string name = Path.GetFileName(directory); + + string expectedDirectory = Path.Combine(Query.DirectoryEnvironments(), name); + if (!string.Equals(directory, expectedDirectory, StringComparison.OrdinalIgnoreCase)) { - // remove all existing environments and kernels - RemoveVirtualEnvironment(name); - RemoveKernel(name); + Base.Compute.RecordError($"The TOML file must be deployed within the BHoM Python environments directory, at {Path.Combine(expectedDirectory, "pyproject.toml")}. For development outside this directory, run `uv sync` from the project folder instead."); + return null; } - if (!File.Exists(versionExecutable)) + // a package must have an associated TOML file, a README.md and a src/ + string readmeFile = Path.Combine(directory, "README.md"); + if (!File.Exists(readmeFile)) { - // The output here should be the same, but to be sure replace the value. - BH.Engine.Base.Compute.RecordNote($"The base environment for the requested version {version} has been installed as it was not present."); - versionExecutable = BasePythonEnvironment(version, run: true)?.Executable; + Base.Compute.RecordError($"README.md file not found at {readmeFile}"); + return null; + } - if (versionExecutable == null) // If the executable is null, then python wasn't installed correctly, so return null - the error message for downloading the version should suffice. - return null; + string packageName = StampVersion(tomlFile, Base.Query.BHoMVersion()); + if (packageName == null) + return null; + + string packageFile = Path.Combine(directory, "src", packageName, "__init__.py"); + if (!File.Exists(packageFile)) + { + Base.Compute.RecordError($"A Python package must contain a .\\src\\{packageName}\\__init__.py file."); + return null; } - // create the venv from the base environment - Process process = new Process() + if (!CheckLocalSources(tomlFile)) + return null; + + if (Query.VirtualEnvironmentExists(name) && !reload) + RemoveVirtualEnvironment(name: name, run: true); + + InstallUV(true); // ensure UV is installed + + if (RunUV("sync --all-extras", startDirectory: directory).Item3 != 0) + return null; + + PythonEnvironment venv = new PythonEnvironment() { Executable = Query.VirtualEnvironmentExecutable(name), Name = name }; + if (venv.Executable == null) + return null; + + InstallJupyterKernel(venv: venv); + + return venv; + } + + /***************************************************/ + /**** Private methods ****/ + /***************************************************/ + + // A TOML table's content, from its header up to the next table header. + private static Match TomlTable(string toml, string table) + { + return Regex.Match(toml, @"(?ms)^[ \t]*\[" + Regex.Escape(table) + @"\][ \t]*(?:#[^\r\n]*)?\r?\n(?.*?)(?=^[ \t]*\[|\z)"); + } + + /***************************************************/ + + // Set the static [project] version to the given version, preserving formatting and comments. Returns the [project] name, or null on failure. + private static string StampVersion(string tomlFile, string version) + { + string toml = File.ReadAllText(tomlFile); + Match project = TomlTable(toml, "project"); + string packageName = Regex.Match(project.Groups["content"].Value, + @"(?m)^[ \t]*name[ \t]*=[ \t]*['""](?[^'""\r\n]+)['""]").Groups["name"].Value; + if (!project.Success || string.IsNullOrWhiteSpace(packageName)) { - StartInfo = new ProcessStartInfo() - { - FileName = Modify.AddQuotesIfRequired(versionExecutable), - Arguments = $"-m virtualenv --python={Modify.AddQuotesIfRequired(versionExecutable)} {Modify.AddQuotesIfRequired(targetDirectory)}", - RedirectStandardError = true, - UseShellExecute = false, - } - }; + Base.Compute.RecordError($"A [project] section with a package name is required in {tomlFile}."); + return null; + } - process.StartInfo.Environment["PYTHONHOME"] = ""; + Group content = project.Groups["content"]; + Match versionField = m_VersionField.Match(content.Value); + if (!versionField.Success) + { + Base.Compute.RecordError($"A static [project] version is required in {tomlFile}."); + return null; + } - using (Process p = Process.Start(process.StartInfo)) + if (versionField.Groups["value"].Value != version) { - string standardError = p.StandardError.ReadToEnd(); - p.WaitForExit(); - if (p.ExitCode != 0) - BH.Engine.Base.Compute.RecordError($"Error creating virtual environment.\n{standardError}"); + string quote = versionField.Groups["quote"].Value; + string updatedProject = m_VersionField.Replace(content.Value, + match => match.Groups["prefix"].Value + quote + version + quote + match.Groups["suffix"].Value, 1); + File.WriteAllText(tomlFile, toml.Substring(0, content.Index) + updatedProject + toml.Substring(content.Index + content.Length)); } - // install ipykernel, pytest and black into new virtualenv - InstallPackages(targetExecutable, new List() { "ipykernel", "pytest", "black" }); + return packageName; + } + + /***************************************************/ + + // Ensure every local path declared in [tool.uv.sources] exists (i.e. dependent BHoM toolkits are installed), following + // the whole dependency chain (dependencies of dependencies), and stamp the versions of deployed toolkits along the way. + private static bool CheckLocalSources(string tomlFile) + { + HashSet visited = new HashSet(StringComparer.OrdinalIgnoreCase) { Path.GetDirectoryName(tomlFile) }; + return CheckLocalSources(tomlFile, new List { Path.GetFileName(Path.GetDirectoryName(tomlFile)) }, visited); + } + + /***************************************************/ - // register the virtualenv with the base environment - Process process2 = new Process() + private static bool CheckLocalSources(string tomlFile, List chain, HashSet visited) + { + string directory = Path.GetDirectoryName(tomlFile); + Match sources = TomlTable(File.ReadAllText(tomlFile), "tool.uv.sources"); + if (!sources.Success) + return true; + + bool success = true; + MatchCollection entries = Regex.Matches(sources.Groups["content"].Value, + @"(?m)^[ \t]*(?[A-Za-z0-9_.\-]+)[ \t]*=[ \t]*\{[^}\r\n]*\bpath[ \t]*=[ \t]*['""](?[^'""\r\n]+)['""]"); + foreach (Match entry in entries) { - StartInfo = new ProcessStartInfo() + string dependencyName = entry.Groups["name"].Value; + string dependencyDirectory = Path.GetFullPath(Path.Combine(directory, entry.Groups["path"].Value)); + string dependencyToml = Path.Combine(dependencyDirectory, "pyproject.toml"); + + // each toolkit is only checked once, which also guards against circular dependencies + if (!visited.Add(dependencyDirectory)) + continue; + + List dependencyChain = new List(chain) { dependencyName }; + if (!File.Exists(dependencyToml)) { - FileName = targetExecutable, - Arguments = $"-m ipykernel install --name={name} --user", //--user adds the kernel to %appdata%/jupyter/kernels, rather than to the virtualenv/share/jupyter/kernels - RedirectStandardError = true, - UseShellExecute = false, + string via = chain.Count > 1 ? $" (required via {string.Join(" -> ", dependencyChain)})" : ""; + Base.Compute.RecordError($"{chain[chain.Count - 1]} depends on {dependencyName}{via}, which was not found at {dependencyDirectory}. Install (or build) the BHoM toolkit providing {dependencyName} first."); + success = false; + continue; } - }; - process2.StartInfo.Environment["PYTHONHOME"] = ""; + // only stamp deployed toolkits; never modify source repositories + if (dependencyDirectory.StartsWith(Query.DirectoryEnvironments(), StringComparison.OrdinalIgnoreCase)) + success &= StampVersion(dependencyToml, Base.Query.BHoMVersion()) != null; - using (Process p = Process.Start(process2.StartInfo)) - { - string standardError = p.StandardError.ReadToEnd(); - p.WaitForExit(); - if (p.ExitCode != 0) - BH.Engine.Base.Compute.RecordError($"Error registering the \"{name}\" virtual environment.\n{standardError}"); + success &= CheckLocalSources(dependencyToml, dependencyChain, visited); } - return new PythonEnvironment() { Executable = targetExecutable, Name = name }; + return success; } } } - - - diff --git a/Python_Engine/Convert/ToPython.cs b/Python_Engine/Convert/ToPython.cs deleted file mode 100644 index 193669df..00000000 --- a/Python_Engine/Convert/ToPython.cs +++ /dev/null @@ -1,42 +0,0 @@ -/* - * This file is part of the Buildings and Habitats object Model (BHoM) - * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. - * - * Each contributor holds copyright over their respective contributions. - * The project versioning (Git) records all such contribution source information. - * - * - * The BHoM is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3.0 of the License, or - * (at your option) any later version. - * - * The BHoM is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this code. If not, see . - */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using BH.oM.Base.Attributes; - -namespace BH.Engine.Python -{ - public static partial class Convert - { - // TODO - REMOVE THIS METHOD, NO LONGER REQUIRED, PLUS IT HAS AN OLD ToBeRemoved TAG - [ToBeRemoved("5.3", "This method included in order to fool versioning into playing nicely.")] - public static bool ToPython(this T[,] input) - { - return false; - } - } -} - diff --git a/Python_Engine/Modify/AddQuotesIfRequired.cs b/Python_Engine/Modify/AddQuotesIfRequired.cs index ad54d616..e9be36dd 100644 --- a/Python_Engine/Modify/AddQuotesIfRequired.cs +++ b/Python_Engine/Modify/AddQuotesIfRequired.cs @@ -21,12 +21,7 @@ */ using BH.oM.Base.Attributes; -using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace BH.Engine.Python { @@ -38,14 +33,9 @@ public static partial class Modify public static string AddQuotesIfRequired(this string path) { return !string.IsNullOrWhiteSpace(path) ? - path.Contains(" ") && (!path.StartsWith("\"") && !path.EndsWith("\"")) ? + path.Contains(" ") && !path.StartsWith("\"") && !path.EndsWith("\"") ? "\"" + path + "\"" : path : string.Empty; } } } - - - - - diff --git a/Python_Engine/Python/Dockerfile b/Python_Engine/Python/Dockerfile index dde75b24..f7f5a4d7 100644 --- a/Python_Engine/Python/Dockerfile +++ b/Python_Engine/Python/Dockerfile @@ -1,22 +1,27 @@ -FROM python:3.10-slim -COPY . /Python_Toolkit +# syntax=docker/dockerfile:1 -#requires build argument --build-context bhom-assemblies C:/ProgramData/BHoM/Assemblies -COPY --from=bhom-assemblies . /bin/BHoM/Assemblies +# keep the UV version in sync with BH.Engine.Python.Query.UVVersion() +FROM ghcr.io/astral-sh/uv:0.13.10 AS uv +FROM mcr.microsoft.com/dotnet/aspnet:10.0-bookworm-slim AS dotnet -#install .net core 8.0, and set the pythonnet runtime to the .net core CLR -RUN apt-get update \ - && apt-get install -y wget - -RUN wget https://packages.microsoft.com/config/debian/13/packages-microsoft-prod.deb -O packages-microsoft-prod.deb -RUN dpkg -i packages-microsoft-prod.deb -RUN rm packages-microsoft-prod.deb +FROM python:3.10-slim-bookworm -RUN apt-get update \ - && apt-get install -y aspnetcore-runtime-10.0 +COPY --from=uv /uv /opt/BHoM/Extensions/Python/tools/uv +COPY --from=dotnet /usr/share/dotnet /usr/share/dotnet -ENV PYTHONNET_RUNTIME="coreclr" +ENV DOTNET_ROOT=/usr/share/dotnet \ + PYTHONNET_RUNTIME=coreclr \ + UV_PYTHON_DOWNLOADS=never \ + UV_LINK_MODE=copy \ + PATH="/opt/BHoM/Extensions/Python/Python_Toolkit/.venv/bin:/opt/BHoM/Extensions/Python/tools:/usr/share/dotnet:${PATH}" \ + PYTHONPATH="/opt/BHoM/Assemblies" -RUN pip3 install ./Python_Toolkit +WORKDIR /opt/BHoM/Extensions/Python/Python_Toolkit -RUN rm ./Python_Toolkit -rf \ No newline at end of file +# Requires the bhom-assemblies named build context. +COPY --from=bhom-assemblies . /opt/BHoM/Assemblies + +COPY pyproject.toml README.md ./ +COPY src ./src + +RUN /opt/BHoM/Extensions/Python/tools/uv sync --no-dev --no-editable --all-extras diff --git a/Python_Engine/Python/README.md b/Python_Engine/Python/README.md index bf482e26..b24ce11f 100644 --- a/Python_Engine/Python/README.md +++ b/Python_Engine/Python/README.md @@ -1,262 +1,103 @@ -# Python_Toolkit - -The code contained here is intended to be used in conjunction with the Python_Toolkit, as part of a wider [BHoM](https://bhom.xyz/) installation. Its main purpose is to augment capabilities of the BHoM. - -# BHoM Python environments - -_Where guidelines are not explicitly given, code style standards and procedures should refer to the wider [BHoM code compliance guidance](https://github.com/BHoM/documentation/wiki/Code-Compliance)._ - -## Creation of a Python environment - -A BHoM toolkit can be associated with a Python environment. The toolkit needs to have a location where Python code associated with that toolkit exists - so the first step is in creating that location and structure. - -**In the example below we'll go through creating a Python environment for the `Example_Toolkit`**. - -### Structure - -All Python code within BHoM should be placed within the hosting toolkit, inside its `*_Engine` folder. Within this folder, the following directory structure should be created (files have been included here within `./example_toolkit`, though these are purely indicative and struictures can vary based on toolkit need): - +# python_toolkit + +The root BHoM Python package. Every BHoM Python toolkit depends on it for shared behaviour, so that behaviour is +controlled in one place: + +| Module | What it provides | Requires | +| --- | --- | --- | +| `python_toolkit.bhom.logging` | `get_logger(name)`: console logging in the standard BHoM format | standard library | +| `python_toolkit.bhom.analytics` | `@bhom_analytics()`: lightweight usage tracking | standard library | +| `python_toolkit.bhom.bhom_object` | `BHoMObject`, `IObject` and JSON encoder/decoder compatible with the BHoM serialiser | standard library | +| `python_toolkit.bhom.decorators` / `run_wrapped` | `@bhom_wrapper.bhom_callable(...)`: expose Python methods to C# | standard library | +| `python_toolkit.units` | unit enumerations with conversion | standard library | +| `python_toolkit.scaffold` | `bhom-new-toolkit`: create a new toolkit | standard library | +| `python_toolkit.plot`, `python_toolkit.helpers` | plotting and data helpers | `python_toolkit[plot]` | +| `python_toolkit.bhom_tkinter` | BHoM-styled tkinter windows and widgets | `python_toolkit[ui]` | +| `python_toolkit.bhom.installer_info` | BHoM installation details via the .NET assemblies | `python_toolkit[clr]` | + +The core has **no third-party dependencies** and supports **Python 3.10 and later**, because it is installed into +every downstream toolkit's environment, whatever that toolkit's Python version. Keep it that way: anything needing +third-party packages belongs in an extra (guarded with `python_toolkit._optional.require_extra`) or in a downstream +toolkit. A test (`tests/test_core.py`) and CI enforce this. + +## Building a toolkit on python_toolkit + +Create a toolkit with `uv run bhom-new-toolkit --output --python <3.x>`, or with +`BH.Engine.Python.Compute.CreateToolkit`. The generated toolkit follows these conventions: + +```toml +# pyproject.toml +[project] +name = "wind_toolkit" +version = "999.999.999" # stamped with the BHoM version when the environment is created +requires-python = ">=3.11,<3.12" # the toolkit's own Python version +dependencies = ["python_toolkit[plot]", "other_toolkit"] + +[tool.uv.sources] # other toolkits are installed from where BHoM deploys them +python_toolkit = { path = "C:/ProgramData/BHoM/Extensions/Python/Python_Toolkit", editable = true } +other_toolkit = { path = "C:/ProgramData/BHoM/Extensions/Python/Other_Toolkit", editable = true } + +[tool.ruff] # the shared formatting/linting standard +extend = "C:/ProgramData/BHoM/Extensions/Python/Python_Toolkit/ruff.toml" ``` -. -├── ... -├── Example_Engine -│ └── Python -| ├── README.md -| ├── requirements.txt -| ├── setup.py -| ├── src -| | └── example_toolkit -| | ├── __init__.py -| | ├── module_a -| | | ├── __init__.py -| | | └── ... -| | └── ... -| └── tests -| ├── __init__.py -| ├── test_module_a.py -| └── ... -└── ... -``` - -### `setup.py` - -The `setup.py` file must be created alongside the code within a toolkit. This should contain teh following: ```python -## setup.py ## -from pathlib import Path - -import setuptools -from win32api import HIWORD, LOWORD, GetFileVersionInfo - -TOOLKIT_NAME = "Example_Toolkit" +# src/wind_toolkit/__init__.py +from python_toolkit.bhom.logging import get_logger -def _bhom_version() -> str: - """Return the version of BHoM installed (using the BHoM.dll in the root BHoM directory.""" - info = GetFileVersionInfo("C:/ProgramData/BHoM/Assemblies/BHoM.dll", "\\") # pylint: disable=[no-name-in-module] - ms = info["FileVersionMS"] - ls = info["FileVersionLS"] - return f"{HIWORD(ms)}.{LOWORD(ms)}.{HIWORD(ls)}.{LOWORD(ls)}" # pylint: disable=[no-name-in-module] +LOGGER = get_logger("Wind_Toolkit") -BHOM_VERSION = _bhom_version() +# src/wind_toolkit/speed.py +from python_toolkit.bhom.analytics import bhom_analytics -here = Path(__file__).parent.resolve() -long_description = (here / "README.md").read_text(encoding="utf-8") -requirements = [ - i.strip() - for i in (here / "requirements.txt").read_text(encoding="utf-8-sig").splitlines() -] -setuptools.setup( - name=TOOLKIT_NAME.lower(), - author="BHoM", - author_email="bhombot@burohappold.com", - description=f"A Python library that contains code intended to be used by the {TOOLKIT_NAME} Python environment for BHoM workflows.", - long_description=long_description, - long_description_content_type="text/markdown", - url=f"https://github.com/BHoM/{TOOLKIT_NAME}", - package_dir={"": "src"}, - packages=setuptools.find_packages(where="src", exclude=['tests']), - install_requires=requirements, - version=BHOM_VERSION, -) +@bhom_analytics() +def mean_speed(speeds: list[float]) -> float: + """Google-style docstrings are used to generate the documentation.""" + return sum(speeds) / len(speeds) ``` -### Enabling installation +The editable path sources mean that when BHoM is upgraded (redeploying `Python_Toolkit`), downstream toolkits pick up +the new shared code without reinstalling. -Two methods are required in the toolkit to which Python code is being added. The first is a `Query` method for the name of that toolkit: +## Usage analytics -```C# -using BH.oM.Base.Attributes; +Calls to `@bhom_analytics()` functions are aggregated in memory, one record per method per process, at a cost of a +couple of microseconds per call. Records are written to `%ProgramData%\BHoM\Logs\Usage__.jsonl`: -using System.ComponentModel; +- when the process exits; +- every 60 seconds or 10,000 calls; +- at most 10 MB per day. -namespace BH.Engine.Example -{ - public static partial class Query - { - [Description("Get the name of the current toolkit.")] - [Output("name", "The name of the current toolkit.")] - public static string ToolkitName() - { - return "Example_Toolkit"; - } - } -} -``` - -And the second is a `Compute` method called `ExampleToolkitPythonEnvironment` which installs the toolkits associated Python environment. In the method below, Python v3.7.9 is being used for this toolkits Python environment: - -```C# -using BH.oM.Base.Attributes; -using BH.oM.Python; - -using System.ComponentModel; - -namespace BH.Engine.Example -{ - public static partial class Compute - { - [Description("Install the Python virtualenv for the Example_Toolkit.")] - [Input("run", "Run the installation process for this BHoM Python environment.")] - [Output("env", "The Example_Toolkit Python environment, including any locally referenced BHoM code.")] - public static PythonEnvironment ExampleToolkitPythonEnvironment(bool run = false) - { - if (run) - { - return BH.Engine.Python.Compute.InstallVirtualenv( - name: Query.ToolkitName(), - pythonVersion: BH.oM.Python.Enums.PythonVersion.v3_7_9, // the version of Python to be used for this toolkits Python environment - localPackage: Path.Combine(Engine.Python.Query.CodeDirectory(), Query.ToolkitName()), - run: run - ); - } - return null; - } - } -} -``` - -Variations upon this can be made to reference external environments with known Python versions and installed packages also - with the [LadybugTools_Toolkit](https://github.com/BHoM/LadybugTools_Toolkit/blob/c005dc901459c4b779b329b65406d4a6c88f0965/LadybugTools_Engine/Compute/LadybugToolsToolkitPythonEnvironment.cs) showing how this is done. +A method called 100,000 times therefore produces one line, not 100,000. Each line is a JSON object with +`"schema": "bhom.python.usage/1"`, plus: -## Structure of Python code +- the method and toolkit; +- call and error counts; +- total and maximum durations; +- first and last call times; +- the project number (see `set_project_number`); +- the BHoM and Python versions; +- up to 10 distinct errors. -Unless otherwise specified, code style must follow guidance from [PEP8](https://peps.python.org/pep-0008/), unless otherwise stated in this document or in [BHoM C# guidance](https://github.com/BHoM/documentation/wiki/Coding-Style) (though some aspects of C# guidance are not applicable here due to differences between the two languages). +The `analytics` module docstring describes every field. `load_logs_from_file` and `summarise_usage_logs` read both this +format and the older per-call `UsageLogEntry` lines. -### BHoM/Python specific style guidance - -- One method or class per file. -- As much as possible, your code should be logically organised into a collection of directories and subdirectories. -- Helper methods often don't fit into specific workflows and exist outside of packaged Python modules. These should be placed in a `./helpers` directory in the root of the toolkits Python code. -- Files named in snake_case. For example, a class called `AThing`, would be in a file called `a_thing.py`, and a method called `do_stuff` would be in a files called `do_stuff.py`. -- Imports at the top of files must be absolute, to remove all ambiguity. -- Type hints are required on all functions and classes (both inputs and outputs). -- Docstrings must be added for all classes and methods. If the method is wrapped by a class, then only a description of that method is required as a minimum (unless the method is a dunder method). -- Docstrings should be provided in [Google format](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods). -- Default values should only be used where the defaults given are expected by a typical user of that code. If in doubt do not include a default. -- Where defaults are given, these are best placed in the method/class instantiation rather than reassigning to that variable upon checking if variable "is None" later in the code. -- Errors should be handled gracefully. When errors happen, the user should be told what went wrong and how to fix it. Broad Exceptions are allowed, although specific errors are preferable. Errors should also be captured at the lowest-possible level. - -## Testing - -The following guidelines are given for implementation of Python code testing. It is anticipated that the majority of testing can be undertaken automatically without need for human interaction. This does increase the time required to develop code - but will result in far better code overall as a result. Everything that can be reasonably tested should be done so. Dispensation may be given from the CI/CD lead where appropriate following suitable justification made by the code developer. - -The testing framework used in all BHoM Python code is `pytest`. In each BHoM toolkit, in the base of that toolkit is a ./.ci directory wherein tests should be placed. For example, in the `Example_Toolkit`, tests would be located in `./Example_Toolkit/.ci/unit_tests/python`. Tests should be created by the person that writes the code that is being tested, and subject to review by those undertaking the PR review. A passing unit test is required for PR approval. The reviewer needs to ensure that the testing procedure is sufficiently comprehensive as part of their approval. - -An example is given below for an appropriate candidate for testing: - -```python -## example_code.py ## -from typing import Union -def add(a: Union[int, float], b: Union[int, float]) -> float: - """Add two numbers together. +Set the `DISABLE_BHOM_ANALYTICS` environment variable to switch tracking off completely. Decorated functions are then +not wrapped at all. - Args: - a (Union[int, float]): The first number. - b (Union[int, float]): The second number. +## Development - Returns: - Union[int, float]: The result of adding the inputs together. - """ - if (not isinstance(a, (int, float))) and (not isinstance(b, (int, float)): - raise TypeError(f"The combination of dtypes ({type(a)}, {type(b)}) passed are not valid for this method.") - return a + b +```powershell +uv sync --all-extras # create .venv (Python 3.10, see .python-version) +uv run pytest # all tests; add -m "not slow" to skip the end-to-end scaffold test +uv run ruff format; uv run ruff check --fix # format and lint (see ruff.toml) +uv run --all-extras --group docs sphinx-build -b html docs docs/_build/html # documentation ``` -... with testing procedures defined to check that this method works as expected ... +The same tests can be run from C# with `BH.Engine.Python.Compute.RunPytest`. The VS Code tasks in the repository root +wrap all of the above. -```python -## test_example_code.py ## -import pytest -from example_code import add - -def test_add(): - a = 1.5 - b = 2.5 - assert add(a, b) == 4.0 - -def test_add_fails(): - with pytest.raises(TypeError) as e_info: - add("1", 1) - -``` - -... and the command used to test this would be ... - -``` -python -m pytest ./test_example_code.py -``` - -Tests should be written so that: - -- Cases where a method runs correctly and returns a pre-defined result pass. -- Cases where the method handles errors gracefully and raises an expected error pass. -- In complex processes, tests may not be possible for all methods; however, it is expected that the lowest methods in that process are tested to reduce risk of error cascading through these processes. -- In complex processes that rely on external programs, assertions should be made at the beginning of testing that those programs are available to the testing methods. -- Where stochastic results are expected, use "fuzzy matching" to check for closeness of results (see [pytest.approx](https://docs.pytest.org/en/7.1.x/reference/reference.html#pytest-approx)) - -# Recommended development environment - -Python in the context of BHoM is intended to be used where C# may not be as rapid or best placed to give results. As such, it can be considered more of a "scripting" language - with scope for formalisation into properly formatted and discretised code as part of BHoM toolkits. Ultimately it is up to the developer how to write their code, but the following setup is suggested for those just starting. - -## IDE - -Use VSCode for Python code development. This editor provides extensibility via packages which enable the automation of a lot of repetitive actions. The plugins that are recommended are: - -- python -- pylance -- Prettier -- autoDocstring - -Additionally, the following user settings can be added to enable auto-formatting of code upon saving to PEP8 compliance using "black" (a requirement of all BHoM Python code). - -```json -{ - "python.formatting.provider": "black", - "python.defaultInterpreterPath": "C:/ProgramData/BHoM/Extensions/PythonEnvironments/Example_Toolkit/python.exe", - "editor.formatOnType": true, - "editor.formatOnSave": true, - "editor.codeActionsOnSave": { - "source.fixAll": true, - "source.organizeImports": true, - "source.sortMembers": true - }, - "python.formatting.blackPath": "C:/ProgramData/BHoM/Extensions/PythonEnvironments/Python_Toolkit/Scripts/black.exe", - "python.linting.pylintArgs": ["--disable=C0114"] -} -``` - -## Scripting/notebooks - -Jupyter notebooks provide a good testing environment for Python code development. The registered ipykernel associated with each BHoM Python environment enables creation of environment specific notebooks with access to all code contained therein. Once you've got the base BHoM Python environment installed, you can run a notebook server using - -```bash -C:/ProgramData/BHoM/Extensions/PythonEnvironments/Python_Toolkit/python.exe -m jupyter lab -``` - -During development it can be useful to reload changes in code rather than restarting the kernel each time you modify the source code. To do this, include the following in the first cell in a notebook and changes you make in the referenced \*.py files will be brought through into the notebook environment. - -```python -%load_ext autoreload -%autoreload 2 -``` +`ruff.toml` is the shared standard for every toolkit. Its `per-file-ignores` list rules that legacy modules +(`plot`, `helpers`, `bhom_tkinter`) do not yet meet. Remove entries as those modules are tidied, and do not add new +ones. diff --git a/Python_Engine/Python/docs/conf.py b/Python_Engine/Python/docs/conf.py new file mode 100644 index 00000000..4478f150 --- /dev/null +++ b/Python_Engine/Python/docs/conf.py @@ -0,0 +1,30 @@ +"""Sphinx configuration (build with ``uv run --group docs sphinx-build docs docs/_build/html``).""" + +import importlib.metadata + +project = "Python_Toolkit" +author = "BHoM" +copyright = "BHoM" +try: + release = importlib.metadata.version("python_toolkit") +except importlib.metadata.PackageNotFoundError: + release = "0.0.0" + +extensions = [ + "autoapi.extension", + "myst_parser", + "sphinx.ext.napoleon", + "sphinx.ext.viewcode", +] + +autoapi_type = "python" +autoapi_dirs = ["../src"] +autoapi_options = ["members", "undoc-members", "show-inheritance", "show-module-summary"] +# the scaffold template contains .py.tmpl files only, but exclude it explicitly to keep the API reference focused +autoapi_ignore = ["*/scaffold/template/*"] +napoleon_google_docstring = True +napoleon_numpy_docstring = False +suppress_warnings = ["autoapi.python_import_resolution"] + +html_theme = "furo" +html_title = project diff --git a/Python_Engine/Python/docs/index.md b/Python_Engine/Python/docs/index.md new file mode 100644 index 00000000..65568295 --- /dev/null +++ b/Python_Engine/Python/docs/index.md @@ -0,0 +1,12 @@ +# Python_Toolkit + +The root BHoM Python toolkit: logging, usage analytics, BHoM JSON (de)serialisation and the C#-callable wrapper shared +by all BHoM Python toolkits, plus optional plotting (`python_toolkit[plot]`) and tkinter UI (`python_toolkit[ui]`) +extras. + +```{toctree} +:maxdepth: 3 +:caption: API reference + +autoapi/index +``` diff --git a/Python_Engine/Python/pyproject.toml b/Python_Engine/Python/pyproject.toml index 6db0bd6c..9dbc4761 100644 --- a/Python_Engine/Python/pyproject.toml +++ b/Python_Engine/Python/pyproject.toml @@ -1,54 +1,83 @@ [project] name = "python_toolkit" +version = "999.999.999" # This placeholder value is replaced by the BHoM build system during packaging. +description = "The root BHoM Python toolkit: logging, usage analytics, BHoM JSON (de)serialisation and the C#-callable wrapper shared by all BHoM Python toolkits." readme = "README.md" -dynamic = ["version", "description"] -authors = [ - { name = "BHoM", email = "bhombot@burohappold.com" } -] -dependencies = [ +# The root is installed into every downstream toolkit's environment, so it must support the oldest Python any toolkit uses. +requires-python = ">=3.10" +authors = [{ name = "BHoM", email = "bhombot@burohappold.com" }] +license = "LGPL-3.0-or-later" +# The core package is standard-library only; heavier capabilities are opt-in extras. +dependencies = [] + +[project.optional-dependencies] +plot = [ "case-converter", - "jupyterlab", "matplotlib", "numpy", "pandas", + "pillow", "plotly", - "pytest>=8.3.5", - "pytest-cov>=6.0.0", - "pytest-order", - "virtualenv", + "pytz", +] +ui = ["python_toolkit[plot]"] +clr = [ "pythonnet", + "pywin32; sys_platform == 'win32'", ] +all = ["python_toolkit[plot,ui,clr]"] -[urls] -source = "https://github.com/BHoM/Python_Toolkit" +[project.scripts] +bhom-new-toolkit = "python_toolkit.scaffold:main" + +[project.urls] +Homepage = "https://github.com/BHoM/Python_Toolkit" +Issues = "https://github.com/BHoM/Python_Toolkit/issues" [build-system] -requires = ["setuptools"] -build-backend = "setuptools.build_meta" +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/python_toolkit"] [dependency-groups] dev = [ - "black", - "ipykernel>=6.29.5", - "pylint>=3.3.5", - "pytest>=8.3.5", - "pytest-cov>=6.0.0", - "pytest-order", - "sphinx>=8.1.3", - "sphinx-bootstrap-theme>=0.8.1", - "sphinxcontrib-fulltoc>=1.2.0", - "sphinxcontrib-napoleon>=0.7", + "ipykernel", + "pre-commit", + "pytest", + "pytest-cov", + "pytest-rerunfailures", + "pytest-xdist", + "ruff", +] +docs = [ + "furo", + "myst-parser", + "sphinx", + "sphinx-autoapi", ] -[tool.setuptools] -package-dir = {"" = "src"} - -[tool.setuptools.packages.find] -where = ["src"] -exclude = ["tests"] +[tool.uv] +default-groups = ["dev"] -[tool.setuptools.package-data] -"*" = ["*.mplstyle"] +# Formatting and linting: see ruff.toml (the shared BHoM standard, which ruff reads in preference to this file). [tool.pytest.ini_options] -pythonpath = "src" +testpaths = ["tests"] +addopts = "-ra --strict-markers" +markers = [ + "slow: long-running tests (deselect with -m \"not slow\")", + "ui: tests that open tkinter windows (require a display)", +] +filterwarnings = [ + "ignore::DeprecationWarning:pywintypes", +] + +[tool.coverage.run] +source = ["python_toolkit"] +branch = true + +[tool.coverage.report] +show_missing = true +skip_covered = true diff --git a/Python_Engine/Python/ruff.toml b/Python_Engine/Python/ruff.toml new file mode 100644 index 00000000..f4c358ba --- /dev/null +++ b/Python_Engine/Python/ruff.toml @@ -0,0 +1,56 @@ +# Shared BHoM Python formatting and linting standard. +# +# This file is the single source of truth for every BHoM Python toolkit. Downstream toolkits +# reference the deployed copy from their pyproject.toml: +# +# [tool.ruff] +# extend = "C:/ProgramData/BHoM/Extensions/Python/Python_Toolkit/ruff.toml" +# +# Toolkit-specific exceptions belong in that toolkit's own pyproject.toml, not here. Ruff resolves paths (including +# `src` and per-file-ignores globs) relative to the file defining them, so the path-based settings below only apply to +# Python_Toolkit itself; downstream toolkits declare their own (see the scaffold template). + +target-version = "py310" +line-length = 120 +extend-exclude = ["docs/_build", "docs/autoapi"] +src = ["src", "tests"] + +[format] +docstring-code-format = true + +[lint] +select = [ + "E", # pycodestyle errors + "W", # pycodestyle warnings + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "B", # flake8-bugbear + "D", # pydocstyle (enables documentation generation from docstrings) + "C4", # flake8-comprehensions + "SIM", # flake8-simplify + "RUF", # ruff-specific rules +] +ignore = [ + "D105", # magic methods are self-describing + "D107", # __init__ is documented on the class + "E501", # line length is handled by the formatter +] + +[lint.pydocstyle] +convention = "google" + +[lint.per-file-ignores] +"**/__init__.py" = ["F401"] +"docs/conf.py" = ["D"] +"scripts/**" = ["D"] +"tests/**" = ["D", "RUF059"] +# Legacy optional-extra modules of Python_Toolkit that predate this standard. Do not add new codes here; remove them +# as the modules are brought up to standard. New modules (and the stdlib-only core) must pass the full rule set. +"src/python_toolkit/{bhom_tkinter,helpers,plot}/**" = [ + "B026", "B905", "D1", "D205", "D417", "RUF005", "RUF012", "RUF015", "RUF046", "RUF059", + "SIM102", "SIM105", "SIM108", "UP007", +] +# imports intentionally follow the require_extra() guard / matplotlib backend selection +"src/python_toolkit/{bhom_tkinter,helpers}/__init__.py" = ["E402"] +"src/python_toolkit/bhom_tkinter/bhom_base_window.py" = ["E402"] diff --git a/Python_Engine/Python/run_tests.bat b/Python_Engine/Python/run_tests.bat deleted file mode 100644 index 18e46305..00000000 --- a/Python_Engine/Python/run_tests.bat +++ /dev/null @@ -1,7 +0,0 @@ -SET PYTHON_EXE=C:\ProgramData\BHoM\Extensions\PythonEnvironments\Python_Toolkit\v3_10\python.exe -SET TEST_DIR=C:\ProgramData\BHoM\Extensions\PythonCode\Python_Toolkit\tests - -@REM C:\ProgramData\BHoM\Extensions\PythonEnvironments\Python_Toolkit\v3_10\python.exe -m pytest --cov-report term --cov-report html:cov_html --cov python_toolkit -v C:\ProgramData\BHoM\Extensions\PythonCode\Python_Toolkit\tests - -"%PYTHON_EXE%" -m pytest --cov-report term --cov-report html:cov_html --cov python_toolkit -v "%TEST_DIR%" -cmd /k \ No newline at end of file diff --git a/Python_Engine/Python/scripts/build_docs.ps1 b/Python_Engine/Python/scripts/build_docs.ps1 new file mode 100644 index 00000000..824603b9 --- /dev/null +++ b/Python_Engine/Python/scripts/build_docs.ps1 @@ -0,0 +1,25 @@ +param ( + [switch]$Serve, + [ValidateRange(1, 65535)] + [int]$Port = 8000 +) + +# Build the HTML documentation for this toolkit with Sphinx (installed from the "docs" dependency group). +$ErrorActionPreference = "Stop" +$projectRoot = Split-Path -Parent $PSScriptRoot +$outputDirectory = Join-Path $projectRoot "docs\_build\html" + +Push-Location $projectRoot +try { + uv run --all-extras --group docs sphinx-build -b html docs $outputDirectory + if ($LASTEXITCODE -ne 0) { throw "Sphinx build failed with exit code $LASTEXITCODE." } + Write-Host "Documentation was built at $outputDirectory." + + if ($Serve) { + Write-Host "Serving documentation at http://127.0.0.1:$Port/ (press Ctrl+C to stop)." + uv run python -m http.server $Port --bind 127.0.0.1 --directory $outputDirectory + } +} +finally { + Pop-Location +} diff --git a/Python_Engine/Python/scripts/install.ps1 b/Python_Engine/Python/scripts/install.ps1 new file mode 100644 index 00000000..ab94076f --- /dev/null +++ b/Python_Engine/Python/scripts/install.ps1 @@ -0,0 +1,50 @@ +param ( + [switch]$Run +) + +. "$PSScriptRoot\shared.ps1" + +function Install-Package { + $functionName = $MyInvocation.MyCommand.Name + + $workspaceRoot = Split-Path -Parent $PSScriptRoot + $locationPushed = $false + $toolkitName = "Python Toolkit" + $installationComplete = $false + + try { + Push-Location $workspaceRoot + $locationPushed = $true + $tomlFile = Get-TomlFile + $toolkitName = Get-ToolkitName + Write-InfoMessage -Message "Starting installation process for $toolkitName." -FunctionName $functionName + + Write-InfoMessage -Message "Preparing UV and its command-line tools." -FunctionName $functionName + Install-UV + + Write-InfoMessage -Message "Syncing the Python environment from $tomlFile." -FunctionName $functionName + Sync-PythonEnvironment + + Write-InfoMessage -Message "Registering the Jupyter kernel." -FunctionName $functionName + Register-Kernel -KernelName $toolkitName + $installationComplete = $true + } + catch { + Write-ErrorMessage -Message "Installation failed for $toolkitName. $($_.Exception.Message)" -FunctionName $functionName -ThrowError + } + finally { + if ($locationPushed) { + Pop-Location + } + if ($installationComplete) { + Write-InfoMessage -Message "Installation process for $toolkitName completed successfully." -FunctionName $functionName + } + else { + Write-WarningMessage -Message "Installation process for $toolkitName did not complete." -FunctionName $functionName + } + } +} + +if ($Run -or $MyInvocation.InvocationName -ne '.') { + Install-Package +} diff --git a/Python_Engine/Python/scripts/pre_commit.ps1 b/Python_Engine/Python/scripts/pre_commit.ps1 new file mode 100644 index 00000000..6e57c154 --- /dev/null +++ b/Python_Engine/Python/scripts/pre_commit.ps1 @@ -0,0 +1,27 @@ +param ( + [switch]$Check +) + +# Format and lint this toolkit with the shared BHoM ruff standard (see ../ruff.toml). +# Use -Check to verify without modifying files (as CI does). To run automatically on every commit, install the +# repository's git hooks once with: uv run pre-commit install +$ErrorActionPreference = "Stop" +$projectRoot = Split-Path -Parent $PSScriptRoot + +Push-Location $projectRoot +try { + if ($Check) { + uv run ruff format --check . + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + uv run ruff check . + } + else { + uv run ruff format . + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + uv run ruff check --fix . + } + exit $LASTEXITCODE +} +finally { + Pop-Location +} diff --git a/Python_Engine/Python/scripts/run_tests.ps1 b/Python_Engine/Python/scripts/run_tests.ps1 new file mode 100644 index 00000000..dc20562c --- /dev/null +++ b/Python_Engine/Python/scripts/run_tests.ps1 @@ -0,0 +1,21 @@ +param ( + [switch]$IncludeSlow, + [switch]$Coverage +) + +# Run this toolkit's tests. Slow tests (marked @pytest.mark.slow) are skipped unless -IncludeSlow is given. +$ErrorActionPreference = "Stop" +$projectRoot = Split-Path -Parent $PSScriptRoot + +$arguments = @() +if (-not $IncludeSlow) { $arguments += @("-m", "not slow") } +if ($Coverage) { $arguments += @("--cov", "--cov-report=term-missing") } + +Push-Location $projectRoot +try { + uv run --all-extras pytest @arguments + exit $LASTEXITCODE +} +finally { + Pop-Location +} diff --git a/Python_Engine/Python/scripts/shared.ps1 b/Python_Engine/Python/scripts/shared.ps1 new file mode 100644 index 00000000..67219a8a --- /dev/null +++ b/Python_Engine/Python/scripts/shared.ps1 @@ -0,0 +1,241 @@ +function Write-InfoMessage { + param ( + [Parameter(Mandatory = $true)] + [string]$Message, + [string]$FunctionName = $MyInvocation.MyCommand.Name + ) + + Write-Host "- [$FunctionName] Info: $Message" -ForegroundColor Cyan +} + +function Write-WarningMessage { + param ( + [Parameter(Mandatory = $true)] + [string]$Message, + [string]$FunctionName = $MyInvocation.MyCommand.Name + ) + + Write-Host "- [$FunctionName] Warning: $Message" -ForegroundColor Magenta +} + +function Write-ErrorMessage { + param ( + [Parameter(Mandatory = $true)] + [string]$Message, + [Parameter(Mandatory = $false)] + [string]$FunctionName = $MyInvocation.MyCommand.Name, + [switch]$ThrowError + ) + + Write-Host "m- [$FunctionName] Error: $Message" -ForegroundColor Red + if ($ThrowError) { + throw $Message + } +} + +function Read-UserInput { + param ( + [Parameter(Mandatory = $true)] + [string]$Message + ) + + Write-Host $Message -ForegroundColor Yellow -NoNewline + return Read-Host +} + +function Get-LocalPythonExecutable { + $functionName = $MyInvocation.MyCommand.Name + $workspaceRoot = Split-Path -Parent $PSScriptRoot + $projectPython = Join-Path $workspaceRoot ".venv\Scripts\python.exe" + if (Test-Path $projectPython -PathType Leaf) { + Write-InfoMessage -Message "Using Python executable: $projectPython" -FunctionName $functionName + return $projectPython + } + else { + Write-ErrorMessage -Message "Local Python executable not found at $projectPython. Run the installation script first." -FunctionName $functionName -ThrowError + } +} + +function Get-TomlFile { + $workspaceRoot = Split-Path -Parent $PSScriptRoot + $tomlFile = Join-Path $workspaceRoot "pyproject.toml" + if (Test-Path $tomlFile -PathType Leaf) { + return $tomlFile + } + else { + throw "pyproject.toml file not found at $tomlFile." + } +} + +function Register-Kernel { + param ( + [Parameter(Mandatory = $true)] + [string]$KernelName, + [Parameter(Mandatory = $false)] + [string]$DisplayName + ) + + $functionName = $MyInvocation.MyCommand.Name + + $workspaceRoot = Split-Path -Parent $PSScriptRoot + $pythonExecutable = Get-LocalPythonExecutable + + if (-not $DisplayName) { + $DisplayName = "Python ($KernelName)" + } + + $locationPushed = $false + try { + Push-Location $workspaceRoot + $locationPushed = $true + Write-InfoMessage -Message "Creating $KernelName ($DisplayName) Jupyter kernel." -FunctionName $functionName + + & $pythonExecutable -m ipykernel install --user --name $KernelName --display-name $DisplayName + if ($LASTEXITCODE -ne 0) { + throw "Python failed to register the Jupyter kernel (exit code $LASTEXITCODE)." + } + } + catch { + Write-ErrorMessage -Message "Failed to create the $KernelName Jupyter kernel. $($_.Exception.Message)" -FunctionName $functionName -ThrowError + } + finally { + if ($locationPushed) { + Pop-Location + } + } +} + +function Unregister-Kernel { + param ( + [Parameter(Mandatory = $true)] + [string]$KernelName + ) + $functionName = $MyInvocation.MyCommand.Name + $workspaceRoot = Split-Path -Parent $PSScriptRoot + $pythonExecutable = Get-LocalPythonExecutable + + try { + Push-Location $workspaceRoot + try { + Write-InfoMessage -Message "Removing $KernelName Jupyter kernel." -FunctionName $functionName + + & $pythonExecutable -m jupyter kernelspec uninstall $KernelName -f + $uninstallExitCode = $LASTEXITCODE + if ($uninstallExitCode -ne 0) { + Write-WarningMessage -Message "Jupyter could not remove the kernel (exit code $uninstallExitCode); checking its files directly." -FunctionName $functionName + } + + $kernelPath = Join-Path $env:APPDATA "jupyter\kernels\$KernelName" + if (Test-Path $kernelPath) { + Remove-PathIfExists -Path $kernelPath -Description "the $KernelName Jupyter kernel" -FunctionName $functionName + } + else { + Write-InfoMessage -Message "No remaining Jupyter kernel files found for $KernelName." -FunctionName $functionName + } + } + finally { + Pop-Location + } + } + catch { + Write-ErrorMessage -Message "Failed to remove the $KernelName Jupyter kernel. $($_.Exception.Message)" -FunctionName $functionName -ThrowError + } +} + +function Get-ToolkitName { + $tomlFile = Get-TomlFile + $tomlContent = Get-Content -LiteralPath $tomlFile -ErrorAction Stop + foreach ($line in $tomlContent) { + if ($line -match '^\s*name\s*=\s*"([^"]+)"\s*$') { + return $matches[1] + } + } + throw "Project name was not found in $tomlFile." +} + +function Remove-PathIfExists { + param ( + [Parameter(Mandatory = $true)] + [string]$Path, + [Parameter(Mandatory = $true)] + [string]$Description, + [Parameter(Mandatory = $true)] + [string]$FunctionName + ) + + if (Test-Path $Path) { + try { + Remove-Item -LiteralPath $Path -Recurse -Force -ErrorAction Stop + Write-InfoMessage -Message "Removed ${Description}: $Path" -FunctionName $FunctionName + } + catch { + Write-ErrorMessage -Message "Could not remove ${Description} at $Path. $($_.Exception.Message)" -FunctionName $FunctionName -ThrowError + } + } +} + +function Get-UVExecutable { + return Join-Path $env:ProgramData "BHoM\Extensions\Python\tools\uv.exe" +} + +# Keep in sync with BH.Engine.Python.Query.UVVersion() +$script:UVVersion = "0.13.10" + +function Install-UV { + # Install the pinned UV into the BHoM tools directory (mirrors BH.Engine.Python.Compute.InstallUV). + $functionName = $MyInvocation.MyCommand.Name + $uvExecutable = Get-UVExecutable + $uvBinPath = Split-Path -Parent $uvExecutable + + $installedVersion = $null + if (Test-Path -LiteralPath $uvExecutable -PathType Leaf) { + $installedVersion = ((& $uvExecutable --version) -split " ")[1] + } + + if ($installedVersion -ne $script:UVVersion) { + try { + Write-InfoMessage -Message "Installing UV $($script:UVVersion) in $uvBinPath." -FunctionName $functionName + $escapedDirectory = $uvBinPath.Replace("'", "''") + & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "`$ErrorActionPreference = 'Stop'; `$env:UV_INSTALL_DIR = '$escapedDirectory'; `$env:UV_NO_MODIFY_PATH = '1'; irm https://astral.sh/uv/$($script:UVVersion)/install.ps1 | iex" + if ($LASTEXITCODE -ne 0) { + throw "UV installer exited with code $LASTEXITCODE." + } + } + catch { + Write-ErrorMessage -Message "Failed to install UV. $($_.Exception.Message)" -FunctionName $functionName -ThrowError + } + } + + if (-not (Test-Path -LiteralPath $uvExecutable -PathType Leaf)) { + Write-ErrorMessage -Message "The UV executable was not installed at $uvExecutable." -FunctionName $functionName -ThrowError + } + + # keep UV-managed interpreters and caches inside the BHoM tools directory (mirrors Query.UVEnvironmentVariables) + if (-not $env:UV_PYTHON_INSTALL_DIR) { $env:UV_PYTHON_INSTALL_DIR = Join-Path $uvBinPath "python" } + if (-not $env:UV_CACHE_DIR) { $env:UV_CACHE_DIR = Join-Path $uvBinPath "cache" } + Write-InfoMessage -Message "Using UV from $uvExecutable." -FunctionName $functionName +} + +function Sync-PythonEnvironment { + $functionName = $MyInvocation.MyCommand.Name + $workspaceRoot = Split-Path -Parent $PSScriptRoot + $locationPushed = $false + + try { + Push-Location $workspaceRoot + $locationPushed = $true + Write-InfoMessage -Message "Installing Python packages with UV." -FunctionName $functionName + & (Get-UVExecutable) sync --all-extras + if ($LASTEXITCODE -ne 0) { + throw "uv sync exited with code $LASTEXITCODE." + } + } + catch { + Write-ErrorMessage -Message "Failed to sync the Python environment. $($_.Exception.Message)" -FunctionName $functionName -ThrowError + } + finally { + if ($locationPushed) { + Pop-Location + } + } +} diff --git a/Python_Engine/Python/tests/test_styling.py b/Python_Engine/Python/scripts/styling_guide.py similarity index 91% rename from Python_Engine/Python/tests/test_styling.py rename to Python_Engine/Python/scripts/styling_guide.py index a6b8e499..84e07f76 100644 --- a/Python_Engine/Python/tests/test_styling.py +++ b/Python_Engine/Python/scripts/styling_guide.py @@ -10,8 +10,8 @@ from __future__ import annotations import os -from tkinter import ttk from tkinter import font as tkfont +from tkinter import ttk from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow from python_toolkit.bhom_tkinter.widgets.label import Label as BHoMLabel @@ -90,10 +90,14 @@ def run_styling_guide( parsed = tkfont.Font(root=window, font=font_lookup) print( style_name, - "lookup=", font_lookup, - "actual-size=", parsed.actual("size"), - "linespace=", parsed.metrics("linespace"), - "rendered-height=", sample.label.winfo_reqheight(), + "lookup=", + font_lookup, + "actual-size=", + parsed.actual("size"), + "linespace=", + parsed.metrics("linespace"), + "rendered-height=", + sample.label.winfo_reqheight(), ) if auto_close_ms is not None and auto_close_ms > 0: diff --git a/Python_Engine/Python/scripts/uninstall.ps1 b/Python_Engine/Python/scripts/uninstall.ps1 new file mode 100644 index 00000000..e2f6977e --- /dev/null +++ b/Python_Engine/Python/scripts/uninstall.ps1 @@ -0,0 +1,51 @@ +param ( + [switch]$Run +) + +. "$PSScriptRoot\shared.ps1" + +function Uninstall-Package { + $functionName = $MyInvocation.MyCommand.Name + + $workspaceRoot = Split-Path -Parent $PSScriptRoot + $locationPushed = $false + $toolkitName = "Python Toolkit" + $uninstallationComplete = $false + + try { + Push-Location $workspaceRoot + $locationPushed = $true + $toolkitName = Get-ToolkitName + + $userInput = Read-UserInput -Message "Do you really want to uninstall the $toolkitName Python package? (y/n): " + if ($userInput -ne "y") { + Write-InfoMessage -Message "Uninstallation aborted by the user." -FunctionName $functionName + return + } + + Write-InfoMessage -Message "Removing the Jupyter kernel." -FunctionName $functionName + Unregister-Kernel -KernelName $toolkitName + + Write-InfoMessage -Message "Removing the project virtual environment." -FunctionName $functionName + Remove-PathIfExists -Path (Join-Path $workspaceRoot ".venv") -Description "the $toolkitName virtual environment" -FunctionName $functionName + $uninstallationComplete = $true + } + catch { + Write-ErrorMessage -Message "Uninstallation failed for $toolkitName. $($_.Exception.Message)" -FunctionName $functionName -ThrowError + } + finally { + if ($locationPushed) { + Pop-Location + } + if ($uninstallationComplete) { + Write-InfoMessage -Message "Uninstallation process for $toolkitName completed successfully." -FunctionName $functionName + } + elseif ($userInput -eq "y") { + Write-WarningMessage -Message "Uninstallation process for $toolkitName did not complete." -FunctionName $functionName + } + } +} + +if ($Run -or $MyInvocation.InvocationName -ne '.') { + Uninstall-Package +} diff --git a/Python_Engine/Python/setup.py b/Python_Engine/Python/setup.py deleted file mode 100644 index 1132b946..00000000 --- a/Python_Engine/Python/setup.py +++ /dev/null @@ -1,22 +0,0 @@ -from pathlib import Path -import setuptools - -TOOLKIT_NAME = "Python_Toolkit" - -here = Path(__file__).parent.resolve() - -def _bhom_version() -> str: - """Return the version of BHoM installed (using the BHoM.dll in the root BHoM directory.""" - versionFile = here / "VERSION.txt" #version file is created in a pre-build event in Python_Engine.csproj - return versionFile.read_text(); - -BHOM_VERSION = _bhom_version() - -long_description = (here / "README.md").read_text(encoding="utf-8") - -setuptools.setup( - description=f"A Python library that contains minimal code intended to be used by the {TOOLKIT_NAME} Python environment for BHoM workflows.", - long_description=long_description, - long_description_content_type="text/markdown", - version=BHOM_VERSION, -) diff --git a/Python_Engine/Python/src/python_toolkit/__init__.py b/Python_Engine/Python/src/python_toolkit/__init__.py index 3e022cfb..3c46645b 100644 --- a/Python_Engine/Python/src/python_toolkit/__init__.py +++ b/Python_Engine/Python/src/python_toolkit/__init__.py @@ -1,14 +1,19 @@ -"""Base module for the python_toolkit package.""" -# pylint: disable=E0401 +"""The root BHoM Python toolkit. + +The core of this package (``python_toolkit.bhom``, ``python_toolkit.units`` and ``python_toolkit.scaffold``) +depends only on the Python standard library, so it can be installed into every downstream toolkit's +environment regardless of that toolkit's Python version. Heavier capabilities are optional extras: + +* ``python_toolkit[plot]`` - ``python_toolkit.plot`` and ``python_toolkit.helpers`` +* ``python_toolkit[ui]`` - ``python_toolkit.bhom_tkinter`` +* ``python_toolkit[clr]`` - pythonnet access to BHoM .NET assemblies +""" + import getpass import os from pathlib import Path -import matplotlib.pyplot as plt - -# pylint: disable=E0401 - -# get common paths +# common paths DATA_DIRECTORY = (Path(__file__).parent.parent / "data").absolute() BHOM_DIRECTORY = (Path(__file__).parent / "bhom").absolute() HOME_DIRECTORY = (Path("C:/Users/") / getpass.getuser()).absolute() @@ -16,5 +21,5 @@ TOOLKIT_NAME = "Python_Toolkit" if os.name == "nt": - # override "HOME" in case this is set to something other than default for windows - os.environ["HOME"] = (Path("C:/Users/") / getpass.getuser()).as_posix() + # override "HOME" in case this is set to something other than default for windows (relied upon by downstream toolkits) + os.environ["HOME"] = HOME_DIRECTORY.as_posix() diff --git a/Python_Engine/Python/src/python_toolkit/_optional.py b/Python_Engine/Python/src/python_toolkit/_optional.py new file mode 100644 index 00000000..ef97df7d --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/_optional.py @@ -0,0 +1,21 @@ +"""Helpers for optional ("extra") dependencies.""" + +from importlib.util import find_spec + + +def require_extra(extra: str, *modules: str) -> None: + """Raise a helpful ImportError if any module needed by an optional extra is not installed. + + Args: + extra: The name of the python_toolkit extra providing the modules, e.g. "plot". + *modules: Top-level module names that must be importable. + + Raises: + ImportError: If any module is missing. + """ + missing = [module for module in modules if find_spec(module) is None] + if missing: + raise ImportError( + f"This feature requires the optional dependencies {', '.join(missing)}. " + f'Install them with the "{extra}" extra, e.g. `uv add "python_toolkit[{extra}]"`.' + ) diff --git a/Python_Engine/Python/src/python_toolkit/bhom/__init__.py b/Python_Engine/Python/src/python_toolkit/bhom/__init__.py index e3ab0b23..9ae785af 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom/__init__.py +++ b/Python_Engine/Python/src/python_toolkit/bhom/__init__.py @@ -1,41 +1,54 @@ -"""Root for the bhom subpackage.""" +"""Core BHoM integration: constants, logging, usage analytics and BHoM object (de)serialisation. +Everything in this subpackage depends only on the Python standard library. +""" + +import importlib.metadata import os -from pathlib import Path # pylint: disable=E0401 -from os import path import tempfile -import importlib.metadata - -if os.name == 'nt': - from .installer_info import INSTALLER_INFO -else: - INSTALLER_INFO = {"Version": importlib.metadata.version("python_toolkit")} +from pathlib import Path +from typing import Any -BHOM_LOG_FOLDER = Path(path.expandvars("%PROGRAMDATA%/BHoM/Logs")) -TEMP_LOG_FOLDER = Path(tempfile.gettempdir()) / "BHoM" / "Logs" TOOLKIT_NAME = "Python_Toolkit" -BHOM_VERSION = INSTALLER_INFO["Version"] -#Environment variable that if set disables BHoM analytics logging. -DISABLE_ANALYTICS = os.environ.get("DISABLE_BHOM_ANALYTICS", None) -if DISABLE_ANALYTICS is None: - DISABLE_ANALYTICS = False -else: - DISABLE_ANALYTICS = True +# Environment variable that, if set, disables BHoM analytics logging. +DISABLE_ANALYTICS = os.environ.get("DISABLE_BHOM_ANALYTICS") is not None -if not BHOM_LOG_FOLDER.exists(): +def _bhom_version() -> str: + """The BHoM version this toolkit was installed with. + + BH.Engine.Python stamps each toolkit's pyproject.toml version with the BHoM version before installing it, + so the installed package metadata holds the BHoM version without needing to load any .NET assemblies. + """ + try: + return importlib.metadata.version("python_toolkit") + except importlib.metadata.PackageNotFoundError: + return "0.0.0" + + +BHOM_VERSION = _bhom_version() + +TEMP_LOG_FOLDER = Path(tempfile.gettempdir()) / "BHoM" / "Logs" +BHOM_LOG_FOLDER = Path(os.path.expandvars("%PROGRAMDATA%/BHoM/Logs")) if os.name == "nt" else TEMP_LOG_FOLDER + +if not BHOM_LOG_FOLDER.exists(): try: BHOM_LOG_FOLDER.mkdir(exist_ok=True, parents=True) - #migration recovery for any logs in the temp folder - if TEMP_LOG_FOLDER.exists(): + # migration recovery for any logs in the temp folder + if TEMP_LOG_FOLDER.exists() and TEMP_LOG_FOLDER != BHOM_LOG_FOLDER: for file in TEMP_LOG_FOLDER.glob("*.log"): file.rename(BHOM_LOG_FOLDER / file.name) - - except Exception as e: + except OSError: BHOM_LOG_FOLDER = TEMP_LOG_FOLDER BHOM_LOG_FOLDER.mkdir(exist_ok=True, parents=True) +def __getattr__(name: str) -> Any: + # INSTALLER_INFO requires pythonnet (the "clr" extra) and loads BHoM assemblies, so only do so when asked for. + if name == "INSTALLER_INFO": + from .installer_info import INSTALLER_INFO + return INSTALLER_INFO + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/Python_Engine/Python/src/python_toolkit/bhom/analytics.py b/Python_Engine/Python/src/python_toolkit/bhom/analytics.py index 7ba81cb9..927e6f4d 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom/analytics.py +++ b/Python_Engine/Python/src/python_toolkit/bhom/analytics.py @@ -1,222 +1,491 @@ -"""BHoM analytics decorator.""" -# pylint: disable=E0401 -import codecs -from dataclasses import dataclass, field -import inspect -from itertools import groupby +"""Lightweight usage analytics for BHoM Python toolkits. + +Decorate public functions with :func:`bhom_analytics` to record how, when and where they are used:: + + from python_toolkit.bhom.analytics import bhom_analytics + + + @bhom_analytics() + def my_method(x: float) -> float: + return x * 2 + +Calls are aggregated in memory (one record per method, project and process) rather than logged one by one, so a +method called thousands of times costs a couple of microseconds per call and produces a single line of output. +Records are flushed to ``/Usage__.jsonl`` when the process exits, and whenever +:data:`FLUSH_INTERVAL_SECONDS` have elapsed or :data:`FLUSH_CALL_THRESHOLD` calls have been made since the last flush. +Each daily file is capped at :data:`MAX_DAILY_LOG_BYTES`. Set the ``DISABLE_BHOM_ANALYTICS`` environment variable to +disable tracking entirely (decorated functions are then returned unwrapped, with no overhead). + +Each line of the log file is a JSON object with the following fields (``schema = "bhom.python.usage/1"``): + +======================== ============================================================================== +``schema`` The record format identifier. Consumers should check this before parsing. +``session`` A random identifier for the Python process that produced the record. +``toolkit`` The top-level package of the decorated function, e.g. ``python_toolkit``. +``module`` The module containing the decorated function. +``method`` The qualified name of the decorated function. +``project`` The project number set via :func:`set_project_number` (or ``""``). +``count`` Number of calls aggregated into this record. +``error_count`` Number of those calls that raised an exception. +``total_seconds`` Total time spent in the function. +``max_seconds`` Longest single call. +``first`` / ``last`` UTC ISO-8601 timestamps of the first and last aggregated calls. +``bhom_version`` The BHoM version the toolkit was installed with. +``python`` The Python version. +``interpreter`` The Python executable. +``errors`` Up to :data:`MAX_ERRORS_PER_METHOD` distinct errors: ``{"type", "message", "count"}``. +======================== ============================================================================== +""" + +from __future__ import annotations + +import atexit import itertools import json import os -from pathlib import Path +import platform import socket import sys +import threading +import time import traceback import uuid +from collections.abc import Callable +from dataclasses import dataclass, field +from datetime import datetime, timezone from functools import wraps -from typing import Any, Callable, Dict, List, Union -from datetime import datetime - -# pylint: enable=E0401 +from itertools import groupby +from pathlib import Path +from typing import Any, TypeVar -from .logging import ANALYTICS_LOGGER, CONSOLE_LOGGER +from . import BHOM_LOG_FOLDER, BHOM_VERSION, DISABLE_ANALYTICS +from .logging import CONSOLE_LOGGER from .util import bson_unix_ticks, bson_unix_ticks_to_datetime -from . import BHOM_VERSION, TOOLKIT_NAME, BHOM_LOG_FOLDER, DISABLE_ANALYTICS -@dataclass -class UsageLogEntry(): - BHoMVersion:str = BHOM_VERSION - BHoM_Guid:uuid.UUID = uuid.uuid4() - CallerName:str = "" - ComponentId:uuid.UUID = uuid.uuid4() - CustomData:Dict = field(default_factory = {"interpreter", sys.executable}) - Errors:List[str] = field(default_factory = []) - FileId:str = "" - FileName:str = "" - Fragments:List[str] = field(default_factory = []) - Name:str = "" - ProjectID:str = "" - SelectedItem:Dict = field(default_factory = {"MethodName": "", "Parameters": [], "TypeName": ""}) - Time:Dict = field(default_factory = {"$date": 0}) - UI:str = "Python" - UiVersion:str = sys.version - _t:str = "BH.oM.Base.UsageLogEntry" +SCHEMA = "bhom.python.usage/1" +FLUSH_INTERVAL_SECONDS = 60.0 +FLUSH_CALL_THRESHOLD = 10_000 +MAX_ERRORS_PER_METHOD = 10 +MAX_ERROR_MESSAGE_LENGTH = 500 +MAX_DAILY_LOG_BYTES = 10 * 1024 * 1024 + +F = TypeVar("F", bound=Callable[..., Any]) + + +def _isoformat(timestamp: float) -> str: + return datetime.fromtimestamp(timestamp, timezone.utc).isoformat(timespec="seconds") + + +class _MethodStats: + """Aggregated usage of a single method within a single process and project.""" + + __slots__ = ( + "count", + "error_count", + "errors", + "first", + "last", + "max_seconds", + "method", + "module", + "project", + "toolkit", + "total_seconds", + ) + + def __init__(self, toolkit: str, module: str, method: str, project: str, now: float) -> None: + self.toolkit = toolkit + self.module = module + self.method = method + self.project = project + self.count = 0 + self.error_count = 0 + self.total_seconds = 0.0 + self.max_seconds = 0.0 + self.first = now + self.last = now + self.errors: dict[tuple[str, str], int] = {} + + def add(self, duration: float, now: float, exception: BaseException | None) -> None: + self.count += 1 + self.total_seconds += duration + if duration > self.max_seconds: + self.max_seconds = duration + self.last = now + if exception is not None: + self.error_count += 1 + key = (type(exception).__name__, str(exception)[:MAX_ERROR_MESSAGE_LENGTH]) + if key in self.errors: + self.errors[key] += 1 + elif len(self.errors) < MAX_ERRORS_PER_METHOD: + self.errors[key] = 1 + + def to_record(self, session: str) -> dict[str, Any]: + return { + "schema": SCHEMA, + "session": session, + "toolkit": self.toolkit, + "module": self.module, + "method": self.method, + "project": self.project, + "count": self.count, + "error_count": self.error_count, + "total_seconds": round(self.total_seconds, 6), + "max_seconds": round(self.max_seconds, 6), + "first": _isoformat(self.first), + "last": _isoformat(self.last), + "bhom_version": BHOM_VERSION, + "python": platform.python_version(), + "interpreter": sys.executable, + "errors": [ + {"type": error_type, "message": message, "count": count} + for (error_type, message), count in self.errors.items() + ], + } + + +class UsageTracker: + """Thread-safe, in-memory aggregator of method usage that periodically flushes to the BHoM log folder.""" + + def __init__(self, log_folder: Path | None = None, register_atexit: bool = True) -> None: + """Create a tracker. + + Args: + log_folder: The folder to write usage logs to. Defaults to the BHoM log folder. + register_atexit: Flush automatically when the Python process exits. + """ + self.log_folder = Path(log_folder) if log_folder is not None else BHOM_LOG_FOLDER + self.session = str(uuid.uuid4()) + self._lock = threading.Lock() + self._stats: dict[tuple[str, str, str], _MethodStats] = {} + self._pending = 0 + self._last_flush = time.monotonic() + self._full_files: set[Path] = set() + if register_atexit: + atexit.register(self.flush) + + def record( + self, + toolkit: str, + module: str, + method: str, + project: str, + duration: float, + exception: BaseException | None = None, + ) -> None: + """Record a single call of a method. + + Args: + toolkit: The top-level package of the method. + module: The module containing the method. + method: The qualified name of the method. + project: The project number the call was made for. + duration: The duration of the call in seconds. + exception: The exception raised by the call, if any. + """ + now = time.time() + key = (module, method, project) + with self._lock: + stats = self._stats.get(key) + if stats is None: + stats = self._stats[key] = _MethodStats(toolkit, module, method, project, now) + stats.add(duration, now, exception) + self._pending += 1 + due = ( + self._pending >= FLUSH_CALL_THRESHOLD or (time.monotonic() - self._last_flush) >= FLUSH_INTERVAL_SECONDS + ) + if due: + self.flush() + + def snapshot(self) -> list[dict[str, Any]]: + """The records that would be written by the next flush, without flushing them.""" + with self._lock: + return [stats.to_record(self.session) for stats in self._stats.values()] + + def flush(self) -> None: + """Write all aggregated records to disk and reset the aggregation. Never raises.""" + with self._lock: + stats, self._stats = self._stats, {} + self._pending = 0 + self._last_flush = time.monotonic() + if not stats: + return + + try: + self.log_folder.mkdir(parents=True, exist_ok=True) + day = datetime.now().strftime("%Y%m%d") + lines: dict[Path, list[str]] = {} + for method_stats in stats.values(): + path = self.log_folder / f"Usage_{method_stats.toolkit}_{day}.jsonl" + record = method_stats.to_record(self.session) + lines.setdefault(path, []).append(json.dumps(record, separators=(",", ":"), default=str)) + + for path, file_lines in lines.items(): + if path.exists() and path.stat().st_size >= MAX_DAILY_LOG_BYTES: + if path not in self._full_files: + self._full_files.add(path) + CONSOLE_LOGGER.warning( + f"Usage log {path} has reached its daily size limit; usage is no longer being recorded to it." + ) + continue + # a single write per file keeps appends from concurrent processes from interleaving + with path.open("a", encoding="utf-8") as file: + file.write("\n".join(file_lines) + "\n") + except Exception: # analytics must never break the calling code + CONSOLE_LOGGER.debug("Failed to write usage analytics.", exc_info=True) + + +_TRACKER = UsageTracker() + + +def get_usage_tracker() -> UsageTracker: + """The process-wide usage tracker used by :func:`bhom_analytics`.""" + return _TRACKER + + +def flush_usage() -> None: + """Immediately write any aggregated usage records to disk.""" + _TRACKER.flush() + + +_PROJECT_NUMBER: str | None = None + + +def set_project_number(project_number: str | None) -> None: + """Set the project number that subsequent usage is attributed to. + + Args: + project_number: The project number, or None to clear it. + """ + global _PROJECT_NUMBER + _PROJECT_NUMBER = project_number - @classmethod - def from_json(cls, json_str:str) -> 'UsageLogEntry': - d = json.loads(json_str) - if "CustomData" not in d: - d["CustomData"] = None - if "Fragments" not in d: - d["Fragments"] = None - return UsageLogEntry(d["BHoMVersion"], d["BHoM_Guid"], d["CallerName"], d["ComponentId"], d["CustomData"], d["Errors"], d["FileId"], d["FileName"], d["Fragments"], d["Name"], d["ProjectID"], d["SelectedItem"], d["Time"], d["UI"], d["UiVersion"]) - -def load_logs_from_file(filename:str) -> List[UsageLogEntry]: - logs:List[UsageLogEntry] = [] - - #adapted from https://stackoverflow.com/questions/30629297/remove-byte-order-mark-from-objects-in-a-list - #due to some files generated by BHoM logs being encoded with utf-8 BOM instead of utf-8 - with open(filename, "r") as f: - lines = f.readlines() - if lines[0].__contains__(codecs.BOM_UTF8.decode(f.encoding)): - # A Byte Order Mark is present - lines[0] = lines[0].strip(codecs.BOM_UTF8.decode(f.encoding)) - for line in lines: - if len(line) != 0: - logs.append(UsageLogEntry.from_json(line)) - return logs +def get_project_number() -> str | None: + """The project number that usage is currently attributed to.""" + return _PROJECT_NUMBER -def summarise_usage_logs(usage_log_entries:List[UsageLogEntry]) -> List[Dict]: - db_entries:List[Dict] = [] - usage_log_entries.sort(key=lambda x: x.ProjectID) +def bhom_analytics( + project_id: Callable[[], str | None] = get_project_number, + disable: bool = DISABLE_ANALYTICS, +) -> Callable[[F], F]: + """Decorator for capturing usage data. - short_bhom_version = ".".join(BHOM_VERSION.split(".", 2)[0:2]) + Args: + project_id: A callable returning the project number to attribute usage to. + disable: Disable tracking for the decorated function (returning it unwrapped). - for file_id, filegroup in groupby(usage_log_entries, lambda x: x.FileId): - filegroup = list(filegroup) - project_id = filegroup[0].ProjectID - filename = filegroup[0].FileName - filegroup.sort(key = lambda x: x.CallerName + str(x.SelectedItem)) + Returns: + The decorator. + """ - for method_name, methodgroup in groupby(filegroup, lambda x: x.CallerName + str(x.SelectedItem)): - methodgroup = list(methodgroup) - first_entry = methodgroup[0] + def decorator(function: F) -> F: + if disable: + return function - db_entries.append({ - "StartTime": bson_unix_ticks_to_datetime(min(methodgroup, key=lambda x: x.Time["$date"]).Time["$date"], short=True), - "EndTime": bson_unix_ticks_to_datetime(max(methodgroup, key=lambda x: x.Time["$date"]).Time["$date"], short=True), - "UI": first_entry.UI, - "UiVersion":first_entry.UiVersion, - "CallerName": first_entry.CallerName, - "SelectedItem": first_entry.SelectedItem, - "Computer": socket.gethostname(), - "Username": os.environ.get("USERNAME"), - "BHoMVersion": short_bhom_version, - "FileId": file_id, - "FileName": filename, - "ProjectID": project_id, - "NbCallingComponents": len(set([a.ComponentId for a in methodgroup])), - "TotalNbCalls": len(methodgroup), - "Errors": list(itertools.chain.from_iterable([x.Errors for x in methodgroup])), - "_t": "BH.oM.BHoMAnalytics.UsageEntry", - "__Time__": datetime.now(), - "_bhomVersion": short_bhom_version - }) + module = function.__module__ + method = function.__qualname__ + toolkit = module.split(".")[0] - return db_entries + def _record(start: float, exception: BaseException | None) -> None: + duration = time.perf_counter() - start + try: + project = project_id() or "" + _TRACKER.record(toolkit, module, method, str(project), duration, exception) + except Exception: # analytics must never break the calling code + CONSOLE_LOGGER.debug("Failed to record usage analytics.", exc_info=True) + + @wraps(function) + def wrapper(*args: Any, **kwargs: Any) -> Any: + start = time.perf_counter() + try: + result = function(*args, **kwargs) + except Exception as exception: + _record(start, exception) + raise + _record(start, None) + return result + + return wrapper # type: ignore[return-value] + + return decorator -def convert_exc_info_to_bhom_error(exc_info): - time = bson_unix_ticks(datetime.now(), short=True) - utcTime = bson_unix_ticks(short=True) - stack_trace = traceback.extract_tb(exc_info[2]) - message = str(exc_info[1]) - Type = "Error" #using string but ideally this would be an enum value. - return {"Time": {"$date": time}, "UtcTime": {"$date": utcTime}, "StackTrace": stack_trace, "Message": message, "Type": Type, "_t": "BH.oM.Base.Debugging.Event"} - -global PROJECT_NUMBER -PROJECT_NUMBER = None - -def set_project_number(project_number: Union[str, None]): - global PROJECT_NUMBER - CONSOLE_LOGGER.debug(f"Setting project number: {PROJECT_NUMBER} to {project_number}") - PROJECT_NUMBER = project_number - -def get_project_number() -> Union[str, None]: - CONSOLE_LOGGER.debug(f"Retrieving project number: {PROJECT_NUMBER}") - return PROJECT_NUMBER - -def bhom_analytics(project_id:Callable = get_project_number, disable:bool = DISABLE_ANALYTICS) -> Callable: - """Decorator for capturing usage data. - Returns - ------- - Callable - The decorated function. +# --------------------------------------------------------------------------------------------------------------------- +# Reading and summarising usage logs +# --------------------------------------------------------------------------------------------------------------------- + + +@dataclass +class UsageLogEntry: + """A legacy (pre ``bhom.python.usage/1``) usage log entry, in the format of ``BH.oM.Base.UsageLogEntry``.""" + + BHoMVersion: str = BHOM_VERSION + BHoM_Guid: uuid.UUID = field(default_factory=uuid.uuid4) + CallerName: str = "" + ComponentId: uuid.UUID = field(default_factory=uuid.uuid4) + CustomData: dict | None = field(default_factory=lambda: {"interpreter": sys.executable}) + Errors: list = field(default_factory=list) + FileId: str = "" + FileName: str = "" + Fragments: list | None = field(default_factory=list) + Name: str = "" + ProjectID: str | None = "" + SelectedItem: dict = field(default_factory=lambda: {"MethodName": "", "Parameters": [], "TypeName": ""}) + Time: dict = field(default_factory=lambda: {"$date": 0}) + UI: str = "Python" + UiVersion: str = sys.version + _t: str = "BH.oM.Base.UsageLogEntry" + + @classmethod + def from_json(cls, json_str: str) -> UsageLogEntry: + """Create an entry from a JSON string.""" + d = json.loads(json_str) + return cls.from_dict(d) + + @classmethod + def from_dict(cls, d: dict[str, Any]) -> UsageLogEntry: + """Create an entry from a deserialised JSON object.""" + return UsageLogEntry( + d["BHoMVersion"], + d["BHoM_Guid"], + d["CallerName"], + d["ComponentId"], + d.get("CustomData"), + d["Errors"], + d["FileId"], + d["FileName"], + d.get("Fragments"), + d["Name"], + d["ProjectID"], + d["SelectedItem"], + d["Time"], + d["UI"], + d["UiVersion"], + ) + + +def load_logs_from_file(filename: str | Path) -> list[UsageLogEntry | dict[str, Any]]: + """Load a usage log file. + + Args: + filename: The log file to load. + + Returns: + One item per line: a dict for ``bhom.python.usage`` records, or a :class:`UsageLogEntry` for legacy lines. """ + logs: list[UsageLogEntry | dict[str, Any]] = [] + # utf-8-sig, as some files generated by BHoM logs are encoded with a byte order mark + with open(filename, encoding="utf-8-sig") as f: + for line in f: + line = line.strip() + if not line: + continue + d = json.loads(line) + if str(d.get("schema", "")).startswith("bhom.python.usage/"): + logs.append(d) + else: + logs.append(UsageLogEntry.from_dict(d)) + return logs - _componentId = uuid.uuid4() - def decorator(function: Callable): - """A decorator to capture usage data for called methods/functions. +def _file_id(project: str | None) -> str: + return str(uuid.uuid3(uuid.NAMESPACE_OID, project or "")) - Arguments - --------- - function : Callable - The function to decorate. - Returns - ------- - Callable - The decorated function. - """ +def summarise_usage_logs(usage_log_entries: list[UsageLogEntry | dict[str, Any]]) -> list[dict[str, Any]]: + """Summarise usage logs into one ``BH.oM.BHoMAnalytics.UsageEntry`` per project and method. - @wraps(function) - def wrapper(*args, **kwargs) -> Any: - """A wrapper around the function that captures usage analytics.""" - - if disable: - CONSOLE_LOGGER.debug("bhom_analytics is curently disabled.") - return function(*args, **kwargs) - - _id = uuid.uuid4() - - #for now for file IDs, generate one using the project ID - pid = project_id() - if pid == None: - pid = "" - - file_id = uuid.uuid3(uuid.NAMESPACE_OID, pid) - - # get the data being passed to the function, expected dtype and return type - argspec = inspect.getfullargspec(function)[-1] - argspec.pop("return", None) - - _args = [f'{{"_t": "{argspec[k]}", "Name": "{k}"}}' for k in argspec.keys()] - - exec_metadata = { - "BHoMVersion": BHOM_VERSION, - "BHoM_Guid": _id, - "CallerName": function.__name__, - "ComponentId": _componentId, - "CustomData": {"interpreter": sys.executable}, - "Errors": [], - "FileId": str(file_id), - "FileName": str(file_id), - "Fragments": [], - "Name": "", - "ProjectID": project_id(), - "SelectedItem": { - "MethodName": function.__name__, - "Parameters": _args, - "TypeName": f"{function.__module__}.{function.__qualname__}" - }, - "Time": { - "$date": bson_unix_ticks(short=True), - }, - "UI": "Python", - "UiVersion": sys.version, - "_t": "BH.oM.Base.UsageLogEntry", - } + Args: + usage_log_entries: Entries as returned by :func:`load_logs_from_file` (legacy and current formats may be mixed). - try: - result = function(*args, **kwargs) - except Exception as exc: # pylint: disable=broad-except - exec_metadata["Errors"].extend(convert_exc_info_to_bhom_error(sys.exc_info())) - raise exc - finally: - log_file = BHOM_LOG_FOLDER / f"Usage_{function.__module__.split('.')[0]}_{datetime.now().strftime('%Y%m%d')}.log" + Returns: + The summarised entries. + """ + short_bhom_version = ".".join(BHOM_VERSION.split(".", 2)[0:2]) + common = { + "Computer": socket.gethostname(), + "Username": os.environ.get("USERNAME"), + "BHoMVersion": short_bhom_version, + "_t": "BH.oM.BHoMAnalytics.UsageEntry", + "_bhomVersion": short_bhom_version, + } - if ANALYTICS_LOGGER.handlers[0].baseFilename != str(log_file): - ANALYTICS_LOGGER.handlers[0].close() - ANALYTICS_LOGGER.handlers[0].baseFilename = str(log_file) + legacy = [entry for entry in usage_log_entries if isinstance(entry, UsageLogEntry)] + records = [entry for entry in usage_log_entries if isinstance(entry, dict)] - ANALYTICS_LOGGER.info( - json.dumps(exec_metadata, default=str, indent=None) - ) + db_entries: list[dict[str, Any]] = [] - return result + legacy.sort(key=lambda x: (x.FileId, x.CallerName + str(x.SelectedItem))) + for file_id, filegroup in groupby(legacy, lambda x: x.FileId): + filegroup = list(filegroup) + for _, methodgroup in groupby(filegroup, lambda x: x.CallerName + str(x.SelectedItem)): + methodgroup = list(methodgroup) + first_entry = methodgroup[0] + db_entries.append( + { + **common, + "StartTime": bson_unix_ticks_to_datetime(min(x.Time["$date"] for x in methodgroup), short=True), + "EndTime": bson_unix_ticks_to_datetime(max(x.Time["$date"] for x in methodgroup), short=True), + "UI": first_entry.UI, + "UiVersion": first_entry.UiVersion, + "CallerName": first_entry.CallerName, + "SelectedItem": first_entry.SelectedItem, + "FileId": file_id, + "FileName": first_entry.FileName, + "ProjectID": first_entry.ProjectID, + "NbCallingComponents": len({a.ComponentId for a in methodgroup}), + "TotalNbCalls": len(methodgroup), + "Errors": list(itertools.chain.from_iterable(x.Errors for x in methodgroup)), + "__Time__": datetime.now(), + } + ) + + def record_key(record: dict[str, Any]) -> tuple[str, str, str]: + return (record.get("project", ""), record["module"], record["method"]) + + records.sort(key=record_key) + for (project, module, method), group in groupby(records, record_key): + group = list(group) + errors: dict[tuple[str, str], int] = {} + for record in group: + for error in record.get("errors", []): + key = (error["type"], error["message"]) + errors[key] = errors.get(key, 0) + error.get("count", 1) + db_entries.append( + { + **common, + "StartTime": datetime.fromisoformat(min(r["first"] for r in group)).replace(tzinfo=None), + "EndTime": datetime.fromisoformat(max(r["last"] for r in group)).replace(tzinfo=None), + "UI": "Python", + "UiVersion": group[0].get("python", ""), + "CallerName": method, + "SelectedItem": { + "MethodName": method.split(".")[-1], + "Parameters": [], + "TypeName": f"{module}.{method}", + }, + "FileId": _file_id(project), + "FileName": _file_id(project), + "ProjectID": project, + "NbCallingComponents": len({r.get("session") for r in group}), + "TotalNbCalls": sum(r.get("count", 0) for r in group), + "Errors": [{"Type": t, "Message": m, "Count": c} for (t, m), c in errors.items()], + "__Time__": datetime.now(), + } + ) + + return db_entries - return wrapper - return decorator +def convert_exc_info_to_bhom_error(exc_info: tuple) -> dict[str, Any]: + """Convert ``sys.exc_info()`` into a ``BH.oM.Base.Debugging.Event`` dictionary.""" + return { + "Time": {"$date": bson_unix_ticks(datetime.now(), short=True)}, + "UtcTime": {"$date": bson_unix_ticks(short=True)}, + "StackTrace": "".join(traceback.format_tb(exc_info[2])), + "Message": str(exc_info[1]), + "Type": "Error", + "_t": "BH.oM.Base.Debugging.Event", + } diff --git a/Python_Engine/Python/src/python_toolkit/bhom/bhom_object.py b/Python_Engine/Python/src/python_toolkit/bhom/bhom_object.py index 10785de5..4444b21c 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom/bhom_object.py +++ b/Python_Engine/Python/src/python_toolkit/bhom/bhom_object.py @@ -1,37 +1,39 @@ -from base64 import decode +"""Conversion between Python objects and BHoM JSON, as produced and consumed by the BHoM serialiser.""" + import copy +import json +import re +import sys +import uuid from ctypes import ArgumentError from datetime import datetime -from json import encoder +from json import JSONDecoder, JSONEncoder from pathlib import Path -import uuid -import re -from typing import Any, List, Dict, Union -import json -from json import JSONEncoder, JSONDecoder -from .logging import CONSOLE_LOGGER +from typing import Any, Union + from . import BHOM_VERSION +from .logging import CONSOLE_LOGGER from .util import bson_unix_ticks, bson_unix_ticks_to_datetime -import pandas as pd -import numpy as np BHOM_SHORT_VERSION = ".".join(BHOM_VERSION.split(".")[0:2]) + def convert_pascal_to_camel(s: str): """Converts a string to camel_case.""" - sections = re.split("(?<=.)(?=[A-Z])", s) #zero-length match before capitals, skipping capital at the 0th index + sections = re.split("(?<=.)(?=[A-Z])", s) # zero-length match before capitals, skipping capital at the 0th index parts = [] for sec in sections: parts.append(sec.lower()) return "_".join(parts) + def convert_camel_to_pascal(s: str): """Converts a string to PascalCase, ignoring _ if it is the first character.""" - sections = re.split(r'(?<=.)_', s) #match all `_` except if it is the first character. + sections = re.split(r"(?<=.)_", s) # match all `_` except if it is the first character. parts = [] - for sec in sections: #capitalise each section unless the section is empty (in which case, append an underscore) or the section starts with an underscore (first section can begin with _) + for sec in sections: # capitalise each section unless the section is empty (in which case, append an underscore) or the section starts with an underscore (first section can begin with _) if sec == "": parts.append("_") continue @@ -41,68 +43,77 @@ def convert_camel_to_pascal(s: str): parts.append(sec.capitalize()) - return ''.join(parts) + return "".join(parts) + class BHoMJSONDecoder(JSONDecoder): + """Decode BHoM JSON into BHoMObject/IObject instances (and datetimes).""" + def __init__(self, *args, **kwargs): - json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs) + json.JSONDecoder.__init__(self, *args, object_hook=self.object_hook, **kwargs) def object_hook(self, d): + """Convert a decoded JSON object into the matching Python object.""" if "$date" in d: CONSOLE_LOGGER.debug(f"deserialising timestamp {d}") return bson_unix_ticks_to_datetime(d["$date"]) if "_t" not in d: - CONSOLE_LOGGER.debug(f"BHoMJSONDecoder could not convert the following dictionary into a BHoMObject due to a missing '_t' property. Falling back to dictionary: {d}") + CONSOLE_LOGGER.debug( + f"BHoMJSONDecoder could not convert the following dictionary into a BHoMObject due to a missing '_t' property. Falling back to dictionary: {d}" + ) return self.deserialise_unknown(d) - - props = { - "_t": d.pop("_t"), - "_bhom_version": d.pop("_bhomVersion", BHOM_SHORT_VERSION) - } + + props = {"_t": d.pop("_t"), "_bhom_version": d.pop("_bhomVersion", BHOM_SHORT_VERSION)} if (props["_bhom_version"] is not None) and (props["_bhom_version"] != BHOM_SHORT_VERSION): - CONSOLE_LOGGER.warning(f"The bhom version specified in the encoded json ({props['_bhom_version']}) is different from the BHoM version that python_toolkit was installed with ({BHOM_SHORT_VERSION}). There may be versioning issues with this object. Consider deserialising and then serialising again with the BHoM serialiser to get the correct version, or update BHoM to the correct version.") + CONSOLE_LOGGER.warning( + f"The bhom version specified in the encoded json ({props['_bhom_version']}) is different from the BHoM version that python_toolkit was installed with ({BHOM_SHORT_VERSION}). There may be versioning issues with this object. Consider deserialising and then serialising again with the BHoM serialiser to get the correct version, or update BHoM to the correct version." + ) if d.get("BHoM_Guid", None) is not None: - #deserialise as BHoM Object + # deserialise as BHoM Object - #get default BHoMObject properties and replace with defaults if not present + # get default BHoMObject properties and replace with defaults if not present props["name"] = d.pop("Name", "") props["bhom_guid"] = uuid.UUID(d.pop("BHoM_Guid")) props["tags"] = d.pop("Tags", []) props["fragments"] = d.pop("Fragments", []) props["custom_data"] = d.pop("CustomData", {}) - #convert all other properties to camel_case as python users expect + # convert all other properties to camel_case as python users expect for prop_name in d: props[convert_pascal_to_camel(prop_name)] = d[prop_name] return self.deserialise_unknown(BHoMObject(**props)) else: - if props["_t"].startswith("System.Collections.Generic.List"): #this handles when the BHoM serialiser makes generic lists from CustomObject list properties, which get converted to a dictionary. The BHoM serialiser does recognise lists if it can find the object definition via reflection. + if props[ + "_t" + ].startswith( + "System.Collections.Generic.List" + ): # this handles when the BHoM serialiser makes generic lists from CustomObject list properties, which get converted to a dictionary. The BHoM serialiser does recognise lists if it can find the object definition via reflection. return d["_v"] - #deserialise as IObject + # deserialise as IObject for prop_name in d: props[convert_pascal_to_camel(prop_name)] = d[prop_name] return self.deserialise_unknown(IObject(**props)) - def deserialise_unknown(self, obj: Union['IObject', 'BHoMObject', dict]): + def deserialise_unknown(self, obj: Union["IObject", "BHoMObject", dict]): """Override this method in a subclass to add extra object hook on top of the existing method. If the object is an object serialised by the BHoM serialiser, the output object will be a BHoMObject or IObject, so use isinstance() to select.""" return obj + class BHoMJSONEncoder(JSONEncoder): + """Encode BHoMObject/IObject instances and common Python types as BHoM JSON.""" + def default(self, o): + """Convert an object that json cannot serialise natively into a serialisable form.""" if isinstance(o, BHoMObject): - #initialise special BHoMObject properties + # initialise special BHoMObject properties - props = { - "Name": o.name, - "BHoM_Guid": str(o.bhom_guid), - "_t": o._t - } + props = {"Name": o.name, "BHoM_Guid": str(o.bhom_guid), "_t": o._t} if len(o.tags) > 0: props["Tags"] = o.tags @@ -116,7 +127,7 @@ def default(self, o): if o._bhom_version is not None: props["_bhomVersion"] = o._bhom_version - #get property names with reflection and convert all properties to PascalCase as the BHoM serialiser expects + # get property names with reflection and convert all properties to PascalCase as the BHoM serialiser expects for prop_name, value in vars(o).copy().items(): if prop_name in ["name", "bhom_guid", "tags", "fragments", "custom_data", "_t", "_bhom_version"]: continue @@ -125,9 +136,7 @@ def default(self, o): return props elif isinstance(o, IObject): - props = { - "_t": o._t - } + props = {"_t": o._t} if o._bhom_version is not None: props["_bhomVersion"] = o._bhom_version @@ -139,48 +148,58 @@ def default(self, o): props[convert_camel_to_pascal(prop_name)] = value return props - #handle common non-serialisable types - elif isinstance(o, uuid.UUID): #UUID object is not json serialisable by default + # handle common non-serialisable types + elif isinstance(o, uuid.UUID): # UUID object is not json serialisable by default return str(o) - elif isinstance(o, pd.DatetimeIndex): + + # pandas/numpy are optional: an object can only be one of their types if they have already been imported + pd = sys.modules.get("pandas") + np = sys.modules.get("numpy") + if pd is not None and isinstance(o, pd.DatetimeIndex): return [date.isoformat() for date in o] - elif isinstance(o, np.ndarray): + elif np is not None and isinstance(o, np.ndarray): return o.tolist() - elif isinstance(o, pd.Timestamp): + elif pd is not None and isinstance(o, pd.Timestamp): return {"$date": bson_unix_ticks(o.to_pydatetime(), True)} - elif isinstance(o, datetime): + elif pd is not None and isinstance(o, pd.Series): + return dict(zip(o.index.astype(str), o, strict=True)) + + if isinstance(o, datetime): return {"$date": bson_unix_ticks(o, True)} - elif isinstance(o, pd.Series): - return dict(zip(o.index.astype(str), o)) elif isinstance(o, Path): - return { "FileName": str(o.name), "Directory": str(o.parent), "_t": "BH.oM.Adapter.FileSettings", "BHoM_Guid": str(uuid.uuid4()) } + return { + "FileName": str(o.name), + "Directory": str(o.parent), + "_t": "BH.oM.Adapter.FileSettings", + "BHoM_Guid": str(uuid.uuid4()), + } - return self.serialise_unknown(o) #if the object is unknown at this point, call serialise_unknown to allow subclasses to add their own serialisation logic. + return self.serialise_unknown( + o + ) # if the object is unknown at this point, call serialise_unknown to allow subclasses to add their own serialisation logic. - def serialise_unknown(self, obj: Any) -> Union[Dict[str, str], str, List[str], Any]: - """ - This is called by the BHoMJSONEncoder to serialise unknown objects so that the BHoM can handle them if they exist as BHoM Objects in c# but not in python (i.e. an object from an external library). + def serialise_unknown(self, obj: Any) -> dict[str, str] | str | list[str] | Any: + """This is called by the BHoMJSONEncoder to serialise unknown objects so that the BHoM can handle them if they exist as BHoM Objects in c# but not in python (i.e. an object from an external library). Override this method in a sub class with its own logic, and call super().serialise_unknown(obj) for objects that are unknown, or do not wish to serialise. The following objects won't be passed to this method: BHoMObject, IObject, uuid.UUID, pandas.DatetimeIndex, numpy.ndarray, pandas.Timestamp, pandas.Series, pathlib.Path """ - return super(type(self), self).default(obj) #fallback to default json decoder (ValueError) if object is not a BHoMObject or common serialisable type. + return super(type(self), self).default( + obj + ) # fallback to default json decoder (ValueError) if object is not a BHoMObject or common serialisable type. + class IObject: """More generic version of BHoMObject, for non-native objects serialised by the BHoM serialiser, but do not inherit from BHoMObject.""" + _t: str _bhom_version: str - def __init__( - self, - _t: str, - _bhom_version: str = None, - **kwargs - ) -> 'IObject': + def __init__(self, _t: str, _bhom_version: str | None = None, **kwargs) -> "IObject": self._t = _t self._bhom_version = _bhom_version - - #set properties with reflection. + + # set properties with reflection. for kwarg in kwargs: setattr(self, kwarg, kwargs[kwarg]) @@ -193,66 +212,76 @@ def __eq__(self, other) -> bool: if self._t != other._t: return False - + vself = vars(self).copy() vother = vars(other).copy() - #ignore these properties when comparing by property. + # ignore these properties when comparing by property. ignore = ["_bhom_version"] _ = [(vself.pop(p, None), vother.pop(p, None)) for p in ignore] return vself == vother @classmethod - def from_json(cls, j: str, decoder_class: type = BHoMJSONDecoder) -> 'IObject': + def from_json(cls, j: str, decoder_class: type = BHoMJSONDecoder) -> "IObject": + """Deserialise an object from BHoM JSON.""" obj = json.loads(j, cls=decoder_class) - if not isinstance(obj, cls): #this only tests that the top level object was deserialised correctly, if there are problems with deep properties, change the CONSOLE_LOGGER log level to debug. + if not isinstance( + obj, cls + ): # this only tests that the top level object was deserialised correctly, if there are problems with deep properties, change the CONSOLE_LOGGER log level to debug. raise TypeError("The object provided does not deserialise to a valid BHoM object.") return obj - + def to_json(self, encoder_class: type = BHoMJSONEncoder) -> str: + """Serialise this object to BHoM JSON.""" return json.dumps(self, cls=encoder_class) @classmethod - def from_dict(cls, d: dict) -> 'IObject': + def from_dict(cls, d: dict) -> "IObject": + """Create an object from a dictionary of its properties.""" try: - return cls(**d) #should be valid as long as the dictionary has all necessary entries. + return cls(**d) # should be valid as long as the dictionary has all necessary entries. except ArgumentError as ae: - raise ArgumentError("Input dictionary was missing some required arguments, see traceback for more information.") from ae + raise ArgumentError( + "Input dictionary was missing some required arguments, see traceback for more information." + ) from ae def to_dict(self, encoder_class: type = BHoMJSONEncoder) -> dict: """Convert this IObject to a dictionary via deep copying vars(self).""" return copy.deepcopy(vars(self)) + class BHoMObject(IObject): + """A Python representation of a BHoM object (one with a BHoM_Guid).""" + name: str bhom_guid: uuid.UUID - tags: List[str] - fragments: List[Dict[str, object]] - custom_data: Dict[str, object] + tags: list[str] + fragments: list[dict[str, object]] + custom_data: dict[str, object] def __init__( self, - _t: str, #don't make default, as subclasses of this class should set this with super().__init__ + _t: str, # don't make default, as subclasses of this class should set this with super().__init__ name: str = "", - bhom_guid: uuid.UUID = uuid.uuid4(), - tags: List[str] = [], - fragments: List[Dict[str, object]] = [], - custom_data: Dict[str, object] = {}, - _bhom_version: str = None, - **kwargs - ) -> 'BHoMObject': + bhom_guid: uuid.UUID | None = None, + tags: list[str] | None = None, + fragments: list[dict[str, object]] | None = None, + custom_data: dict[str, object] | None = None, + _bhom_version: str | None = None, + **kwargs, + ) -> "BHoMObject": self._t = _t self.name = name - self.bhom_guid = bhom_guid - self.fragments = fragments - self.tags = tags - self.custom_data = custom_data + self.bhom_guid = bhom_guid if bhom_guid is not None else uuid.uuid4() + self.fragments = fragments if fragments is not None else [] + self.tags = tags if tags is not None else [] + self.custom_data = custom_data if custom_data is not None else {} self._bhom_version = _bhom_version - #set non-CustomData properties with reflection. + # set non-CustomData properties with reflection. for kwarg in kwargs: setattr(self, kwarg, kwargs[kwarg]) @@ -269,7 +298,7 @@ def __eq__(self, other) -> bool: vself = vars(self).copy() vother = vars(other).copy() - #ignore these properties when comparing by property. + # ignore these properties when comparing by property. ignore = ["bhom_guid", "_bhom_version"] _ = [(vself.pop(p, None), vother.pop(p, None)) for p in ignore] @@ -277,26 +306,34 @@ def __eq__(self, other) -> bool: @classmethod def from_json(cls, j: str, decoder_class: type = BHoMJSONDecoder): + """Deserialise an object from BHoM JSON, converting to this class if it is a subclass.""" obj = json.loads(j, cls=decoder_class) if isinstance(obj, list): - CONSOLE_LOGGER.warning("The root element of the JSON provided was a list, assuming that the first item is the desired object. If you intended to deserialise a list, please use the `.from_json_array(j)` method instead.") + CONSOLE_LOGGER.warning( + "The root element of the JSON provided was a list, assuming that the first item is the desired object. If you intended to deserialise a list, please use the `.from_json_array(j)` method instead." + ) obj = obj[0] if issubclass(cls, BHoMObject) and cls != BHoMObject: obj = cls._from_bhom_object(obj) - if not isinstance(obj, cls): #this only tests that the top level object was deserialised correctly, if there are problems with deep properties, change the CONSOLE_LOGGER log level to debug. + if not isinstance( + obj, cls + ): # this only tests that the top level object was deserialised correctly, if there are problems with deep properties, change the CONSOLE_LOGGER log level to debug. raise TypeError("The object provided does not deserialise to a valid BHoM object.") return obj - + @classmethod def from_json_array(cls, j: str, decoder_class: type = BHoMJSONDecoder): + """Deserialise a list of objects from a BHoM JSON array.""" objs = json.loads(j, cls=decoder_class) if not isinstance(objs, list): - raise TypeError("The root element of the JSON provided was not a JSON array. Perhaps you intended to use `.from_json(j)` instead?") + raise TypeError( + "The root element of the JSON provided was not a JSON array. Perhaps you intended to use `.from_json(j)` instead?" + ) out = [] for obj in objs: @@ -308,5 +345,5 @@ def from_json_array(cls, j: str, decoder_class: type = BHoMJSONDecoder): return out @classmethod - def _from_bhom_object(cls, o: 'BHoMObject'): - return cls(**vars(o).copy()) #assuming that the sub class is correctly set up, then this should work \ No newline at end of file + def _from_bhom_object(cls, o: "BHoMObject"): + return cls(**vars(o).copy()) # assuming that the sub class is correctly set up, then this should work diff --git a/Python_Engine/Python/src/python_toolkit/bhom/decorators/__init__.py b/Python_Engine/Python/src/python_toolkit/bhom/decorators/__init__.py index 70cea52d..b880027d 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom/decorators/__init__.py +++ b/Python_Engine/Python/src/python_toolkit/bhom/decorators/__init__.py @@ -1 +1,3 @@ -from ._bhom_callable_decorator import bhom_wrapper \ No newline at end of file +"""Decorators for exposing Python methods to BHoM (C#).""" + +from ._bhom_callable_decorator import bhom_wrapper diff --git a/Python_Engine/Python/src/python_toolkit/bhom/decorators/_bhom_callable_decorator.py b/Python_Engine/Python/src/python_toolkit/bhom/decorators/_bhom_callable_decorator.py index 436ebcb9..b66d547b 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom/decorators/_bhom_callable_decorator.py +++ b/Python_Engine/Python/src/python_toolkit/bhom/decorators/_bhom_callable_decorator.py @@ -1,19 +1,29 @@ -import json -from typing import Any, Callable, Union, Dict +import json +from collections.abc import Callable from functools import wraps +from typing import Any, ClassVar + from ..bhom_object import CONSOLE_LOGGER, BHoMJSONDecoder, BHoMJSONEncoder, BHoMObject, IObject -class _BHoMWrapper: - _registered_methods: Dict[str, Callable] = {} - def bhom_callable(self, identifier: str, argument_types:Dict[str, type] = {}, encoder_cls: type = BHoMJSONEncoder, decoder_cls: type = BHoMJSONDecoder): +class _BHoMWrapper: + _registered_methods: ClassVar[dict[str, Callable]] = {} + + def bhom_callable( + self, + identifier: str, + argument_types: dict[str, type] | None = None, + encoder_cls: type = BHoMJSONEncoder, + decoder_cls: type = BHoMJSONDecoder, + ): """Decorator for functions to be made callable from BHoM C# methods/adapters. Note: methods that this wraps must not have "__input_json__" as a default kwarg, as this is used internally to allow BHoM adapters to call the method. when __input_json__ is set, this will cause the method to always output BHoM style json (using the encoder_cls provided to this decorator) - + Args: + identifier (str): the identifier BHoM uses to call the method (see ``python_toolkit.bhom.run_wrapped``). argument_types (dict[str, type]): this is a dictionary that is used to map the argument names to types (specifically BHoMObject types) to subclasses of BHoMObjects. For example, if you have a class that is a subclass of BHoMObject, the default serialiser will only deserialise json to a BHoMObject. To go the extra step to get your class, you must provide the type in this dictionary to allow the wrapper to convert the BHoMObject type to your desired type. @@ -22,35 +32,40 @@ def bhom_callable(self, identifier: str, argument_types:Dict[str, type] = {}, en decoder_cls (JSONDecoder): same as encoder_cls but for JSONDecoder. """ + def decorator(function: Callable): @wraps(function) - def wrapper(*args, **kwargs) -> Union[str, Any]: + def wrapper(*args, **kwargs) -> str | Any: - do_wrap:bool = False + do_wrap: bool = False if "__input_json__" in kwargs and len(args) == 0: do_wrap = True - - #get dictionary from input as file path or json like string. + + # get dictionary from input as file path or json like string. input_json = kwargs.pop("__input_json__") - if not input_json.startswith("{"): #assume it's a path - with open(input_json, "r") as f: + if not input_json.startswith("{"): # assume it's a path + with open(input_json) as f: input_json = f.read() try: - json_kwargs: Union[dict, IObject] = json.loads(input_json, cls=decoder_cls) + json_kwargs: dict | IObject = json.loads(input_json, cls=decoder_cls) if isinstance(json_kwargs, IObject): json_kwargs = json_kwargs.to_dict() - except: - CONSOLE_LOGGER.error("Could not load JSON from file or string due to invalid JSON. Attempting to run with given args and kwargs.", exc_info=1) - - #update kwargs with json + except (json.JSONDecodeError, TypeError, ValueError): + CONSOLE_LOGGER.error( + "Could not load JSON from file or string due to invalid JSON. Attempting to run with given args and kwargs.", + exc_info=1, + ) + json_kwargs = {} + + # update kwargs with json for kwarg_name in json_kwargs: val = json_kwargs[kwarg_name] - if kwarg_name in argument_types: + if argument_types and kwarg_name in argument_types: t = argument_types[kwarg_name] if issubclass(t, BHoMObject) and type(json_kwargs[kwarg_name]) is BHoMObject: @@ -61,14 +76,14 @@ def wrapper(*args, **kwargs) -> Union[str, Any]: rtn = function(*args, **kwargs) if do_wrap: - #don't bother serialising if the method already returns a string. + # don't bother serialising if the method already returns a string. if isinstance(rtn, str): return rtn json_rtn = json.dumps(rtn, cls=encoder_cls) return json_rtn - + return rtn self._registered_methods[identifier] = wrapper @@ -80,10 +95,13 @@ def get_registered_method(self, method_identifier: str): method = self._registered_methods.get(method_identifier, None) if method is None: - raise NotImplementedError(f"The requested method {method_identifier} is not implemented or could not be found.") + raise NotImplementedError( + f"The requested method {method_identifier} is not implemented or could not be found." + ) return method -#the registered methods are stored as a class attribute, so this isn't actually needed -#but this is easier to use, otherwise a new instance must be created every time a method needs to be wrapped -bhom_wrapper = _BHoMWrapper() \ No newline at end of file + +# the registered methods are stored as a class attribute, so this isn't actually needed +# but this is easier to use, otherwise a new instance must be created every time a method needs to be wrapped +bhom_wrapper = _BHoMWrapper() diff --git a/Python_Engine/Python/src/python_toolkit/bhom/installer_info.py b/Python_Engine/Python/src/python_toolkit/bhom/installer_info.py index 10f1b76d..da489c21 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom/installer_info.py +++ b/Python_Engine/Python/src/python_toolkit/bhom/installer_info.py @@ -1,17 +1,23 @@ +"""Information about the installed BHoM, read from the BHoM .NET assemblies (requires the "clr" extra).""" + +import json import os import sys -import json -import clr +from .._optional import require_extra + +require_extra("clr", "clr") + +import clr # noqa: E402 -#append assemblies dir +# append assemblies dir sys.path.append(os.path.expandvars("%ProgramData%\\BHoM\\Assemblies")) -#add required CLR references (dotnet dlls) +# add required CLR references (dotnet dlls) clr.AddReference("UI_Engine") clr.AddReference("Serialiser_Engine") -from BH.Engine.UI import Query -from BH.Engine.Serialiser import Convert +from BH.Engine.Serialiser import Convert # noqa: E402 +from BH.Engine.UI import Query # noqa: E402 -INSTALLER_INFO = json.loads(Convert.ToJson(Query.Information())) \ No newline at end of file +INSTALLER_INFO = json.loads(Convert.ToJson(Query.Information())) diff --git a/Python_Engine/Python/src/python_toolkit/bhom/logging/__init__.py b/Python_Engine/Python/src/python_toolkit/bhom/logging/__init__.py index 4e9eae56..595c9fe6 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom/logging/__init__.py +++ b/Python_Engine/Python/src/python_toolkit/bhom/logging/__init__.py @@ -1,2 +1,6 @@ +"""Logging utilities shared by all BHoM Python toolkits.""" + +from .console import CONSOLE_LOGGER, get_logger from .file import ANALYTICS_LOGGER -from .console import CONSOLE_LOGGER + +__all__ = ["ANALYTICS_LOGGER", "CONSOLE_LOGGER", "get_logger"] diff --git a/Python_Engine/Python/src/python_toolkit/bhom/logging/console.py b/Python_Engine/Python/src/python_toolkit/bhom/logging/console.py index 029dc9ab..d0590a4e 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom/logging/console.py +++ b/Python_Engine/Python/src/python_toolkit/bhom/logging/console.py @@ -1,21 +1,36 @@ -"""Logging utilities for BHoM analytics.""" +"""Console logging shared by all BHoM Python toolkits.""" -# pylint: disable=E0401 import logging import sys -# pylint: enable=E0401 - from .. import TOOLKIT_NAME -level = logging.INFO +LOG_FORMAT = "%(name)s - %(levelname)s - %(message)s" + + +def get_logger(name: str, level: int = logging.INFO) -> logging.Logger: + """Get a console logger using the standard BHoM format. + + Downstream toolkits should use this rather than configuring their own handlers, so that log formatting + is controlled in one place. Calling this repeatedly with the same name returns the same logger without + adding duplicate handlers. + + Args: + name: The logger name, typically the toolkit name (e.g. "LadybugTools_Toolkit"). + level: The initial logging level. + + Returns: + The configured logger. + """ + logger = logging.getLogger(f"{name}[console]") + if not any(getattr(handler, "_bhom_console", False) for handler in logger.handlers): + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter(logging.Formatter(LOG_FORMAT)) + handler._bhom_console = True # type: ignore[attr-defined] + logger.addHandler(handler) + logger.setLevel(level) + logger.propagate = False + return logger -formatter = logging.Formatter("%(name)s - %(levelname)s - %(message)s") -handler = logging.StreamHandler(sys.stdout) -handler.setLevel(level) -handler.setFormatter(formatter) -CONSOLE_LOGGER = logging.getLogger(f"{TOOLKIT_NAME}[console]") -CONSOLE_LOGGER.propagate = False -CONSOLE_LOGGER.setLevel(level) -CONSOLE_LOGGER.addHandler(handler) +CONSOLE_LOGGER = get_logger(TOOLKIT_NAME) diff --git a/Python_Engine/Python/src/python_toolkit/bhom/logging/file.py b/Python_Engine/Python/src/python_toolkit/bhom/logging/file.py index 0516311d..893e76b4 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom/logging/file.py +++ b/Python_Engine/Python/src/python_toolkit/bhom/logging/file.py @@ -1,14 +1,10 @@ -"""Logging utilities for BHoM analytics.""" +"""File logging for the Python_Toolkit (written lazily, only when something is logged).""" -# pylint: disable=E0401 import logging from datetime import datetime from logging.handlers import RotatingFileHandler -# pylint: enable=E0401 - - -from .. import TOOLKIT_NAME, BHOM_LOG_FOLDER +from .. import BHOM_LOG_FOLDER, TOOLKIT_NAME formatter = logging.Formatter("%(message)s") handler = RotatingFileHandler( @@ -17,7 +13,7 @@ maxBytes=25 * 1024 * 1024, # 25mb max before file overwritten backupCount=1, encoding="utf-8", - delay=True, # wait until all logs collected before writing + delay=True, # do not create the file until something is logged ) handler.setLevel(logging.DEBUG) handler.setFormatter(formatter) diff --git a/Python_Engine/Python/src/python_toolkit/bhom/run_wrapped.py b/Python_Engine/Python/src/python_toolkit/bhom/run_wrapped.py index 2a21c362..52befcbf 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom/run_wrapped.py +++ b/Python_Engine/Python/src/python_toolkit/bhom/run_wrapped.py @@ -1,7 +1,16 @@ -from .decorators import bhom_wrapper -from . import wrapped +"""Entry point used by BHoM (C#) to run a registered Python method with JSON input.""" -def run_wrapped(identifier: str, json: str): +from . import wrapped # noqa: F401 (imported for its side effect: registering bhom_callable methods) +from .decorators import bhom_wrapper + + +def run_wrapped(identifier: str, json: str) -> None: + """Run a method registered with ``bhom_callable`` and print its JSON result to stdout. + + Args: + identifier: The identifier the method was registered with. + json: The method's keyword arguments, as a JSON string or the path to a JSON file. + """ method = bhom_wrapper.get_registered_method(identifier) - print(method(__input_json__ = json)) \ No newline at end of file + print(method(__input_json__=json)) diff --git a/Python_Engine/Python/src/python_toolkit/bhom/util.py b/Python_Engine/Python/src/python_toolkit/bhom/util.py index 1c06ab0d..ef597b75 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom/util.py +++ b/Python_Engine/Python/src/python_toolkit/bhom/util.py @@ -1,31 +1,46 @@ """General utility functions.""" -# pylint: disable=E0401 -from datetime import datetime, timedelta -# pylint: enable=E0401 +from datetime import datetime, timedelta, timezone -def bson_unix_ticks(date_time: datetime = datetime.utcnow(), short: bool = False) -> int: +_EPOCH = datetime(1970, 1, 1) + + +def _utcnow() -> datetime: + return datetime.now(timezone.utc).replace(tzinfo=None) + + +def bson_unix_ticks(date_time: datetime | None = None, short: bool = False) -> int: """Python implementation of unix ticks. Args: - date_time (datetime, optional): The datetime to convert to ticks. Defaults to datetime.utcnow(). - short (bool, optional): Whether to return the short ticks. Defaults to False. + date_time: The datetime to convert to ticks. Defaults to the current UTC time. + short: Whether to return the short (millisecond) ticks. Returns: - int: The ticks. + The ticks. """ + if date_time is None: + date_time = _utcnow() - _ticks = (date_time - datetime(1970, 1, 1)).total_seconds() * 10**3 + ticks = (date_time - _EPOCH).total_seconds() * 10**3 if short: - return int(_ticks) + return int(ticks) + + return int(ticks * (10**3)) - return int(_ticks*(10**3)) -def bson_unix_ticks_to_datetime(ticks: int, short:bool = False) -> datetime: +def bson_unix_ticks_to_datetime(ticks: int, short: bool = False) -> datetime: + """Convert unix ticks to a datetime. + Args: + ticks: The ticks to convert. + short: Whether the ticks are short (millisecond) ticks. + + Returns: + The datetime. + """ if not short: ticks = int(ticks / (10**3)) - return datetime(1970, 1, 1) + timedelta(milliseconds=ticks) - + return _EPOCH + timedelta(milliseconds=ticks) diff --git a/Python_Engine/Python/src/python_toolkit/bhom/wrapped/__init__.py b/Python_Engine/Python/src/python_toolkit/bhom/wrapped/__init__.py index 10636f63..ae13ed49 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom/wrapped/__init__.py +++ b/Python_Engine/Python/src/python_toolkit/bhom/wrapped/__init__.py @@ -1,6 +1,8 @@ -from importlib import import_module -from pathlib import Path +"""Import every module in this folder so that their ``bhom_callable`` methods are registered.""" + import os +from importlib import import_module +from pathlib import Path python_files = Path(__file__).parent.glob("**/*.py") @@ -10,4 +12,4 @@ rel = file.relative_to(Path(__file__).parent) module = "." + str(rel).replace(".py", "").replace(os.path.sep, ".") - import_module(module, "python_toolkit.bhom.wrapped") \ No newline at end of file + import_module(module, "python_toolkit.bhom.wrapped") diff --git a/Python_Engine/Python/src/python_toolkit/bhom/wrapped/_test_wrapped.py b/Python_Engine/Python/src/python_toolkit/bhom/wrapped/_test_wrapped.py index ac0764f1..f6f547fc 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom/wrapped/_test_wrapped.py +++ b/Python_Engine/Python/src/python_toolkit/bhom/wrapped/_test_wrapped.py @@ -1,10 +1,10 @@ -from python_toolkit.plot.heatmap import heatmap +"""A method registered for testing the C#-callable wrapper (see ``python_toolkit.bhom.run_wrapped``).""" + from ..decorators import bhom_wrapper -import pandas as pd + @bhom_wrapper.bhom_callable("test") -def heatmap_2(geometry, **kwargs): - print(geometry) - print(kwargs["arg2"]) +def echo_geometry(geometry, **kwargs): + """Set the x coordinate of the given geometry to 20 and return it.""" geometry.x = 20 return geometry diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/__init__.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/__init__.py index 0dbeb309..bae51310 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/__init__.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/__init__.py @@ -1,54 +1,59 @@ +"""BHoM-styled tkinter windows and widgets (requires the "ui" extra: ``python_toolkit[ui]``).""" + +from .._optional import require_extra + +require_extra("ui", "tkinter", "matplotlib", "PIL") + +from .bhom_base_child_window import BHoMBaseChildWindow +from .theming import ( + DARK, + LIGHT, + TclTheme, + ThemeManager, +) from .widgets import ( - BHoMBaseWidget, - PackingOptions, - CalendarWidget, - CheckboxSelection, - MultiBoxSelection, - CmapSelector, - ColourPicker, - DropDownSelection, - FigureContainer, - ScrollableListBox, - PathSelector, - RadioSelection, - ValidatedEntryBox, + BHoMBaseWidget, + CalendarWidget, + CheckboxSelection, + CmapSelector, + ColourPicker, + DropDownSelection, + FigureContainer, + MultiBoxSelection, + PackingOptions, + PathSelector, + RadioSelection, + ScrollableListBox, + ValidatedEntryBox, ) -from .bhom_base_child_window import BHoMBaseChildWindow from .windows import ( - BHoMModalWindow, - DirectoryFileSelector, - LandingPage, - ProcessingWindow, - WarningBox, -) - -from .theming import ( - TclTheme, - ThemeManager, - LIGHT, - DARK, + BHoMModalWindow, + DirectoryFileSelector, + LandingPage, + ProcessingWindow, + WarningBox, ) __all__ = [ - "BHoMBaseWidget", - "PackingOptions", - "CalendarWidget", - "CheckboxSelection", - "MultiBoxSelection", - "CmapSelector", - "ColourPicker", - "DropDownSelection", - "FigureContainer", - "ScrollableListBox", - "PathSelector", - "RadioSelection", - "ValidatedEntryBox", - "BHoMBaseChildWindow", - "BHoMModalWindow", - "DirectoryFileSelector", - "LandingPage", - "ProcessingWindow", - "WarningBox", - "TclTheme", - "ThemeManager" + "BHoMBaseChildWindow", + "BHoMBaseWidget", + "BHoMModalWindow", + "CalendarWidget", + "CheckboxSelection", + "CmapSelector", + "ColourPicker", + "DirectoryFileSelector", + "DropDownSelection", + "FigureContainer", + "LandingPage", + "MultiBoxSelection", + "PackingOptions", + "PathSelector", + "ProcessingWindow", + "RadioSelection", + "ScrollableListBox", + "TclTheme", + "ThemeManager", + "ValidatedEntryBox", + "WarningBox", ] diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/bhom_base_child_window.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/bhom_base_child_window.py index 3946fd88..f5e1eaa0 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/bhom_base_child_window.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/bhom_base_child_window.py @@ -3,7 +3,8 @@ from __future__ import annotations import tkinter as tk -from typing import Callable, Literal, List, Optional +from collections.abc import Callable +from typing import Literal from python_toolkit.bhom_tkinter.bhom_window_shell import BHoMWindowShell from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget @@ -19,24 +20,24 @@ def __init__( title: str = "Application", min_width: int = 400, min_height: int = 400, - width: Optional[int] = None, - height: Optional[int] = None, + width: int | None = None, + height: int | None = None, resizable: bool = True, center_on_screen: bool = True, show_submit: bool = True, submit_text: str = "Submit", - submit_command: Optional[Callable] = None, + submit_command: Callable | None = None, close_on_submit: bool = True, show_close: bool = True, close_text: str = "Close", - close_command: Optional[Callable] = None, - on_close_window: Optional[Callable] = None, + close_command: Callable | None = None, + on_close_window: Callable | None = None, theme_mode: str | None = None, - widgets: Optional[List[BHoMBaseWidget]] = None, + widgets: list[BHoMBaseWidget] | None = None, top_most: bool = False, fullscreen: bool = False, buttons_side: Literal["left", "right"] = "right", - grid_dimensions: Optional[tuple[int, int]] = None, + grid_dimensions: tuple[int, int] | None = None, show_banner: bool = False, defer_show: bool = False, content_padding: int = 20, diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/bhom_base_window.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/bhom_base_window.py index 7a37b35f..f994ca8b 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/bhom_base_window.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/bhom_base_window.py @@ -1,15 +1,14 @@ """Base themed Tk window used by BHoM toolkit GUI windows.""" -import tkinter as tk -from tkinter import ttk -from python_toolkit.bhom_tkinter.widgets.label import Label -from pathlib import Path -from typing import Optional, Callable, Literal, List -import platform -import ctypes import os +import tkinter as tk +from collections.abc import Callable +from typing import Literal + import matplotlib as mpl +from python_toolkit.bhom_tkinter.widgets.label import Label + # Centralized matplotlib backend selection: # - Allow override via `MPLBACKEND` environment variable (e.g. set to 'Agg' for headless CI). # - Default to 'TkAgg' for Tkinter embedding; fallback to 'Agg' if the requested backend is unavailable. @@ -21,15 +20,13 @@ except Exception: mpl.use("Agg", force=True) +from python_toolkit.bhom_tkinter.bhom_window_shell import BHoMWindowShell from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget from python_toolkit.bhom_tkinter.widgets.button import Button -import python_toolkit -from python_toolkit.bhom_tkinter.theming.theme import ThemeManager -from python_toolkit.bhom_tkinter.bhom_window_shell import BHoMWindowShell + class BHoMBaseWindow(tk.Tk, BHoMWindowShell): - """ - A reusable default root window template for tkinter applications. + """A reusable default root window template for tkinter applications. Includes a branded banner, content area, and optional action buttons. """ @@ -38,31 +35,30 @@ def __init__( title: str = "Application", min_width: int = 400, min_height: int = 400, - width: Optional[int] = None, - height: Optional[int] = None, + width: int | None = None, + height: int | None = None, resizable: bool = True, center_on_screen: bool = True, show_submit: bool = True, submit_text: str = "Submit", - submit_command: Optional[Callable] = None, + submit_command: Callable | None = None, close_on_submit: bool = True, show_close: bool = True, close_text: str = "Close", - close_command: Optional[Callable] = None, - on_close_window: Optional[Callable] = None, - theme_mode:str = "auto", - widgets: Optional[List[BHoMBaseWidget]] = None, + close_command: Callable | None = None, + on_close_window: Callable | None = None, + theme_mode: str = "auto", + widgets: list[BHoMBaseWidget] | None = None, top_most: bool = False, fullscreen: bool = False, buttons_side: Literal["left", "right"] = "right", - grid_dimensions: Optional[tuple[int, int]] = None, + grid_dimensions: tuple[int, int] | None = None, show_banner: bool = True, defer_show: bool = False, content_padding: int = 20, - **kwargs + **kwargs, ): - """ - Initialize the default root window. + """Initialize the default root window. Args: title (str): Window and banner title text. @@ -121,11 +117,9 @@ def __init__( if __name__ == "__main__": - - ### TEST SIMPLE - from python_toolkit.bhom_tkinter.widgets import Label, Button + from python_toolkit.bhom_tkinter.widgets import Button, Label test = BHoMBaseWindow( title="Test Window", @@ -133,8 +127,16 @@ def __init__( ) test.widgets.append(Label(test.content_frame, text="Hello, World!")) - test.widgets.append(Button(test.content_frame, text="Click Me", command=lambda: print("Button Clicked!"), helper_text="This is a button.", item_title="Button Widget Title")) + test.widgets.append( + Button( + test.content_frame, + text="Click Me", + command=lambda: print("Button Clicked!"), + helper_text="This is a button.", + item_title="Button Widget Title", + ) + ) test.build() test.mainloop() - print(test.get()) \ No newline at end of file + print(test.get()) diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/bhom_window_shell.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/bhom_window_shell.py index a1ffc69d..1d2ed81e 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/bhom_window_shell.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/bhom_window_shell.py @@ -1,20 +1,20 @@ """Shared themed window chrome mixin for BHoM root and child windows.""" +import ctypes +import platform import tkinter as tk -from tkinter import ttk -from python_toolkit.bhom_tkinter.widgets.label import Label +from collections.abc import Callable from pathlib import Path -from typing import Optional, Callable, Literal, List -import platform -import ctypes -import python_toolkit -from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget -from python_toolkit.bhom_tkinter.widgets.button import Button -from python_toolkit.bhom_tkinter.widgets._slim_scrollbar import SlimScrollbar, blend -from python_toolkit.bhom_tkinter.theming.theme import ThemeManager -from python_toolkit.bhom_tkinter.theming.scaling import init_scaling, scale, get_work_area +from tkinter import ttk +from typing import Literal from python_toolkit.bhom import BHOM_VERSION +from python_toolkit.bhom_tkinter.theming.scaling import get_work_area, init_scaling, scale +from python_toolkit.bhom_tkinter.theming.theme import ThemeManager +from python_toolkit.bhom_tkinter.widgets._slim_scrollbar import SlimScrollbar, blend +from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget +from python_toolkit.bhom_tkinter.widgets.button import Button +from python_toolkit.bhom_tkinter.widgets.label import Label class BHoMWindowShell: @@ -26,24 +26,24 @@ def _init_bhom_shell( title: str, min_width: int, min_height: int, - width: Optional[int], - height: Optional[int], + width: int | None, + height: int | None, resizable: bool, center_on_screen: bool, show_submit: bool, submit_text: str, - submit_command: Optional[Callable], + submit_command: Callable | None, close_on_submit: bool, show_close: bool, close_text: str, - close_command: Optional[Callable], - on_close_window: Optional[Callable], + close_command: Callable | None, + on_close_window: Callable | None, theme_mode: str, - widgets: Optional[List[BHoMBaseWidget]], + widgets: list[BHoMBaseWidget] | None, top_most: bool, fullscreen: bool, buttons_side: Literal["left", "right"], - grid_dimensions: Optional[tuple[int, int]], + grid_dimensions: tuple[int, int] | None, show_banner: bool = True, defer_show: bool = False, content_padding: int = 20, @@ -83,9 +83,9 @@ def _init_bhom_shell( self.close_command = close_command self.result = None self._is_exiting = False - self.button_bar: Optional[ttk.Frame] = None + self.button_bar: ttk.Frame | None = None self._has_been_shown = False - self._pending_resize_job: Optional[str] = None + self._pending_resize_job: str | None = None self._is_resizing = False self._rigid_width = width is not None self._rigid_height = height is not None @@ -129,18 +129,37 @@ def grid_content_frame(self, x_count: int, y_count: int) -> None: self.content_frame.rowconfigure(r, weight=1) for c in range(x_count): self.content_frame.columnconfigure(c, weight=1) - + def build(self): """Call build on all child widgets that have it (for deferred widget construction).""" - if any(not isinstance(w, BHoMBaseWidget) for w in self.widgets): raise TypeError("All items in widgets list must be instances of BHoMBaseWidget.") - + for widget in self.widgets: widget.build() self.refresh_sizing() + def rebuild(self) -> None: + """Re-place all widgets so changes to `self.widgets` are reflected. + + Every BHoM widget currently managed by the content frame is removed from + its geometry manager (without being destroyed), then `build()` places the + widgets that are still in `self.widgets`. + """ + for child in self.content_frame.winfo_children(): + if not isinstance(child, BHoMBaseWidget): + continue + manager = child.winfo_manager() + if manager == "pack": + child.pack_forget() + elif manager == "grid": + child.grid_forget() + elif manager == "place": + child.place_forget() + + self.build() + def _set_window_icon(self) -> None: """Set a custom window icon, replacing Tk's default icon.""" icon_path = self.theme.icon_path @@ -168,8 +187,7 @@ def _set_window_icon(self) -> None: print(f"Warning: Could not set window icon from {icon_path}: {ex}") def _set_titlebar_theme(self) -> None: - """ - Apply titlebar theme using Windows API. + """Apply titlebar theme using Windows API. Args: theme_style: Theme style key (`light` or `dark`). @@ -178,7 +196,6 @@ def _set_titlebar_theme(self) -> None: None """ try: - use_dark = 1 if self.theme.dark_theme else 0 if platform.system() == "Windows" and ctypes is not None and self.winfo_exists(): @@ -187,20 +204,20 @@ def _set_titlebar_theme(self) -> None: if hwnd: DWMWA_USE_IMMERSIVE_DARK_MODE = 20 ctypes.windll.dwmapi.DwmSetWindowAttribute( - hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE, + hwnd, + DWMWA_USE_IMMERSIVE_DARK_MODE, ctypes.byref(ctypes.c_int(use_dark)), - ctypes.sizeof(ctypes.c_int) + ctypes.sizeof(ctypes.c_int), ) except Exception: pass def _load_theme(self) -> str: - """ - Load a custom theme from a TCL file. - + """Load a custom theme from a TCL file. + Args: - custom_theme_path (Path, optional): Path to custom TCL theme file. + custom_theme_path (Path, optional): Path to custom TCL theme file. If None, uses default style.tcl in same directory. theme_name (str): Name of the theme to apply from the TCL file. @@ -211,11 +228,11 @@ def _load_theme(self) -> str: try: current_themes = set(style.theme_names()) - + expected_theme = self.theme.path.stem.replace("_theme", "") # Load the TCL theme file try: - self.tk.call('source', str(self.theme.path)) + self.tk.call("source", str(self.theme.path)) except tk.TclError as source_error: if "already exists" not in str(source_error).lower(): raise @@ -232,7 +249,7 @@ def _load_theme(self) -> str: style.theme_use(selected_theme) self._ensure_typography_styles(style) return selected_theme - + except Exception as e: print(f"Warning: Could not load custom theme: {e}") try: @@ -284,7 +301,7 @@ def _lookup_font(style_name: str) -> str: except Exception: pass - def _build_banner(self, parent: ttk.Frame, title: str, logo_path: Optional[Path]) -> None: + def _build_banner(self, parent: ttk.Frame, title: str, logo_path: Path | None) -> None: """Build the branded banner section. Args: @@ -310,6 +327,7 @@ def _build_banner(self, parent: ttk.Frame, title: str, logo_path: Optional[Path] if logo_path and logo_path.exists(): try: from PIL import Image, ImageTk + img = Image.open(logo_path) img.thumbnail((scale(80), scale(80)), Image.Resampling.LANCZOS) # Bind image to this root explicitly to avoid stale image handles @@ -323,19 +341,11 @@ def _build_banner(self, parent: ttk.Frame, title: str, logo_path: Optional[Path] pass # PIL not available, skip logo # Title - title_label = Label( - text_container, - text=title, - style="LargeTitle.TLabel" - ) + title_label = Label(text_container, text=title, style="LargeTitle.TLabel") title_label.pack(anchor="w") # Subtitle - subtitle_label = Label( - text_container, - text=f"powered by BHoM (v{BHOM_VERSION})", - style="Caption.TLabel" - ) + subtitle_label = Label(text_container, text=f"powered by BHoM (v{BHOM_VERSION})", style="Caption.TLabel") subtitle_label.pack(anchor="w") def _build_buttons( @@ -345,7 +355,7 @@ def _build_buttons( submit_text: str, show_close: bool, close_text: str, - buttons_side: Literal["left", "right"] = "right" + buttons_side: Literal["left", "right"] = "right", ) -> None: """Build the bottom button bar. @@ -377,9 +387,9 @@ def _build_buttons( if show_close: close_widget = Button( - button_container, - text=close_text, - command=self._on_close, + button_container, + text=close_text, + command=self._on_close, width=12, alignment="center", ) @@ -422,9 +432,7 @@ def _build_scroll_host(self, content_padding: int) -> None: self._scroll_host.pack(fill=tk.BOTH, expand=True) background = ttk.Style().lookup("TFrame", "background") or self.cget("background") - self._scroll_canvas = tk.Canvas( - self._scroll_host, highlightthickness=0, borderwidth=0, background=background - ) + self._scroll_canvas = tk.Canvas(self._scroll_host, highlightthickness=0, borderwidth=0, background=background) background = ttk.Style().lookup("TFrame", "background") or "#1e1e1e" foreground = ttk.Style().lookup("TLabel", "foreground") or "#cccccc" try: @@ -436,23 +444,15 @@ def _build_scroll_host(self, content_padding: int) -> None: except Exception: colours = {} bar_options = dict(thickness=scale(12), padding=scale(3), **colours) - self._scroll_bar = SlimScrollbar( - self._scroll_host, tk.VERTICAL, self._scroll_canvas.yview, **bar_options - ) - self._scroll_hbar = SlimScrollbar( - self._scroll_host, tk.HORIZONTAL, self._scroll_canvas.xview, **bar_options - ) - self._scroll_canvas.configure( - yscrollcommand=self._scroll_bar.set, xscrollcommand=self._scroll_hbar.set - ) + self._scroll_bar = SlimScrollbar(self._scroll_host, tk.VERTICAL, self._scroll_canvas.yview, **bar_options) + self._scroll_hbar = SlimScrollbar(self._scroll_host, tk.HORIZONTAL, self._scroll_canvas.xview, **bar_options) + self._scroll_canvas.configure(yscrollcommand=self._scroll_bar.set, xscrollcommand=self._scroll_hbar.set) self._scroll_canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) self._scroll_bar_visible = False self._scroll_hbar_visible = False self.content_frame = ttk.Frame(self._scroll_canvas, padding=content_padding) - self._content_window = self._scroll_canvas.create_window( - (0, 0), window=self.content_frame, anchor="nw" - ) + self._content_window = self._scroll_canvas.create_window((0, 0), window=self.content_frame, anchor="nw") self._scroll_canvas.bind("", self._on_scroll_canvas_configure) self.content_frame.bind("", self._on_content_configure, add="+") self.bind_all("", self._on_mousewheel, add="+") @@ -561,7 +561,9 @@ def _apply_sizing(self) -> None: required_height = max(required_height, self.main_container.winfo_reqheight()) if self.button_bar is not None and self.button_bar.winfo_manager(): - required_height = max(required_height, self.button_bar.winfo_reqheight() + self._scroll_canvas.winfo_reqheight()) + required_height = max( + required_height, self.button_bar.winfo_reqheight() + self._scroll_canvas.winfo_reqheight() + ) # Determine final dimensions: auto-size unless a rigid dimension is explicitly provided. if self._rigid_width: @@ -628,7 +630,9 @@ def _apply_post_show_sizing(self) -> None: required_height = max(required_height, self.main_container.winfo_reqheight()) if self.button_bar is not None and self.button_bar.winfo_manager(): - required_height = max(required_height, self.button_bar.winfo_reqheight() + self._scroll_canvas.winfo_reqheight()) + required_height = max( + required_height, self.button_bar.winfo_reqheight() + self._scroll_canvas.winfo_reqheight() + ) current_width = self.winfo_width() current_height = self.winfo_height() @@ -656,7 +660,7 @@ def _apply_post_show_sizing(self) -> None: def _show_window_with_styling(self) -> None: """Apply titlebar styling and show the window.""" self._set_titlebar_theme() - + # Show window after styling self.deiconify() self._has_been_shown = True @@ -673,7 +677,6 @@ def close(self) -> None: def destroy_root(self) -> None: """Safely terminate and destroy the Tk root window.""" - try: if self.winfo_exists(): self.quit() @@ -681,7 +684,7 @@ def destroy_root(self) -> None: except tk.TclError: pass - def _exit(self, result: str, callback: Optional[Callable] = None) -> None: + def _exit(self, result: str, callback: Callable | None = None) -> None: """Handle any exit path and always destroy the root window. Args: @@ -712,7 +715,7 @@ def _on_submit(self) -> None: if self.close_on_submit: self._exit("submit", self.submit_command) return - + self.result = "submit" try: if self.submit_command: @@ -726,12 +729,11 @@ def _on_submit(self) -> None: finally: self._cached_widget_values = self._collect_widget_values() - def _on_close(self) -> None: """Handle close button click.""" self._exit("close", self.close_command) - def _on_close_window(self, callback: Optional[Callable]) -> None: + def _on_close_window(self, callback: Callable | None) -> None: """Handle window X button click.""" self._exit("window_closed", callback) @@ -751,12 +753,9 @@ def _collect_widget_values(self) -> dict[str, object]: widget_values: dict[str, object] = {} for widget in self.widgets: - if hasattr(widget, "get"): try: widget_values[widget.id] = widget.get() except Exception as ex: print(f"Warning: Failed to get value from widget {widget}: {ex}") return widget_values - - diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/theming/__init__.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/theming/__init__.py index db0139ed..512bfc13 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/theming/__init__.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/theming/__init__.py @@ -1 +1 @@ -from .theme import TclTheme, ThemeManager, LIGHT, DARK \ No newline at end of file +from .theme import DARK, LIGHT, TclTheme, ThemeManager diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/theming/scaling.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/theming/scaling.py index 8ee126a8..18e822ed 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/theming/scaling.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/theming/scaling.py @@ -74,6 +74,7 @@ def get_work_area(root: tk.Misc) -> tuple[int, int]: if platform.system() == "Windows": try: from ctypes import wintypes + rect = wintypes.RECT() # SPI_GETWORKAREA = 0x0030 if ctypes.windll.user32.SystemParametersInfoW(0x0030, 0, ctypes.byref(rect), 0): diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/theming/theme.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/theming/theme.py index 4143869d..3cc0dee6 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/theming/theme.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/theming/theme.py @@ -1,13 +1,15 @@ from dataclasses import dataclass from pathlib import Path + import python_toolkit + @dataclass class TclTheme: name: str path: Path - logo_path: Path|None = None - icon_path: Path|None = None + logo_path: Path | None = None + icon_path: Path | None = None dark_theme: bool = False def __post_init__(self): @@ -18,21 +20,23 @@ def __post_init__(self): if self.icon_path and not self.icon_path.exists(): raise FileNotFoundError(f"Icon file not found at {self.icon_path}") + LIGHT = TclTheme( - name="light", + name="light", path=Path(list(python_toolkit.__path__)[0]).absolute() / "bhom_tkinter" / "theming" / "bhom_light_theme.tcl", logo_path=Path(list(python_toolkit.__path__)[0]).absolute() / "bhom" / "assets" / "BHoM_Logo.png", icon_path=Path(list(python_toolkit.__path__)[0]).absolute() / "bhom" / "assets" / "bhom_icon.png", - dark_theme=False + dark_theme=False, ) DARK = TclTheme( - name="dark", + name="dark", path=Path(list(python_toolkit.__path__)[0]).absolute() / "bhom_tkinter" / "theming" / "bhom_dark_theme.tcl", logo_path=Path(list(python_toolkit.__path__)[0]).absolute() / "bhom" / "assets" / "BHoM_Logo.png", icon_path=Path(list(python_toolkit.__path__)[0]).absolute() / "bhom" / "assets" / "bhom_icon.png", - dark_theme=True - ) + dark_theme=True, +) + class ThemeManager: def __init__(self, theme_mode: str = "light"): @@ -41,7 +45,7 @@ def __init__(self, theme_mode: str = "light"): "light": LIGHT, "dark": DARK, "auto": DARK if self._is_windows_dark_mode() else LIGHT, - "default": LIGHT + "default": LIGHT, } def register_theme(self, theme: TclTheme) -> None: @@ -54,7 +58,14 @@ def set_theme_mode(self, mode: str) -> None: raise ValueError(f"Invalid theme mode: {mode}") self.theme_mode = mode - def add_new_theme(self, name: str, path: Path, logo_path: Path|None = None, icon_path: Path|None = None, dark_theme: bool = False) -> None: + def add_new_theme( + self, + name: str, + path: Path, + logo_path: Path | None = None, + icon_path: Path | None = None, + dark_theme: bool = False, + ) -> None: """Add a new theme by providing its details.""" new_theme = TclTheme(name=name, path=path, logo_path=logo_path, icon_path=icon_path, dark_theme=dark_theme) self.register_theme(new_theme) @@ -62,73 +73,72 @@ def add_new_theme(self, name: str, path: Path, logo_path: Path|None = None, icon @property def name(self) -> str: return self.get_theme().name - + @name.setter def name(self, value: str) -> None: if value not in self.themes: raise ValueError(f"Invalid theme name: {value}") self.set_theme_mode(value) - + @property def path(self) -> Path: return self.get_theme().path - + @path.setter def path(self, value: Path) -> None: theme = self.get_theme() theme.path = value - + @property - def logo_path(self) -> Path|None: + def logo_path(self) -> Path | None: return self.get_theme().logo_path - + @logo_path.setter - def logo_path(self, value: Path|None) -> None: + def logo_path(self, value: Path | None) -> None: theme = self.get_theme() theme.logo_path = value - + @property - def icon_path(self) -> Path|None: + def icon_path(self) -> Path | None: return self.get_theme().icon_path - + @icon_path.setter - def icon_path(self, value: Path|None) -> None: + def icon_path(self, value: Path | None) -> None: theme = self.get_theme() theme.icon_path = value - + @property def dark_theme(self) -> bool: return self.get_theme().dark_theme - + @dark_theme.setter def dark_theme(self, value: bool) -> None: theme = self.get_theme() theme.dark_theme = value - + def get_theme(self, theme_mode: str | None = None) -> TclTheme: if theme_mode is None: theme_mode = self.theme_mode if theme_mode not in self.themes: raise ValueError(f"Invalid theme mode: {theme_mode}") return self.themes[theme_mode] - + def _is_windows_dark_mode(self) -> bool: - + try: - import winreg + key = winreg.OpenKey( - winreg.HKEY_CURRENT_USER, - r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" - ) + winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" + ) value, _ = winreg.QueryValueEx(key, "AppsUseLightTheme") - return value == 0 # 0 means dark mode, 1 means light mode - + return value == 0 # 0 means dark mode, 1 means light mode + except FileNotFoundError: - # Key may not exist on older Windows versions + # Key may not exist on older Windows versions return False - + except ImportError: # winreg is only available on Windows - return False \ No newline at end of file + return False diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/__init__.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/__init__.py index b8432351..285a1965 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/__init__.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/__init__.py @@ -1,39 +1,39 @@ -from ._packing_options import PackingOptions from ._grid_options import GridOptions +from ._packing_options import PackingOptions from ._widgets_base import BHoMBaseWidget -from .widget_calendar import CalendarWidget +from .button import Button from .check_box_selection import CheckboxSelection +from .check_box_selection import CheckboxSelection as MultiBoxSelection from .cmap_selector import CmapSelector from .colour_picker import ColourPicker from .drop_down_selection import DropDownSelection from .figure_container import FigureContainer +from .label import Label from .list_box import ScrollableListBox -from .searchable_list_box import SearchableListBox -from .check_box_selection import CheckboxSelection as MultiBoxSelection from .path_selector import PathSelector from .radio_selection import RadioSelection -from .validated_entry_box import ValidatedEntryBox -from .button import Button -from .label import Label +from .searchable_list_box import SearchableListBox from .spinbox import Spinbox +from .validated_entry_box import ValidatedEntryBox +from .widget_calendar import CalendarWidget __all__ = [ - "BHoMBaseWidget", - "PackingOptions", - "GridOptions", - "CalendarWidget", - "CheckboxSelection", - "MultiBoxSelection", - "CmapSelector", - "ColourPicker", - "DropDownSelection", - "FigureContainer", - "ScrollableListBox", - "SearchableListBox", - "PathSelector", - "RadioSelection", - "ValidatedEntryBox", - "Button", - "Label", - "Spinbox", -] \ No newline at end of file + "BHoMBaseWidget", + "Button", + "CalendarWidget", + "CheckboxSelection", + "CmapSelector", + "ColourPicker", + "DropDownSelection", + "FigureContainer", + "GridOptions", + "Label", + "MultiBoxSelection", + "PackingOptions", + "PathSelector", + "RadioSelection", + "ScrollableListBox", + "SearchableListBox", + "Spinbox", + "ValidatedEntryBox", +] diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_build_options.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_build_options.py index 7891a6ab..522b417c 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_build_options.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_build_options.py @@ -1,11 +1,10 @@ """Typed build options shared by BHoM Tkinter widgets.""" -from dataclasses import dataclass, asdict -from typing import Any, Literal +from dataclasses import asdict, dataclass + @dataclass class BuildOptions: - """Container for widget build options with type hints.""" def to_dict(self) -> dict: @@ -14,4 +13,4 @@ def to_dict(self) -> dict: Returns: dict: Build options filtered to keys with concrete values. """ - return {k: v for k, v in asdict(self).items() if v is not None} \ No newline at end of file + return {k: v for k, v in asdict(self).items() if v is not None} diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_grid_options.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_grid_options.py index 1ec68e1f..24938757 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_grid_options.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_grid_options.py @@ -1,14 +1,14 @@ """Typed gridding options shared by BHoM Tkinter widgets.""" -from dataclasses import dataclass, asdict +from dataclasses import asdict, dataclass from typing import Any, Literal -from python_toolkit.bhom_tkinter.widgets._build_options import BuildOptions from python_toolkit.bhom_tkinter.theming.scaling import scale, scale_pad +from python_toolkit.bhom_tkinter.widgets._build_options import BuildOptions + @dataclass class GridOptions(BuildOptions): - """Container for `grid` geometry keyword arguments with type hints.""" column: int = 0 @@ -20,7 +20,7 @@ class GridOptions(BuildOptions): pady: float | str | tuple[float | str, float | str] = 0.0 row: int = 0 rowspan: int = 1 - sticky: Literal['n', 'e', 's', 'w', 'ne', 'nw', 'se', 'sw', ''] = '' + sticky: Literal["n", "e", "s", "w", "ne", "nw", "se", "sw", ""] = "" def to_dict(self) -> dict: """Convert the dataclass to a dictionary, excluding `None` values. @@ -37,4 +37,3 @@ def to_dict(self) -> dict: if key in options: options[key] = scale(options[key]) return options - diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_packing_options.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_packing_options.py index d7a6570f..6e19e50c 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_packing_options.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_packing_options.py @@ -1,21 +1,22 @@ """Typed packing options shared by BHoM Tkinter widgets.""" -from dataclasses import dataclass, asdict +from dataclasses import asdict, dataclass from typing import Any, Literal -from python_toolkit.bhom_tkinter.widgets._build_options import BuildOptions from python_toolkit.bhom_tkinter.theming.scaling import scale, scale_pad +from python_toolkit.bhom_tkinter.widgets._build_options import BuildOptions + @dataclass class PackingOptions(BuildOptions): """Container for `pack` geometry keyword arguments with type hints.""" after: Any = None - anchor: Literal['nw', 'n', 'ne', 'w', 'center', 'e', 'sw', 's', 'se'] = 'center' + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = "center" before: Any = None expand: bool | Literal[0, 1] = 0 - fill: Literal['none', 'x', 'y', 'both'] = 'none' - side: Literal['left', 'right', 'top', 'bottom'] = 'top' + fill: Literal["none", "x", "y", "both"] = "none" + side: Literal["left", "right", "top", "bottom"] = "top" ipadx: float | str = 0.0 ipady: float | str = 0.0 padx: float | str | tuple[float | str, float | str] = 0.0 @@ -37,8 +38,8 @@ def to_dict(self) -> dict: if key in options: options[key] = scale(options[key]) return options - -if __name__ == "__main__": - d = PackingOptions(side='left', fill='x', expand=True, padx=5, pady=5, anchor='w') - print(d.to_dict()) \ No newline at end of file + +if __name__ == "__main__": + d = PackingOptions(side="left", fill="x", expand=True, padx=5, pady=5, anchor="w") + print(d.to_dict()) diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_slim_scrollbar.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_slim_scrollbar.py index 10aa0289..56305544 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_slim_scrollbar.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_slim_scrollbar.py @@ -1,14 +1,14 @@ """Slim, rounded scrollbar drawn on a canvas (themed, DPI-aware).""" import tkinter as tk -from typing import Callable, Optional +from collections.abc import Callable def blend(base: str, other: str, amount: float) -> str: """Blend two '#rrggbb' colours; amount=0 gives `base`, 1 gives `other`.""" - b = [int(base[i:i + 2], 16) for i in (1, 3, 5)] - o = [int(other[i:i + 2], 16) for i in (1, 3, 5)] - return "#%02x%02x%02x" % tuple(int(x + (y - x) * amount) for x, y in zip(b, o)) + b = [int(base[i : i + 2], 16) for i in (1, 3, 5)] + o = [int(other[i : i + 2], 16) for i in (1, 3, 5)] + return "#{:02x}{:02x}{:02x}".format(*tuple(int(x + (y - x) * amount) for x, y in zip(b, o))) class SlimScrollbar(tk.Canvas): @@ -22,7 +22,7 @@ def __init__( self, parent: tk.Misc, orient: str = tk.VERTICAL, - command: Optional[Callable] = None, + command: Callable | None = None, *, track: str = "#1e1e1e", thumb: str = "#5a5a5a", @@ -37,7 +37,7 @@ def __init__( self._padding = padding self._first, self._last = 0.0, 1.0 self._hover = False - self._drag_offset: Optional[float] = None + self._drag_offset: float | None = None size = {"width": thickness} if self._vertical else {"height": thickness} super().__init__(parent, highlightthickness=0, borderwidth=0, background=track, **size) diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_widgets_base.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_widgets_base.py index 6d9f5735..65b51eed 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_widgets_base.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/_widgets_base.py @@ -1,39 +1,39 @@ """Abstract base widget primitives used across BHoM Tkinter components.""" -from abc import ABC, abstractmethod -from typing import cast - import tkinter as tk +from abc import ABC, abstractmethod +from collections.abc import Callable from tkinter import ttk -from typing import Optional, Literal, Union, Tuple, Callable +from typing import Literal, cast +from uuid import uuid4 -from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions +from python_toolkit.bhom.logging import CONSOLE_LOGGER from python_toolkit.bhom_tkinter.widgets._build_options import BuildOptions from python_toolkit.bhom_tkinter.widgets._grid_options import GridOptions +from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions -from uuid import uuid4 class BHoMBaseWidget(ttk.Frame, ABC): - """ - Base class for all widgets in the BHoM Tkinter toolkit. + """Base class for all widgets in the BHoM Tkinter toolkit. Provides common structure and functionality for consistent design. """ def __init__( - self, - parent: ttk.Frame, - id: Optional[str] = None, - item_title: Optional[str] = None, - helper_text: Optional[str] = None, - alignment: Literal['left', 'center', 'right'] = 'left', - fill_extents: bool = False, - custom_validation: Optional[Callable[[object], Tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]]] = None, - disable_validation: bool = False, - build_options: BuildOptions = PackingOptions(), - on_change: Optional[Callable] = None, - **kwargs): - """ - Initialize the widget base. + self, + parent: ttk.Frame, + id: str | None = None, + item_title: str | None = None, + helper_text: str | None = None, + alignment: Literal["left", "center", "right"] = "left", + fill_extents: bool = False, + custom_validation: Callable[[object], tuple[bool, str | None, Literal["info", "warning", "error"] | None]] + | None = None, + disable_validation: bool = False, + build_options: BuildOptions | None = None, + on_change: Callable | None = None, + **kwargs, + ): + """Initialize the widget base. Args: parent: Parent widget @@ -57,12 +57,12 @@ def __init__( self.item_title = item_title self.helper_text = helper_text - self.build_options = build_options - self.alignment: Literal['left', 'center', 'right'] = self._normalise_alignment(alignment) + self.build_options = build_options if build_options is not None else PackingOptions() + self.alignment: Literal["left", "center", "right"] = self._normalise_alignment(alignment) self.fill_extents = self._normalise_bool(fill_extents) self.custom_validation = custom_validation self.disable_validation = bool(disable_validation) - self.on_change: Optional[Callable] = on_change + self.on_change: Callable | None = on_change if id is None: self.id = str(uuid4()) @@ -104,54 +104,63 @@ def __init__( self.content_frame.pack(side="top", fill=tk.BOTH, expand=True) @property - def _pack_anchor(self) -> Literal['w', 'center', 'e']: + def _pack_anchor(self) -> Literal["w", "center", "e"]: """Return the pack anchor string for the current alignment. Returns: str: Pack anchor token (`w`, `center`, or `e`). """ - return cast(Literal['w', 'center', 'e'], { - "left": "w", - "center": "center", - "right": "e", - }[self.alignment]) + return cast( + Literal["w", "center", "e"], + { + "left": "w", + "center": "center", + "right": "e", + }[self.alignment], + ) @property - def _text_anchor(self) -> Literal['w', 'center', 'e']: + def _text_anchor(self) -> Literal["w", "center", "e"]: """Return the text anchor string for the current alignment. Returns: str: Text anchor token (`w`, `center`, or `e`). """ - return cast(Literal['w', 'center', 'e'], { - "left": "w", - "center": "center", - "right": "e", - }[self.alignment]) + return cast( + Literal["w", "center", "e"], + { + "left": "w", + "center": "center", + "right": "e", + }[self.alignment], + ) @property - def _text_justify(self) -> Literal['left', 'center', 'right']: + def _text_justify(self) -> Literal["left", "center", "right"]: """Return the Tk justify token for the current alignment. Returns: str: Justification token (`left`, `center`, or `right`). """ - return cast(Literal['left', 'center', 'right'], self.alignment) + return cast(Literal["left", "center", "right"], self.alignment) @property - def _grid_sticky(self) -> Literal['w', '', 'e']: + def _grid_sticky(self) -> Literal["w", "", "e"]: """Return the grid sticky token for the current alignment. Returns: str: Grid sticky token (`w`, empty string for centered, or `e`). """ - return cast(Literal['w', '', 'e'], { - "left": "w", - "center": "", - "right": "e", - }[self.alignment]) - - def _normalise_alignment(self, alignment: Optional[str]) -> Literal['left', 'center', 'right']: + return cast( + Literal["w", "", "e"], + { + "left": "w", + "center": "", + "right": "e", + }[self.alignment], + ) + + def _normalise_alignment(self, alignment: str | None) -> Literal["left", "center", "right"]: """Normalise alignment input and fallback safely to `left`. Args: @@ -163,7 +172,7 @@ def _normalise_alignment(self, alignment: Optional[str]) -> Literal['left', 'cen candidate = str(alignment or "left").strip().lower() if candidate not in {"left", "center", "right"}: return "left" - return cast(Literal['left', 'center', 'right'], candidate) + return cast(Literal["left", "center", "right"], candidate) def _normalise_bool(self, value: object) -> bool: """Normalise bool-like input with safe defaults. @@ -207,7 +216,7 @@ def _apply_text_alignment(self, widget: tk.Widget) -> None: except Exception: pass - def align_child_text(self, widget: tk.Widget, alignment: Optional[Literal['left', 'center', 'right']] = None) -> None: + def align_child_text(self, widget: tk.Widget, alignment: Literal["left", "center", "right"] | None = None) -> None: """Apply left/center/right text alignment to a child widget. Args: @@ -219,11 +228,11 @@ def align_child_text(self, widget: tk.Widget, alignment: Optional[Literal['left' self.alignment = self._normalise_alignment(alignment) self._apply_text_alignment(widget) - + if alignment is not None: self.alignment = previous_alignment - def set_alignment(self, alignment: Literal['left', 'center', 'right']) -> None: + def set_alignment(self, alignment: Literal["left", "center", "right"]) -> None: """Set widget-wide alignment and refresh built-in labels. Args: @@ -284,7 +293,7 @@ def set(self, value): raise NotImplementedError("Subclasses must implement the set() method.") @abstractmethod - def validate(self) -> Tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: """Validate the current widget value. Returns: @@ -295,9 +304,8 @@ def validate(self) -> Tuple[bool, Optional[str], Optional[Literal['info', 'warni raise NotImplementedError("Subclasses must implement the validate() method.") def apply_validation( - self, - base_result: Tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]] - ) -> Tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + self, base_result: tuple[bool, str | None, Literal["info", "warning", "error"] | None] + ) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: """Apply global validation switches and optional custom validation. Subclasses should call this from their `validate()` implementation, @@ -337,11 +345,8 @@ def apply_validation( return True, custom_message, custom_severity return is_valid, message, severity - - def build( - self, - **kwargs - ): + + def build(self, **kwargs): """Place the widget in its parent container. Args: @@ -353,22 +358,18 @@ def build( elif isinstance(self.build_options, GridOptions): self.grid(**self.build_options.to_dict()) - + else: raise NotImplementedError(f"Unsupported build options type: {type(self.build_options)}") - if __name__ == "__main__": - from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow - from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions from python_toolkit.bhom_tkinter.widgets._grid_options import GridOptions + from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions + from python_toolkit.bhom_tkinter.widgets.label import Label - from python_toolkit.bhom_tkinter.widgets.button import Button - from python_toolkit.bhom_tkinter.widgets.label import Label - - #gridding test + # gridding test root = BHoMBaseWindow(grid_dimensions=(3, 3)) diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/button.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/button.py index d51c7542..3fbec1c0 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/button.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/button.py @@ -1,89 +1,87 @@ """Simple button widget with action callback following BHoM toolkit patterns.""" -import tkinter as tk +from collections.abc import Callable from tkinter import ttk -from typing import Optional, Callable, Literal - -from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget +from typing import Literal from python_toolkit.bhom.analytics import CONSOLE_LOGGER +from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget class Button(BHoMBaseWidget): - """A minimal button widget that invokes a callback when clicked. - - - `get()` returns the number of times the button has been clicked. - - `set()` can update the button label when passed a string. - """ - - def __init__( - self, - parent, - text: str = "Click", - command: Optional[Callable[[], None]] = None, - width: int = 25, - style: Optional[str] = None, - **kwargs, - ): - super().__init__(parent, **kwargs) - - self._user_command = command - self._click_count = 0 - self.button = ttk.Button( - self.content_frame, - text=text, - command=self._on_click, - width=width, - style=style, - - ) - self.button.pack(side="top", anchor=self._pack_anchor) - - def _on_click(self): - """Internal click handler increments counter and calls user callback.""" - self._click_count += 1 - if self._user_command: - try: - self._user_command() - except Exception as e: - CONSOLE_LOGGER.error(f"Unhandled exception when trying to perform custom command: {e}", exc_info=True) - - def get(self): - """Return the number of times the button has been clicked.""" - return self._click_count - - def set(self, value): - """Update the button label text when passed a string.""" - if isinstance(value, str): - self.button.configure(text=value) - - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: - """Button has no user-editable state, so validation is always valid unless overridden.""" - return self.apply_validation((True, None, None)) + """A minimal button widget that invokes a callback when clicked. + + - `get()` returns the number of times the button has been clicked. + - `set()` can update the button label when passed a string. + """ + + def __init__( + self, + parent, + text: str = "Click", + command: Callable[[], None] | None = None, + width: int = 25, + style: str | None = None, + **kwargs, + ): + super().__init__(parent, **kwargs) + + self._user_command = command + self._click_count = 0 + self.button = ttk.Button( + self.content_frame, + text=text, + command=self._on_click, + width=width, + style=style, + ) + self.button.pack(side="top", anchor=self._pack_anchor) + + def _on_click(self): + """Internal click handler increments counter and calls user callback.""" + self._click_count += 1 + if self._user_command: + try: + self._user_command() + except Exception as e: + CONSOLE_LOGGER.error(f"Unhandled exception when trying to perform custom command: {e}", exc_info=True) + + def get(self): + """Return the number of times the button has been clicked.""" + return self._click_count + + def set(self, value): + """Update the button label text when passed a string.""" + if isinstance(value, str): + self.button.configure(text=value) + + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: + """Button has no user-editable state, so validation is always valid unless overridden.""" + return self.apply_validation((True, None, None)) if __name__ == "__main__": - from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow - from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions + from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow + from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions - def demo_action(): + def demo_action(): - #test fail + # test fail - a = 1 / 0 + raise ZeroDivisionError("demo failure") - root = BHoMBaseWindow() - parent_frame = root.content_frame + root = BHoMBaseWindow() + parent_frame = root.content_frame - widget = Button( - parent_frame, - text="Press me", - command=demo_action, - item_title="Demo Button", - helper_text="A minimal clickable button.", - build_options=PackingOptions(anchor="n", padx=20, pady=20), - alignment="center", - ) - widget.build() + widget = Button( + parent_frame, + text="Press me", + command=demo_action, + item_title="Demo Button", + helper_text="A minimal clickable button.", + build_options=PackingOptions(anchor="n", padx=20, pady=20), + alignment="center", + ) + widget.build() - root.mainloop() + root.mainloop() diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/check_box_selection.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/check_box_selection.py index ddac1bac..e778dc8c 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/check_box_selection.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/check_box_selection.py @@ -1,206 +1,216 @@ """Checkbox selection widget with multi-select support and state helpers.""" import tkinter as tk +from collections.abc import Callable from tkinter import ttk -from typing import Optional, List, Callable, Tuple, Literal +from typing import Literal -from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget from python_toolkit.bhom_tkinter.theming.scaling import scale_pad +from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget + class CheckboxSelection(BHoMBaseWidget): - """A reusable checkbox selection widget built from a list of fields, allowing multiple selections.""" - - def __init__( - self, - parent, - fields=None, - command: Optional[Callable[[List[str]], None]] = None, - defaults: Optional[List[str]] = None, - orient="vertical", - max_per_line=None, - item_title: Optional[str] = None, - helper_text: Optional[str] = None, - min_selections: Optional[int] = None, - max_selections: Optional[int] = None, - **kwargs): - """ - Args: - parent (tk.Widget): The parent widget. - fields (list, optional): List of selectable fields. - command (callable, optional): Called with list of selected values when changed. - defaults (list, optional): List of default selected values. - orient (str): Either "vertical" or "horizontal". - max_per_line (int, optional): Maximum items per row/column before wrapping. - item_title (str, optional): Optional header text shown at the top of the widget frame. - helper_text (str, optional): Optional helper text shown above the checkboxes. - min_selections (int, optional): Minimum number of selections required. - max_selections (int, optional): Maximum number of selections allowed. - **kwargs: Additional Frame options. - """ - super().__init__(parent, item_title=item_title, helper_text=helper_text, **kwargs) - - self.fields = [str(field) for field in (fields or [])] - self.command = command - self.orient = orient.lower() - self.max_per_line = max_per_line - self.value_vars = {} # Dictionary mapping field names to BooleanVars - self._buttons = [] - self._field_buttons = {} - self.min_selections = min_selections - self.max_selections = max_selections - - # Sub-frame for checkbox controls - self.buttons_frame = ttk.Frame(self.content_frame) - self.buttons_frame.pack(side="top", anchor=self._pack_anchor) - - self._build_buttons() - - if defaults: - self.set(defaults) - - def _build_buttons(self): - """Create checkboxes from current fields.""" - for button in self._buttons: - button.destroy() - self._buttons.clear() - self._field_buttons.clear() - self.value_vars.clear() - - for index, field in enumerate(self.fields): - var = tk.BooleanVar(value=False) - self.value_vars[field] = var - - button = ttk.Checkbutton( - self.buttons_frame, - text=field, - variable=var, - style="Checkbox.TCheckbutton", - command=lambda f=field: self._on_select_field(f), - ) - self.align_child_text(button) - - if self.max_per_line and self.max_per_line > 0: - if self.orient == "horizontal": - row = index // self.max_per_line - column = index % self.max_per_line - else: - row = index % self.max_per_line - column = index // self.max_per_line - button.grid(row=row, column=column, padx=scale_pad((0, 10)), pady=scale_pad((0, 4)), sticky=self._grid_sticky) - elif self.orient == "horizontal": - button.grid(row=0, column=index, padx=scale_pad((0, 10)), pady=scale_pad((0, 4)), sticky=self._grid_sticky) - else: - button.grid(row=index, column=0, padx=scale_pad((0, 10)), pady=scale_pad((0, 4)), sticky=self._grid_sticky) - self._buttons.append(button) - self._field_buttons[field] = button - - def _on_select_field(self, field): - """Handle checkbox selection change.""" - if self.command: - self.command(self.get()) - self._fire_on_change(self.get()) - - def get(self) -> List[str]: - """Return a list of currently selected values. - - Returns: - List[str]: Selected field labels. - """ - return [field for field, var in self.value_vars.items() if var.get()] - - def set(self, value: List[str]): - """Set the selected values. - - Args: - value: Field names to mark as selected. - """ - values = [str(v) for v in (value or [])] - for field, var in self.value_vars.items(): - var.set(field in values) - - def select_all(self): - """Select all checkboxes.""" - for var in self.value_vars.values(): - var.set(True) - if self.command: - self.command(self.get()) - self._fire_on_change(self.get()) - - def deselect_all(self): - """Deselect all checkboxes.""" - for var in self.value_vars.values(): - var.set(False) - if self.command: - self.command(self.get()) - self._fire_on_change(self.get()) - - def toggle_all(self): - """Toggle all checkbox states.""" - for var in self.value_vars.values(): - var.set(not var.get()) - if self.command: - self.command(self.get()) - self._fire_on_change(self.get()) - - def set_fields(self, fields: List[str], defaults: Optional[List[str]] = None): - """Replace the available fields and rebuild the widget. - - Args: - fields: New available field names. - defaults: Optional field names to preselect after rebuild. - """ - self.fields = [str(field) for field in (fields or [])] - self._build_buttons() - - if defaults: - self.set(defaults) - - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: - """Validate the current selection against min/max constraints. - - Returns: - tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: - `(is_valid, message, severity)` where severity is `None` when - valid, or `"error"` for an invalid selection. - """ - selected_count = len(self.get()) - if self.min_selections is not None and selected_count < self.min_selections: - return getattr(self, "apply_validation")((False, f"Select at least {self.min_selections} options.", "error")) - if self.max_selections is not None and selected_count > self.max_selections: - return getattr(self, "apply_validation")((False, f"Select no more than {self.max_selections} options.", "error")) - return getattr(self, "apply_validation")((True, None, None)) + """A reusable checkbox selection widget built from a list of fields, allowing multiple selections.""" + + def __init__( + self, + parent, + fields=None, + command: Callable[[list[str]], None] | None = None, + defaults: list[str] | None = None, + orient="vertical", + max_per_line=None, + item_title: str | None = None, + helper_text: str | None = None, + min_selections: int | None = None, + max_selections: int | None = None, + **kwargs, + ): + """Args: + parent (tk.Widget): The parent widget. + fields (list, optional): List of selectable fields. + command (callable, optional): Called with list of selected values when changed. + defaults (list, optional): List of default selected values. + orient (str): Either "vertical" or "horizontal". + max_per_line (int, optional): Maximum items per row/column before wrapping. + item_title (str, optional): Optional header text shown at the top of the widget frame. + helper_text (str, optional): Optional helper text shown above the checkboxes. + min_selections (int, optional): Minimum number of selections required. + max_selections (int, optional): Maximum number of selections allowed. + **kwargs: Additional Frame options. + """ + super().__init__(parent, item_title=item_title, helper_text=helper_text, **kwargs) + + self.fields = [str(field) for field in (fields or [])] + self.command = command + self.orient = orient.lower() + self.max_per_line = max_per_line + self.value_vars = {} # Dictionary mapping field names to BooleanVars + self._buttons = [] + self._field_buttons = {} + self.min_selections = min_selections + self.max_selections = max_selections + + # Sub-frame for checkbox controls + self.buttons_frame = ttk.Frame(self.content_frame) + self.buttons_frame.pack(side="top", anchor=self._pack_anchor) + + self._build_buttons() + + if defaults: + self.set(defaults) + + def _build_buttons(self): + """Create checkboxes from current fields.""" + for button in self._buttons: + button.destroy() + self._buttons.clear() + self._field_buttons.clear() + self.value_vars.clear() + + for index, field in enumerate(self.fields): + var = tk.BooleanVar(value=False) + self.value_vars[field] = var + + button = ttk.Checkbutton( + self.buttons_frame, + text=field, + variable=var, + style="Checkbox.TCheckbutton", + command=lambda f=field: self._on_select_field(f), + ) + self.align_child_text(button) + + if self.max_per_line and self.max_per_line > 0: + if self.orient == "horizontal": + row = index // self.max_per_line + column = index % self.max_per_line + else: + row = index % self.max_per_line + column = index // self.max_per_line + button.grid( + row=row, column=column, padx=scale_pad((0, 10)), pady=scale_pad((0, 4)), sticky=self._grid_sticky + ) + elif self.orient == "horizontal": + button.grid( + row=0, column=index, padx=scale_pad((0, 10)), pady=scale_pad((0, 4)), sticky=self._grid_sticky + ) + else: + button.grid( + row=index, column=0, padx=scale_pad((0, 10)), pady=scale_pad((0, 4)), sticky=self._grid_sticky + ) + self._buttons.append(button) + self._field_buttons[field] = button + + def _on_select_field(self, field): + """Handle checkbox selection change.""" + if self.command: + self.command(self.get()) + self._fire_on_change(self.get()) + + def get(self) -> list[str]: + """Return a list of currently selected values. + + Returns: + List[str]: Selected field labels. + """ + return [field for field, var in self.value_vars.items() if var.get()] + + def set(self, value: list[str]): + """Set the selected values. + + Args: + value: Field names to mark as selected. + """ + values = [str(v) for v in (value or [])] + for field, var in self.value_vars.items(): + var.set(field in values) + + def select_all(self): + """Select all checkboxes.""" + for var in self.value_vars.values(): + var.set(True) + if self.command: + self.command(self.get()) + self._fire_on_change(self.get()) + + def deselect_all(self): + """Deselect all checkboxes.""" + for var in self.value_vars.values(): + var.set(False) + if self.command: + self.command(self.get()) + self._fire_on_change(self.get()) + + def toggle_all(self): + """Toggle all checkbox states.""" + for var in self.value_vars.values(): + var.set(not var.get()) + if self.command: + self.command(self.get()) + self._fire_on_change(self.get()) + + def set_fields(self, fields: list[str], defaults: list[str] | None = None): + """Replace the available fields and rebuild the widget. + + Args: + fields: New available field names. + defaults: Optional field names to preselect after rebuild. + """ + self.fields = [str(field) for field in (fields or [])] + self._build_buttons() + + if defaults: + self.set(defaults) + + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: + """Validate the current selection against min/max constraints. + + Returns: + tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + `(is_valid, message, severity)` where severity is `None` when + valid, or `"error"` for an invalid selection. + """ + selected_count = len(self.get()) + if self.min_selections is not None and selected_count < self.min_selections: + return self.apply_validation((False, f"Select at least {self.min_selections} options.", "error")) + if self.max_selections is not None and selected_count > self.max_selections: + return self.apply_validation((False, f"Select no more than {self.max_selections} options.", "error")) + return self.apply_validation((True, None, None)) -if __name__ == "__main__": - from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow - from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions - - def on_selection(values): - """Print selected values in the standalone example.""" - print(f"Selected: {values}") - - root = BHoMBaseWindow() - parent_frame = root.content_frame - - widget = CheckboxSelection( - parent_frame, - fields=["Option A", "Option B", "Option C", "Option D", "Option E", "Option F", "Option G"], - command=on_selection, - defaults=["Option B", "Option D"], - orient="vertical", - max_per_line=6, - min_selections=2, - item_title="Choose Options", - helper_text="Select one or more options below:", - build_options=PackingOptions(padx=20, pady=20) - ) - widget.build() - - # Add control buttons for demonstration - control_frame = ttk.Frame(parent_frame) - control_frame.pack(padx=scale_pad(20), pady=scale_pad(10)) - - Button(control_frame, text="Select All", command=widget.select_all).pack(side="left", padx=scale_pad(5)) - Button(control_frame, text="Deselect All", command=widget.deselect_all).pack(side="left", padx=scale_pad(5)) - - root.mainloop() +if __name__ == "__main__": + from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow + from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions + + def on_selection(values): + """Print selected values in the standalone example.""" + print(f"Selected: {values}") + + root = BHoMBaseWindow() + parent_frame = root.content_frame + + widget = CheckboxSelection( + parent_frame, + fields=["Option A", "Option B", "Option C", "Option D", "Option E", "Option F", "Option G"], + command=on_selection, + defaults=["Option B", "Option D"], + orient="vertical", + max_per_line=6, + min_selections=2, + item_title="Choose Options", + helper_text="Select one or more options below:", + build_options=PackingOptions(padx=20, pady=20), + ) + widget.build() + + # Add control buttons for demonstration + control_frame = ttk.Frame(parent_frame) + control_frame.pack(padx=scale_pad(20), pady=scale_pad(10)) + + from python_toolkit.bhom_tkinter.widgets.button import Button + + Button(control_frame, text="Select All", command=widget.select_all).pack(side="left", padx=scale_pad(5)) + Button(control_frame, text="Deselect All", command=widget.deselect_all).pack(side="left", padx=scale_pad(5)) + + root.mainloop() diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/cmap_selector.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/cmap_selector.py index 4d53594e..848709c5 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/cmap_selector.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/cmap_selector.py @@ -1,20 +1,22 @@ """Colormap selector widget with embedded matplotlib preview.""" -from typing import Dict, List, Optional, Literal, Union -from tkinter import ttk import tkinter as tk +from tkinter import ttk +from typing import Literal, Union + import matplotlib as mpl from matplotlib.colors import Colormap, ListedColormap -from python_toolkit.plot.cmap_sample import cmap_sample_plot -from python_toolkit.bhom_tkinter.widgets.figure_container import FigureContainer -from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget -from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions from python_toolkit.bhom.analytics import CONSOLE_LOGGER from python_toolkit.bhom_tkinter.theming.scaling import scale_pad +from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions +from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget +from python_toolkit.bhom_tkinter.widgets.figure_container import FigureContainer +from python_toolkit.plot.cmap_sample import cmap_sample_plot # Accepted colormap input types for colormaps parameter and set()/add_cmap() -CmapInput = Union[str, Colormap, List[str]] +CmapInput = Union[str, Colormap, list[str]] + class CmapSelector(BHoMBaseWidget): """A widget for selecting and previewing a matplotlib colormap. @@ -72,16 +74,15 @@ class CmapSelector(BHoMBaseWidget): def __init__( self, parent: ttk.Frame, - colormaps: Optional[List[CmapInput]] = None, + colormaps: list[CmapInput] | None = None, cmap_set: str = "all", cmap_bins: int = 256, - default_cmap: Optional[CmapInput] = None, + default_cmap: CmapInput | None = None, plot_size: tuple[int, int] = (400, 50), dropdown_position: Literal["n", "e", "s", "w"] = "n", - **kwargs + **kwargs, ) -> None: - """ - Initialize the CmapSelector widget. + """Initialize the CmapSelector widget. Args: parent: Parent widget. @@ -106,7 +107,7 @@ def __init__( self.plot_size = plot_size # Registry of custom (non-matplotlib-named) colormaps: label → Colormap - self._custom_cmaps: Dict[str, Colormap] = {} + self._custom_cmaps: dict[str, Colormap] = {} # Create frame for cmap selection content self.cmap_frame = ttk.Frame(self.content_frame) @@ -114,7 +115,7 @@ def __init__( self.colormap_var = tk.StringVar(value="viridis") self._all_colormaps = self._get_all_colormaps() - self._preset_map: Dict[str, List[str]] = { + self._preset_map: dict[str, list[str]] = { "all": self._all_colormaps, "continuous": self._filter_available(self.CONTINUOUS_CMAPS), "categorical": self._filter_available(self.CATEGORICAL_CMAPS), @@ -155,7 +156,9 @@ def __init__( content, width=plot_size[0], height=plot_size[1], - build_options=PackingOptions(side=pack_side_figure, anchor=self._pack_anchor, fill=fill_mode, padx=0, pady=(0, 8)), + build_options=PackingOptions( + side=pack_side_figure, anchor=self._pack_anchor, fill=fill_mode, padx=0, pady=(0, 8) + ), ) self.figure_widget.build() @@ -172,7 +175,7 @@ def __init__( self._default_label = self._resolve_default_label(default_cmap, current_colormaps) self._select_default_cmap(current_colormaps) - def _get_all_colormaps(self) -> List[str]: + def _get_all_colormaps(self) -> list[str]: """Return all registered colormap names, including reversed variants. Returns: @@ -189,7 +192,7 @@ def _get_all_colormaps(self) -> List[str]: return sorted(all_names) - def _filter_available(self, names: List[str]) -> List[str]: + def _filter_available(self, names: list[str]) -> list[str]: """Filter a candidate list to names available in the current matplotlib build. Args: @@ -201,7 +204,7 @@ def _filter_available(self, names: List[str]) -> List[str]: available = set(self._all_colormaps) return [name for name in names if name in available] - def _with_reversed(self, names: List[str]) -> List[str]: + def _with_reversed(self, names: list[str]) -> list[str]: """Return colormap names with reversed variants next to base maps. Args: @@ -211,7 +214,7 @@ def _with_reversed(self, names: List[str]) -> List[str]: List[str]: Ordered list with available `_r` variants inserted. """ available = set(self._all_colormaps) - selected: List[str] = [] + selected: list[str] = [] for name in names: if name in available and name not in selected: selected.append(name) @@ -221,7 +224,7 @@ def _with_reversed(self, names: List[str]) -> List[str]: selected.append(reversed_name) return selected - def _preset_colormaps(self, cmap_set: str) -> List[str]: + def _preset_colormaps(self, cmap_set: str) -> list[str]: """Resolve a preset colormap set name to a colormap list. Args: @@ -233,7 +236,7 @@ def _preset_colormaps(self, cmap_set: str) -> List[str]: key = (cmap_set or "all").lower() return self._with_reversed(self._preset_map.get(key, self._preset_map["all"])) - def _resolve_colormaps(self, colormaps: List[CmapInput]) -> tuple[List[str], Dict[str, Colormap]]: + def _resolve_colormaps(self, colormaps: list[CmapInput]) -> tuple[list[str], dict[str, Colormap]]: """Normalise a mixed list of colormap inputs into display labels and a custom-cmap registry. Each item is handled as follows: @@ -248,8 +251,8 @@ def _resolve_colormaps(self, colormaps: List[CmapInput]) -> tuple[List[str], Dic Returns: tuple[List[str], Dict[str, Colormap]]: Ordered display label list and a mapping of label → Colormap for non-standard entries. """ - display_names: List[str] = [] - custom_cmaps: Dict[str, Colormap] = {} + display_names: list[str] = [] + custom_cmaps: dict[str, Colormap] = {} list_counter = 0 for item in colormaps: @@ -268,12 +271,15 @@ def _resolve_colormaps(self, colormaps: List[CmapInput]) -> tuple[List[str], Dic display_names.append(label) custom_cmaps[label] = cmap except Exception: - CONSOLE_LOGGER.warning(f"An error occurred when trying to convert a list of colours ({item}) to a `ListedColormap`. This cmap will not be available to select in UI.", exc_info=1) + CONSOLE_LOGGER.warning( + f"An error occurred when trying to convert a list of colours ({item}) to a `ListedColormap`. This cmap will not be available to select in UI.", + exc_info=1, + ) pass return display_names, custom_cmaps - def _unique_label(self, candidate: str, existing: List[str]) -> str: + def _unique_label(self, candidate: str, existing: list[str]) -> str: """Return a label that is unique within `existing`. Args: @@ -291,7 +297,7 @@ def _unique_label(self, candidate: str, existing: List[str]) -> str: counter += 1 return label - def _resolve_default_label(self, default: Optional[CmapInput], available: List[str]) -> Optional[str]: + def _resolve_default_label(self, default: CmapInput | None, available: list[str]) -> str | None: """Resolve a `default_cmap` value of any input type to a display label. Args: @@ -317,11 +323,11 @@ def _resolve_default_label(self, default: Optional[CmapInput], available: List[s return None - def _populate_cmap_list(self, colormaps: List[str]) -> None: + def _populate_cmap_list(self, colormaps: list[str]) -> None: """Replace the combobox options with the provided colormap names.""" self.cmap_combobox["values"] = tuple(colormaps) - def _select_default_cmap(self, colormaps: List[str]) -> None: + def _select_default_cmap(self, colormaps: list[str]) -> None: """Select an initial colormap and render its preview.""" if not colormaps: self.figure_widget.clear() @@ -354,11 +360,11 @@ def _update_cmap_sample(self, *args) -> None: # Use the stored Colormap object for custom entries; fall back to the # name string for standard matplotlib colormaps. - cmap: Union[str, Colormap] = self._custom_cmaps.get(name, name) + cmap: str | Colormap = self._custom_cmaps.get(name, name) fig = cmap_sample_plot(cmap, figsize=(self.plot_size[0] / 100, self.plot_size[1] / 100), bins=self.cmap_bins) self.figure_widget.embed_figure(fig) - def get_selected_cmap(self) -> Optional[Union[str, Colormap]]: + def get_selected_cmap(self) -> str | Colormap | None: """Return the currently selected colormap. Returns the `Colormap` object for custom entries or the name string @@ -373,7 +379,7 @@ def get_selected_cmap(self) -> Optional[Union[str, Colormap]]: return None return self._custom_cmaps.get(name, name) - def get(self) -> Optional[Union[str, Colormap]]: + def get(self) -> str | Colormap | None: """Return the currently selected colormap. * For standard matplotlib colormaps: returns the name string (backwards @@ -386,7 +392,7 @@ def get(self) -> Optional[Union[str, Colormap]]: """ return self.get_selected_cmap() - def get_cmap(self) -> Optional[Colormap]: + def get_cmap(self) -> Colormap | None: """Return the selected colormap always as a resolved `Colormap` object. Unlike `get()`, this method resolves named matplotlib colormaps to @@ -404,7 +410,7 @@ def get_cmap(self) -> Optional[Colormap]: return mpl.colormaps.get(name) - def add_cmap(self, cmap: CmapInput, label: Optional[str] = None) -> Optional[str]: + def add_cmap(self, cmap: CmapInput, label: str | None = None) -> str | None: """Dynamically add a new colormap entry to the selector. The new entry is appended to the combobox and becomes immediately @@ -435,11 +441,16 @@ def add_cmap(self, cmap: CmapInput, label: Optional[str] = None) -> Optional[str base = label or "custom" try: cmap = ListedColormap(cmap, name=base) - except Exception: #currently these are warnings, but maybe they should be replaced with raised exceptions? ValueError here and TypeError for the fallback. - CONSOLE_LOGGER.warning(f"List-like cmap ({cmap}) could not be added due to an error when converting to a `ListedColormap`.", exc_info=1) + except Exception: # currently these are warnings, but maybe they should be replaced with raised exceptions? ValueError here and TypeError for the fallback. + CONSOLE_LOGGER.warning( + f"List-like cmap ({cmap}) could not be added due to an error when converting to a `ListedColormap`.", + exc_info=1, + ) return None else: - CONSOLE_LOGGER.warning(f"Input of type {type(cmap)} was not a valid type for cmap. Expected a str, list or matplotlib Colormap") + CONSOLE_LOGGER.warning( + f"Input of type {type(cmap)} was not a valid type for cmap. Expected a str, list or matplotlib Colormap" + ) return None final_label = self._unique_label(base, existing) @@ -448,7 +459,7 @@ def add_cmap(self, cmap: CmapInput, label: Optional[str] = None) -> Optional[str self._populate_cmap_list(existing) return final_label - def set(self, value: Optional[CmapInput]) -> None: + def set(self, value: CmapInput | None) -> None: """Set the selected colormap. Accepts the same input types as `colormaps` list items: @@ -496,12 +507,15 @@ def set(self, value: Optional[CmapInput]) -> None: self._update_cmap_sample() return except Exception: - CONSOLE_LOGGER.debug("exception thrown when updating cmap sample from list value. visual cmap sample may be in invalid state?", exc_info=1) + CONSOLE_LOGGER.debug( + "exception thrown when updating cmap sample from list value. visual cmap sample may be in invalid state?", + exc_info=1, + ) pass self.figure_widget.clear() self.colormap_var.set("") - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: """Validate the current colormap selection. Returns: @@ -515,11 +529,13 @@ def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warni if name not in self.cmap_combobox["values"]: return self.apply_validation((False, f"Selected colormap '{name}' is not available.", "error")) return self.apply_validation((True, None, None)) - + + if __name__ == "__main__": - from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow from matplotlib.colors import LinearSegmentedColormap + from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow + root = BHoMBaseWindow() parent_container = root.content_frame @@ -541,9 +557,9 @@ def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warni selector_colours = CmapSelector( parent_container, colormaps=[ - bhom_blues, # list of hex strings - ["red", "orange", "yellow", "green"], # list of named colours - "tab10", # mixed with a named cmap + bhom_blues, # list of hex strings + ["red", "orange", "yellow", "green"], # list of named colours + "tab10", # mixed with a named cmap ], default_cmap=bhom_blues, item_title="2. Colour lists", @@ -560,9 +576,9 @@ def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warni selector_objects = CmapSelector( parent_container, colormaps=[ - custom_listed, # ListedColormap object - custom_linear, # LinearSegmentedColormap object - "coolwarm", # standard cmap alongside custom ones + custom_listed, # ListedColormap object + custom_linear, # LinearSegmentedColormap object + "coolwarm", # standard cmap alongside custom ones ], default_cmap=custom_linear, item_title="3. Colormap objects", @@ -602,8 +618,8 @@ def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warni root.mainloop() # After mainloop — demonstrate get() vs get_cmap() return types - print("selector_strings.get() :", selector_strings.get()) # str - print("selector_colours.get() :", selector_colours.get()) # Colormap object - print("selector_objects.get() :", selector_objects.get()) # Colormap object - print("selector_preset.get() :", selector_preset.get()) # str - print("selector_preset.get_cmap():", selector_preset.get_cmap()) # Colormap object \ No newline at end of file + print("selector_strings.get() :", selector_strings.get()) # str + print("selector_colours.get() :", selector_colours.get()) # Colormap object + print("selector_objects.get() :", selector_objects.get()) # Colormap object + print("selector_preset.get() :", selector_preset.get()) # str + print("selector_preset.get_cmap():", selector_preset.get_cmap()) # Colormap object diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/colour_picker.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/colour_picker.py index 503b64b2..2064abf2 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/colour_picker.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/colour_picker.py @@ -1,274 +1,275 @@ """Colour picker widget with themed popup and live RGB/hex preview.""" import tkinter as tk +from collections.abc import Callable from tkinter import ttk -from python_toolkit.bhom_tkinter.widgets.label import Label -from typing import Callable, Optional, Literal +from typing import Literal +from python_toolkit.bhom_tkinter.theming.scaling import scale, scale_pad from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget from python_toolkit.bhom_tkinter.widgets.button import Button -from python_toolkit.bhom_tkinter.theming.scaling import scale, scale_pad +from python_toolkit.bhom_tkinter.widgets.label import Label + class ColourPicker(BHoMBaseWidget): - """A simple colour picker widget where the swatch opens a themed colour dialog.""" - - def __init__( - self, - parent: ttk.Frame, - default_colour: str = "#ffffff", - swatch_width: int = 48, - swatch_height: int = 28, - command: Optional[Callable[[str], None]] = None, - **kwargs, - ) -> None: - """ - Args: - parent: Parent widget. - default_colour: Initial colour value in hex format. - swatch_width: Width of the clickable colour swatch in pixels. - swatch_height: Height of the clickable colour swatch in pixels. - command: Optional callback called with selected hex colour. - **kwargs: Additional Frame options. - """ - super().__init__(parent, **kwargs) - - self.command = command - self.colour_var = tk.StringVar(value=default_colour) - self.swatch_width = max(1, int(swatch_width)) - self.swatch_height = max(1, int(swatch_height)) - self._picker_window: Optional[tk.Toplevel] = None - self._popup_preview: Optional[tk.Canvas] = None - self._popup_swatch: Optional[int] = None - self._popup_hex_var: Optional[tk.StringVar] = None - self._popup_red_var: Optional[tk.IntVar] = None - self._popup_green_var: Optional[tk.IntVar] = None - self._popup_blue_var: Optional[tk.IntVar] = None - - controls = ttk.Frame(self.content_frame) - controls.pack(side="top", anchor=self._pack_anchor) - - self.preview = tk.Canvas( - controls, - width=self.swatch_width, - height=self.swatch_height, - highlightthickness=1, - cursor="hand2", - ) - self.preview.pack(anchor=self._pack_anchor) - self._swatch = self.preview.create_rectangle(0, 0, self.swatch_width, self.swatch_height, outline="#666666") - self.preview.bind("", lambda _event: self._select_colour()) - - self._update_preview(default_colour) - - def _select_colour(self) -> None: - """Open the themed colour picker popup.""" - if self._picker_window and self._picker_window.winfo_exists(): - self._picker_window.focus_force() - return - - current_colour = self.get() - red, green, blue = self._hex_to_rgb(current_colour) - - root_window = self.winfo_toplevel() - window = tk.Toplevel(root_window) - window.title("Select Colour") - window.transient(root_window) - window.resizable(False, False) - window.protocol("WM_DELETE_WINDOW", self._close_picker) - - self._picker_window = window - self._popup_red_var = tk.IntVar(value=red) - self._popup_green_var = tk.IntVar(value=green) - self._popup_blue_var = tk.IntVar(value=blue) - self._popup_hex_var = tk.StringVar(value=current_colour) - - container = ttk.Frame(window, padding=scale(10)) - container.pack(fill=tk.BOTH, expand=True) - - self._build_slider_row(container, "R", self._popup_red_var, 0) - self._build_slider_row(container, "G", self._popup_green_var, 1) - self._build_slider_row(container, "B", self._popup_blue_var, 2) - - hex_row = ttk.Frame(container) - hex_row.grid(row=3, column=0, sticky="ew", pady=scale_pad((8, 4))) - Label(hex_row, text="Hex").pack(side=tk.LEFT) - hex_entry = ttk.Entry(hex_row, textvariable=self._popup_hex_var, width=10) - hex_entry.pack(side=tk.LEFT, padx=scale_pad((8, 0))) - hex_entry.bind("", lambda _event: self._on_hex_entered()) - - preview_row = ttk.Frame(container) - preview_row.grid(row=4, column=0, sticky="w", pady=scale_pad((4, 8))) - Label(preview_row, text="Preview").pack(side=tk.LEFT) - self._popup_preview = tk.Canvas(preview_row, width=scale(48), height=scale(28), highlightthickness=1) - self._popup_preview.pack(side=tk.LEFT, padx=scale_pad((8, 0))) - self._popup_swatch = self._popup_preview.create_rectangle(0, 0, 48, 28, outline="#666666") - - button_row = ttk.Frame(container) - button_row.grid(row=5, column=0, sticky="e") - Button(button_row, text="Cancel", command=self._close_picker).pack(side=tk.LEFT, padx=scale_pad((0, 6))) - Button(button_row, text="Apply", command=self._apply_popup_colour).pack(side=tk.LEFT) - - container.columnconfigure(0, weight=1) - - self._on_rgb_changed() - window.grab_set() - hex_entry.focus_set() - - def _update_preview(self, colour: str) -> None: - """Render the selected colour in the preview swatch.""" - self.preview.itemconfig(self._swatch, fill=colour) - - def _build_slider_row(self, parent: ttk.Frame, label_text: str, value_var: tk.IntVar, row: int) -> None: - row_frame = ttk.Frame(parent) - row_frame.grid(row=row, column=0, sticky="ew", pady=scale_pad(2)) - - Label(row_frame, text=label_text).pack(side=tk.LEFT) - slider = ttk.Scale( - row_frame, - from_=0, - to=255, - orient=tk.HORIZONTAL, - style="ColourPicker.Horizontal.TScale", - command=lambda value, var=value_var: self._on_slider_move(var, value), - ) - slider.set(value_var.get()) - slider.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=scale_pad((8, 8))) - value_label = Label(row_frame, textvariable=value_var, width=4, anchor="e") - value_label.pack(side=tk.LEFT) - - def _on_slider_move(self, value_var: tk.IntVar, value: str) -> None: - value_var.set(int(float(value))) - self._on_rgb_changed() - - def _on_rgb_changed(self) -> None: - if not (self._popup_red_var and self._popup_green_var and self._popup_blue_var and self._popup_hex_var): - return - - colour = self._rgb_to_hex(self._popup_red_var.get(), self._popup_green_var.get(), self._popup_blue_var.get()) - self._popup_hex_var.set(colour) - self._update_popup_preview(colour) - - def _on_hex_entered(self) -> None: - if not self._popup_hex_var: - return - - red, green, blue = self._hex_to_rgb(self._popup_hex_var.get()) - if self._popup_red_var and self._popup_green_var and self._popup_blue_var: - self._popup_red_var.set(red) - self._popup_green_var.set(green) - self._popup_blue_var.set(blue) - self._popup_hex_var.set(self._rgb_to_hex(red, green, blue)) - self._update_popup_preview(self._popup_hex_var.get()) - - def _update_popup_preview(self, colour: str) -> None: - if self._popup_preview and self._popup_swatch is not None: - self._popup_preview.itemconfig(self._popup_swatch, fill=colour) - - def _apply_popup_colour(self) -> None: - if not self._popup_hex_var: - return - - selected = self._rgb_to_hex(*self._hex_to_rgb(self._popup_hex_var.get())) - self.set(selected) - if self.command: - self.command(selected) - self._fire_on_change(selected) - self._close_picker() - - def _close_picker(self) -> None: - if self._picker_window and self._picker_window.winfo_exists(): - try: - self._picker_window.grab_release() - except tk.TclError: - pass - self._picker_window.destroy() - - self._picker_window = None - self._popup_preview = None - self._popup_swatch = None - self._popup_hex_var = None - self._popup_red_var = None - self._popup_green_var = None - self._popup_blue_var = None - - @staticmethod - def _rgb_to_hex(red: int, green: int, blue: int) -> str: - red = max(0, min(255, int(red))) - green = max(0, min(255, int(green))) - blue = max(0, min(255, int(blue))) - return f"#{red:02x}{green:02x}{blue:02x}" - - @staticmethod - def _hex_to_rgb(colour: str) -> tuple[int, int, int]: - value = (colour or "").strip().lstrip("#") - if len(value) == 3: - value = "".join(ch * 2 for ch in value) - if len(value) != 6: - return 255, 255, 255 - try: - return int(value[0:2], 16), int(value[2:4], 16), int(value[4:6], 16) - except ValueError: - return 255, 255, 255 - - def get(self) -> str: - """Return the currently selected hex colour. - - Returns: - str: Selected colour in hex format. - """ - return self.colour_var.get() - - def set(self, value: str) -> None: - """Set the current colour and refresh the preview swatch. - - Args: - value: Colour value in hex format. - """ - self.colour_var.set(value) - self._update_preview(value) - - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: - """Validate the current colour value. - - Returns: - tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: - `(is_valid, message, severity)` where severity is `None` when - valid, or `"error"` for an invalid colour. - """ - colour = self.get() - if not colour: - return self.apply_validation((False, "No colour selected.", "error")) - stripped = colour.strip().lstrip("#") - if len(stripped) == 3: - stripped = "".join(ch * 2 for ch in stripped) - if len(stripped) != 6: - return self.apply_validation((False, f"Invalid colour value: '{colour}'.", "error")) - try: - int(stripped, 16) - except ValueError: - return self.apply_validation((False, f"Invalid colour value: '{colour}'.", "error")) - return self.apply_validation((True, None, None)) + """A simple colour picker widget where the swatch opens a themed colour dialog.""" + + def __init__( + self, + parent: ttk.Frame, + default_colour: str = "#ffffff", + swatch_width: int = 48, + swatch_height: int = 28, + command: Callable[[str], None] | None = None, + **kwargs, + ) -> None: + """Args: + parent: Parent widget. + default_colour: Initial colour value in hex format. + swatch_width: Width of the clickable colour swatch in pixels. + swatch_height: Height of the clickable colour swatch in pixels. + command: Optional callback called with selected hex colour. + **kwargs: Additional Frame options. + """ + super().__init__(parent, **kwargs) + + self.command = command + self.colour_var = tk.StringVar(value=default_colour) + self.swatch_width = max(1, int(swatch_width)) + self.swatch_height = max(1, int(swatch_height)) + self._picker_window: tk.Toplevel | None = None + self._popup_preview: tk.Canvas | None = None + self._popup_swatch: int | None = None + self._popup_hex_var: tk.StringVar | None = None + self._popup_red_var: tk.IntVar | None = None + self._popup_green_var: tk.IntVar | None = None + self._popup_blue_var: tk.IntVar | None = None + + controls = ttk.Frame(self.content_frame) + controls.pack(side="top", anchor=self._pack_anchor) + + self.preview = tk.Canvas( + controls, + width=self.swatch_width, + height=self.swatch_height, + highlightthickness=1, + cursor="hand2", + ) + self.preview.pack(anchor=self._pack_anchor) + self._swatch = self.preview.create_rectangle(0, 0, self.swatch_width, self.swatch_height, outline="#666666") + self.preview.bind("", lambda _event: self._select_colour()) + + self._update_preview(default_colour) + + def _select_colour(self) -> None: + """Open the themed colour picker popup.""" + if self._picker_window and self._picker_window.winfo_exists(): + self._picker_window.focus_force() + return + + current_colour = self.get() + red, green, blue = self._hex_to_rgb(current_colour) + + root_window = self.winfo_toplevel() + window = tk.Toplevel(root_window) + window.title("Select Colour") + window.transient(root_window) + window.resizable(False, False) + window.protocol("WM_DELETE_WINDOW", self._close_picker) + + self._picker_window = window + self._popup_red_var = tk.IntVar(value=red) + self._popup_green_var = tk.IntVar(value=green) + self._popup_blue_var = tk.IntVar(value=blue) + self._popup_hex_var = tk.StringVar(value=current_colour) + + container = ttk.Frame(window, padding=scale(10)) + container.pack(fill=tk.BOTH, expand=True) + + self._build_slider_row(container, "R", self._popup_red_var, 0) + self._build_slider_row(container, "G", self._popup_green_var, 1) + self._build_slider_row(container, "B", self._popup_blue_var, 2) + + hex_row = ttk.Frame(container) + hex_row.grid(row=3, column=0, sticky="ew", pady=scale_pad((8, 4))) + Label(hex_row, text="Hex").pack(side=tk.LEFT) + hex_entry = ttk.Entry(hex_row, textvariable=self._popup_hex_var, width=10) + hex_entry.pack(side=tk.LEFT, padx=scale_pad((8, 0))) + hex_entry.bind("", lambda _event: self._on_hex_entered()) + + preview_row = ttk.Frame(container) + preview_row.grid(row=4, column=0, sticky="w", pady=scale_pad((4, 8))) + Label(preview_row, text="Preview").pack(side=tk.LEFT) + self._popup_preview = tk.Canvas(preview_row, width=scale(48), height=scale(28), highlightthickness=1) + self._popup_preview.pack(side=tk.LEFT, padx=scale_pad((8, 0))) + self._popup_swatch = self._popup_preview.create_rectangle(0, 0, 48, 28, outline="#666666") + + button_row = ttk.Frame(container) + button_row.grid(row=5, column=0, sticky="e") + Button(button_row, text="Cancel", command=self._close_picker).pack(side=tk.LEFT, padx=scale_pad((0, 6))) + Button(button_row, text="Apply", command=self._apply_popup_colour).pack(side=tk.LEFT) + + container.columnconfigure(0, weight=1) + + self._on_rgb_changed() + window.grab_set() + hex_entry.focus_set() + + def _update_preview(self, colour: str) -> None: + """Render the selected colour in the preview swatch.""" + self.preview.itemconfig(self._swatch, fill=colour) + + def _build_slider_row(self, parent: ttk.Frame, label_text: str, value_var: tk.IntVar, row: int) -> None: + row_frame = ttk.Frame(parent) + row_frame.grid(row=row, column=0, sticky="ew", pady=scale_pad(2)) + + Label(row_frame, text=label_text).pack(side=tk.LEFT) + slider = ttk.Scale( + row_frame, + from_=0, + to=255, + orient=tk.HORIZONTAL, + style="ColourPicker.Horizontal.TScale", + command=lambda value, var=value_var: self._on_slider_move(var, value), + ) + slider.set(value_var.get()) + slider.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=scale_pad((8, 8))) + value_label = Label(row_frame, textvariable=value_var, width=4, anchor="e") + value_label.pack(side=tk.LEFT) + + def _on_slider_move(self, value_var: tk.IntVar, value: str) -> None: + value_var.set(int(float(value))) + self._on_rgb_changed() + + def _on_rgb_changed(self) -> None: + if not (self._popup_red_var and self._popup_green_var and self._popup_blue_var and self._popup_hex_var): + return + + colour = self._rgb_to_hex(self._popup_red_var.get(), self._popup_green_var.get(), self._popup_blue_var.get()) + self._popup_hex_var.set(colour) + self._update_popup_preview(colour) + + def _on_hex_entered(self) -> None: + if not self._popup_hex_var: + return + + red, green, blue = self._hex_to_rgb(self._popup_hex_var.get()) + if self._popup_red_var and self._popup_green_var and self._popup_blue_var: + self._popup_red_var.set(red) + self._popup_green_var.set(green) + self._popup_blue_var.set(blue) + self._popup_hex_var.set(self._rgb_to_hex(red, green, blue)) + self._update_popup_preview(self._popup_hex_var.get()) + + def _update_popup_preview(self, colour: str) -> None: + if self._popup_preview and self._popup_swatch is not None: + self._popup_preview.itemconfig(self._popup_swatch, fill=colour) + + def _apply_popup_colour(self) -> None: + if not self._popup_hex_var: + return + + selected = self._rgb_to_hex(*self._hex_to_rgb(self._popup_hex_var.get())) + self.set(selected) + if self.command: + self.command(selected) + self._fire_on_change(selected) + self._close_picker() + + def _close_picker(self) -> None: + if self._picker_window and self._picker_window.winfo_exists(): + try: + self._picker_window.grab_release() + except tk.TclError: + pass + self._picker_window.destroy() + + self._picker_window = None + self._popup_preview = None + self._popup_swatch = None + self._popup_hex_var = None + self._popup_red_var = None + self._popup_green_var = None + self._popup_blue_var = None + + @staticmethod + def _rgb_to_hex(red: int, green: int, blue: int) -> str: + red = max(0, min(255, int(red))) + green = max(0, min(255, int(green))) + blue = max(0, min(255, int(blue))) + return f"#{red:02x}{green:02x}{blue:02x}" + + @staticmethod + def _hex_to_rgb(colour: str) -> tuple[int, int, int]: + value = (colour or "").strip().lstrip("#") + if len(value) == 3: + value = "".join(ch * 2 for ch in value) + if len(value) != 6: + return 255, 255, 255 + try: + return int(value[0:2], 16), int(value[2:4], 16), int(value[4:6], 16) + except ValueError: + return 255, 255, 255 + + def get(self) -> str: + """Return the currently selected hex colour. + + Returns: + str: Selected colour in hex format. + """ + return self.colour_var.get() + + def set(self, value: str) -> None: + """Set the current colour and refresh the preview swatch. + + Args: + value: Colour value in hex format. + """ + self.colour_var.set(value) + self._update_preview(value) + + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: + """Validate the current colour value. + + Returns: + tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + `(is_valid, message, severity)` where severity is `None` when + valid, or `"error"` for an invalid colour. + """ + colour = self.get() + if not colour: + return self.apply_validation((False, "No colour selected.", "error")) + stripped = colour.strip().lstrip("#") + if len(stripped) == 3: + stripped = "".join(ch * 2 for ch in stripped) + if len(stripped) != 6: + return self.apply_validation((False, f"Invalid colour value: '{colour}'.", "error")) + try: + int(stripped, 16) + except ValueError: + return self.apply_validation((False, f"Invalid colour value: '{colour}'.", "error")) + return self.apply_validation((True, None, None)) if __name__ == "__main__": - from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow - from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions - - root = BHoMBaseWindow() - parent_container = root.content_frame - - def on_colour_changed(colour: str) -> None: - """Print selected colour in the standalone example.""" - print(f"Selected colour: {colour}") - - colour_picker = ColourPicker( - parent_container, - command=on_colour_changed, - item_title="Colour Picker", - helper_text="Pick a colour for plotting.", - alignment="center", - build_options=PackingOptions(padx=10, pady=10), - ) - colour_picker.build() - - root.mainloop() + from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow + from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions + + root = BHoMBaseWindow() + parent_container = root.content_frame + + def on_colour_changed(colour: str) -> None: + """Print selected colour in the standalone example.""" + print(f"Selected colour: {colour}") + + colour_picker = ColourPicker( + parent_container, + command=on_colour_changed, + item_title="Colour Picker", + helper_text="Pick a colour for plotting.", + alignment="center", + build_options=PackingOptions(padx=10, pady=10), + ) + colour_picker.build() + + root.mainloop() diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/drop_down_selection.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/drop_down_selection.py index f5afb4dc..2a82ec32 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/drop_down_selection.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/drop_down_selection.py @@ -1,157 +1,160 @@ """Dropdown selection widget built from ttk.Combobox.""" import tkinter as tk +from collections.abc import Callable from tkinter import ttk -from typing import Optional, Callable, List, Literal +from typing import Literal +from python_toolkit.bhom.logging import CONSOLE_LOGGER from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget + class DropDownSelection(BHoMBaseWidget): - """A reusable dropdown selection widget built from a list of options.""" - - def __init__( - self, - parent, - options: Optional[List[str]] = None, - command: Optional[Callable[[str], None]] = None, - default: Optional[str] = None, - width: int = 20, - state: str = "normal", - value_var: Optional[tk.StringVar] = None, - **kwargs): - """ - Args: - parent (tk.Widget): The parent widget. - options (list, optional): List of selectable options. - command (callable, optional): Called with selected value when changed. - default (str, optional): Default selected value. - width (int): Width of the dropdown widget in characters. - state (str): Combobox state ("normal", "readonly", or "disabled"). - item_title (str, optional): Optional header text shown at the top of the widget frame. - helper_text (str, optional): Optional helper text shown above the dropdown. - **kwargs: Additional Frame options. - """ - super().__init__(parent, **kwargs) - - self.options = [str(option) for option in (options or [])] - self.command = command - self.value_var = value_var or tk.StringVar() - - # Create the combobox in the content frame - self.combobox = ttk.Combobox( - self.content_frame, - textvariable=self.value_var, - values=self.options, - width=width, - state=state, - justify=self._text_justify, - ) - self.combobox.pack(side="top", fill="x") - - # Bind selection event - self.combobox.bind("<>", self._on_select) - - # Set default value - if default is not None and default in self.options: - self.set(default) - elif self.options: - self.value_var.set(self.options[0]) - - def _on_select(self, event=None): - """Handle selection change event. - - Args: - event: Tkinter event (optional). - """ - if self.command: - self.command(self.get()) - self._fire_on_change(self.get()) - - def get(self) -> str: - """Return the currently selected value. - - Returns: - str: Selected option value. - """ - return self.value_var.get() - - def set(self, value: str): - """Set the selected value. - - Args: - value: Option value to select. - """ - if value in self.options: - self.value_var.set(value) - else: - CONSOLE_LOGGER.warning("Selected value was not in the given options, and so was not set.") - - def set_options(self, options: List[str], default: Optional[str] = None): - """Replace the available options and optionally set a new default. - - Args: - options: New list of selectable options. - default: Optional value to select after updating options. - """ - self.options = [str(option) for option in (options or [])] - self.combobox['values'] = self.options - - if default is not None and default in self.options: - self.set(default) - elif self.options: - self.value_var.set(self.options[0]) - else: - self.value_var.set("") - - def get_selected_index(self) -> int: - """Return the index of the currently selected option. - - Returns: - int: Index of selected option, or -1 if not found. - """ - try: - return self.options.index(self.get()) - except ValueError: - return -1 - - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: - """Validate the current selection. - - Returns: - tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: - `(is_valid, message, severity)` where severity is `None` when - valid, or `"error"` for an invalid selection. - """ - selected = self.get() - if not selected: - return getattr(self, "apply_validation")((False, "No option selected.", "error")) - if selected not in self.options: - return getattr(self, "apply_validation")((False, f"Selected option '{selected}' is not available.", "error")) - return getattr(self, "apply_validation")((True, None, None)) + """A reusable dropdown selection widget built from a list of options.""" + + def __init__( + self, + parent, + options: list[str] | None = None, + command: Callable[[str], None] | None = None, + default: str | None = None, + width: int = 20, + state: str = "normal", + value_var: tk.StringVar | None = None, + **kwargs, + ): + """Args: + parent (tk.Widget): The parent widget. + options (list, optional): List of selectable options. + command (callable, optional): Called with selected value when changed. + default (str, optional): Default selected value. + width (int): Width of the dropdown widget in characters. + state (str): Combobox state ("normal", "readonly", or "disabled"). + item_title (str, optional): Optional header text shown at the top of the widget frame. + helper_text (str, optional): Optional helper text shown above the dropdown. + **kwargs: Additional Frame options. + """ + super().__init__(parent, **kwargs) + + self.options = [str(option) for option in (options or [])] + self.command = command + self.value_var = value_var or tk.StringVar() + + # Create the combobox in the content frame + self.combobox = ttk.Combobox( + self.content_frame, + textvariable=self.value_var, + values=self.options, + width=width, + state=state, + justify=self._text_justify, + ) + self.combobox.pack(side="top", fill="x") + + # Bind selection event + self.combobox.bind("<>", self._on_select) + + # Set default value + if default is not None and default in self.options: + self.set(default) + elif self.options: + self.value_var.set(self.options[0]) + + def _on_select(self, event=None): + """Handle selection change event. + + Args: + event: Tkinter event (optional). + """ + if self.command: + self.command(self.get()) + self._fire_on_change(self.get()) + + def get(self) -> str: + """Return the currently selected value. + + Returns: + str: Selected option value. + """ + return self.value_var.get() + + def set(self, value: str): + """Set the selected value. + + Args: + value: Option value to select. + """ + if value in self.options: + self.value_var.set(value) + else: + CONSOLE_LOGGER.warning("Selected value was not in the given options, and so was not set.") + + def set_options(self, options: list[str], default: str | None = None): + """Replace the available options and optionally set a new default. + + Args: + options: New list of selectable options. + default: Optional value to select after updating options. + """ + self.options = [str(option) for option in (options or [])] + self.combobox["values"] = self.options + + if default is not None and default in self.options: + self.set(default) + elif self.options: + self.value_var.set(self.options[0]) + else: + self.value_var.set("") + + def get_selected_index(self) -> int: + """Return the index of the currently selected option. + + Returns: + int: Index of selected option, or -1 if not found. + """ + try: + return self.options.index(self.get()) + except ValueError: + return -1 + + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: + """Validate the current selection. + + Returns: + tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + `(is_valid, message, severity)` where severity is `None` when + valid, or `"error"` for an invalid selection. + """ + selected = self.get() + if not selected: + return self.apply_validation((False, "No option selected.", "error")) + if selected not in self.options: + return self.apply_validation((False, f"Selected option '{selected}' is not available.", "error")) + return self.apply_validation((True, None, None)) -if __name__ == "__main__": - from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow - from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions - - def on_selection(value): - """Print selected value in the standalone example.""" - print(f"Selected: {value}") - - root = BHoMBaseWindow(theme_mode="light") - parent_frame = root.content_frame - - widget = DropDownSelection( - parent_frame, - options=["Option A", "Option B", "Option C", "Option D", "Option E"], - command=on_selection, - default="Option C", - width=30, - item_title="Choose an Option", - helper_text="Select one option from the dropdown list.", - alignment="center", - build_options=PackingOptions(padx=20, pady=20) - ) - widget.build() - - root.mainloop() +if __name__ == "__main__": + from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow + from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions + + def on_selection(value): + """Print selected value in the standalone example.""" + print(f"Selected: {value}") + + root = BHoMBaseWindow(theme_mode="light") + parent_frame = root.content_frame + + widget = DropDownSelection( + parent_frame, + options=["Option A", "Option B", "Option C", "Option D", "Option E"], + command=on_selection, + default="Option C", + width=30, + item_title="Choose an Option", + helper_text="Select one option from the dropdown list.", + alignment="center", + build_options=PackingOptions(padx=20, pady=20), + ) + widget.build() + + root.mainloop() diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/figure_container.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/figure_container.py index 2cf03d89..7ea5a186 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/figure_container.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/figure_container.py @@ -1,32 +1,30 @@ -"""Container widget for embedding matplotlib figures or image content.""" +"""Container widget for embedding matplotlib figures or image content.""" import tkinter as tk from tkinter import ttk -from python_toolkit.bhom_tkinter.widgets.label import Label -from typing import Optional, Any, Literal +from typing import Any, Literal + +import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure -import matplotlib.pyplot as plt -from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget -import matplotlib as mpl + from python_toolkit.bhom_tkinter.theming.scaling import scale +from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget +from python_toolkit.bhom_tkinter.widgets.label import Label class FigureContainer(BHoMBaseWidget): - """ - A reusable widget for embedding matplotlib figures and images. - """ + """A reusable widget for embedding matplotlib figures and images.""" def __init__( self, parent: ttk.Frame, auto_size: bool = False, - rigid_width: Optional[int] = None, - rigid_height: Optional[int] = None, - **kwargs + rigid_width: int | None = None, + rigid_height: int | None = None, + **kwargs, ) -> None: - """ - Initialize the FigureContainer widget. + """Initialize the FigureContainer widget. Args: parent: Parent widget @@ -47,14 +45,14 @@ def __init__( if self.rigid_height is not None: self.content_frame.config(height=self.rigid_height) - self.figure: Optional[Figure] = None - self.image: Optional[Any] = None - self.image_file: Optional[str] = None - self._original_pil_image: Optional[Any] = None + self.figure: Figure | None = None + self.image: Any | None = None + self.image_file: str | None = None + self._original_pil_image: Any | None = None - self.canvas: Optional[FigureCanvasTkAgg] = None - self.image_label: Optional[ttk.Label] = None - self._fit_after_id: Optional[str] = None + self.canvas: FigureCanvasTkAgg | None = None + self.image_label: ttk.Label | None = None + self._fit_after_id: str | None = None self._fit_attempts: int = 0 def _clear_children(self) -> None: @@ -149,6 +147,7 @@ def embed_image_file(self, file_path: str) -> None: self.image_file = file_path try: from PIL import Image, ImageTk + pil_image = Image.open(file_path) self._original_pil_image = pil_image self._close_held_figure() @@ -231,6 +230,7 @@ def _scale_image_to_fit_once(self): try: from PIL import Image, ImageTk + img_width, img_height = self._original_pil_image.size scale = min(frame_width / img_width, frame_height / img_height) new_width = int(img_width * scale) @@ -274,9 +274,11 @@ def set(self, value): elif isinstance(value, str): self.embed_image_file(value) else: - raise ValueError("Unsupported value type for FigureContainer. Must be Figure, PhotoImage, or file path string.") + raise ValueError( + "Unsupported value type for FigureContainer. Must be Figure, PhotoImage, or file path string." + ) - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: """Validate the current content of the figure container.""" if self.figure is not None: return self.apply_validation((True, None, None)) @@ -287,9 +289,10 @@ def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warni if __name__ == "__main__": import numpy as np + from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow - from python_toolkit.bhom_tkinter.widgets.validated_entry_box import ValidatedEntryBox from python_toolkit.bhom_tkinter.widgets._grid_options import GridOptions + from python_toolkit.bhom_tkinter.widgets.validated_entry_box import ValidatedEntryBox def make_plot(freq: float) -> Figure: x = np.linspace(0, 2 * np.pi, 300) diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/label.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/label.py index 244c6106..c5c3a234 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/label.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/label.py @@ -1,6 +1,6 @@ -from tkinter import ttk import tkinter as tk -from typing import Optional, Literal +from tkinter import ttk +from typing import Literal from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget @@ -15,23 +15,24 @@ class Label(BHoMBaseWidget): """ def __init__( - self, - parent, - text: str = "", - item_title: Optional[str] = None, - helper_text: Optional[str] = None, - alignment: Optional[str] = None, - image=None, - style=None, - justify=None, - wraplength=None, - anchor=None, - width=None, - compound=None, - textvariable=None, - foreground=None, - font=None, - **kwargs): + self, + parent, + text: str = "", + item_title: str | None = None, + helper_text: str | None = None, + alignment: str | None = None, + image=None, + style=None, + justify=None, + wraplength=None, + anchor=None, + width=None, + compound=None, + textvariable=None, + foreground=None, + font=None, + **kwargs, + ): def resolve(explicit_value, key: str, default=None): fallback = kwargs.pop(key, default) return explicit_value if explicit_value is not None else fallback @@ -120,20 +121,19 @@ def set(self, value): self._image_ref = value self.label.configure(image=self._image_ref, text="") - def update_text(self, new_text: str): """Backward-compatible method name used previously to update label text.""" self.set(new_text) # Provide a generic `update` alias for convenience (matches previous API), # while remaining compatible with tkinter's parameterless `update()`. - def update(self, new_text: Optional[str] = None): + def update(self, new_text: str | None = None): if new_text is None: super().update() return self.update_text(new_text) - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: """Validate the current content of the label. Returns: @@ -141,9 +141,8 @@ def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warni `(is_valid, message, severity)` where severity is `None` when valid, or `"error"` for invalid content. """ - - #always true - return getattr(self, "apply_validation")((True, None, None)) + # always true + return self.apply_validation((True, None, None)) if __name__ == "__main__": @@ -153,10 +152,21 @@ def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warni root = BHoMBaseWindow() parent_frame = root.content_frame - label_widget = Label(parent_frame, text="Hello, World!", build_options=PackingOptions(anchor="n", padx=10, pady=10), alignment="right") + label_widget = Label( + parent_frame, + text="Hello, World!", + build_options=PackingOptions(anchor="n", padx=10, pady=10), + alignment="right", + ) label_widget.build() - label_widget2 = Label(parent_frame, text="Warning: This is a BHoM warning label.", build_options=PackingOptions(anchor="n", padx=10, pady=10), alignment="left", style="Warning.TLabel") + label_widget2 = Label( + parent_frame, + text="Warning: This is a BHoM warning label.", + build_options=PackingOptions(anchor="n", padx=10, pady=10), + alignment="left", + style="Warning.TLabel", + ) label_widget2.build() - root.mainloop() \ No newline at end of file + root.mainloop() diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/list_box.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/list_box.py index 0493e0a2..e273cb2a 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/list_box.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/list_box.py @@ -3,37 +3,38 @@ from __future__ import annotations import tkinter as tk -from tkinter import filedialog, ttk -from typing import Optional, Literal +from tkinter import ttk +from typing import Literal +from python_toolkit.bhom_tkinter.theming.scaling import scale_pad from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget from python_toolkit.bhom_tkinter.widgets.button import Button -from python_toolkit.bhom_tkinter.theming.scaling import scale_pad + class ScrollableListBox(BHoMBaseWidget): """A reusable listbox widget with auto-hiding scrollbar.""" def __init__( - self, - parent: ttk.Frame, - items=None, - selectmode=tk.MULTIPLE, - height=None, - width=None, - show_selection_controls=False, - **kwargs): - """ - Args: - parent (ttk.Frame): The parent widget. - items (list, optional): List of items to populate the listbox. - selectmode (str): Selection mode for the listbox (SINGLE, MULTIPLE, etc.). - height (int, optional): Height of the listbox. Defaults to number of items. - width (int, optional): Width of the listbox in characters. If None, listbox expands to fill available space. - show_selection_controls (bool): Show Select All and Deselect All buttons. - **kwargs: Additional Frame options. + self, + parent: ttk.Frame, + items=None, + selectmode=tk.MULTIPLE, + height=None, + width=None, + show_selection_controls=False, + **kwargs, + ): + """Args: + parent (ttk.Frame): The parent widget. + items (list, optional): List of items to populate the listbox. + selectmode (str): Selection mode for the listbox (SINGLE, MULTIPLE, etc.). + height (int, optional): Height of the listbox. Defaults to number of items. + width (int, optional): Width of the listbox in characters. If None, listbox expands to fill available space. + show_selection_controls (bool): Show Select All and Deselect All buttons. + **kwargs: Additional Frame options. """ super().__init__(parent, **kwargs) - + self.items = items or [] self._cached_options = [str(item) for item in self.items] self._cached_selection: list[str] = [] @@ -67,11 +68,11 @@ def __init__( self.listbox = tk.Listbox(self._lb_container, **listbox_options) self.listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) self.scrollbar.config(command=self.listbox.yview) - + # Populate with items for item in self.items: self.listbox.insert(tk.END, item) - + # Auto-hide scrollbar when not needed self.listbox.bind("", self._on_configure) self.listbox.bind("<>", self._on_selection_change) @@ -79,7 +80,6 @@ def __init__( self._on_configure() if show_selection_controls: - select_widget = Button(self.content_frame, text="Select All", command=self.select_all) select_widget.grid(row=1, column=0, sticky="ns", padx=scale_pad((0, 4)), pady=scale_pad((8, 0))) self.select_all_button = select_widget.button @@ -87,7 +87,7 @@ def __init__( deselect_widget = Button(self.content_frame, text="Deselect All", command=self.deselect_all) deselect_widget.grid(row=1, column=1, sticky="ns", padx=scale_pad((4, 0)), pady=scale_pad((8, 0))) self.deselect_all_button = deselect_widget.button - + def _on_configure(self, event=None): """Hide scrollbar if all items fit in the visible area.""" if self.listbox.size() <= int(self.listbox.cget("height")): @@ -127,7 +127,7 @@ def set_selections(self, items): if item in items: self.listbox.selection_set(index) self._sync_cache_from_widget() - + def get_selection(self): """Return a list of selected items. @@ -138,7 +138,7 @@ def get_selection(self): return list(self._cached_selection) selected_indices = self.listbox.curselection() return [self.listbox.get(i) for i in selected_indices] - + def get_selection_indices(self): """Return tuple of selected indices. @@ -158,7 +158,7 @@ def deselect_all(self): """Clear all selected items in the listbox.""" self.listbox.selection_clear(0, tk.END) self._sync_cache_from_widget() - + def insert(self, index, item): """Insert an item at the specified index. @@ -169,7 +169,7 @@ def insert(self, index, item): self.listbox.insert(index, item) self._sync_cache_from_widget() self._on_configure() - + def delete(self, index): """Delete an item at the specified index. @@ -179,7 +179,7 @@ def delete(self, index): self.listbox.delete(index) self._sync_cache_from_widget() self._on_configure() - + def clear(self): """Clear all items from the listbox.""" self.listbox.delete(0, tk.END) @@ -222,7 +222,7 @@ def set(self, value): self.listbox.activate(index) self.listbox.see(index) self._sync_cache_from_widget() - + def get(self): """Get all currently selected items. @@ -240,8 +240,8 @@ def get_options(self): if not self._is_listbox_alive(): return list(self._cached_options) return [self.listbox.get(i) for i in range(self.listbox.size())] - - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: """Validate the current listbox state. Returns: @@ -268,27 +268,28 @@ def _sync_items_from_listbox(self) -> None: """Synchronize cached items with the listbox contents.""" self._sync_cache_from_widget() -if __name__ == "__main__": +if __name__ == "__main__": from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions root = BHoMBaseWindow(theme_mode="light") parent_container = root.content_frame - + items = [f"Item {i}" for i in range(1, 21)] - root.widgets.append(ScrollableListBox( - parent_container, - items=items, - height=10, - show_selection_controls=True, - item_title="List Box", - helper_text="Select items from the list.", - build_options=PackingOptions(padx=10, pady=10) - )) + root.widgets.append( + ScrollableListBox( + parent_container, + items=items, + height=10, + show_selection_controls=True, + item_title="List Box", + helper_text="Select items from the list.", + build_options=PackingOptions(padx=10, pady=10), + ) + ) root.widgets[-1].build() - root.mainloop() - - print("Selected items:", root.widgets[-1].get()) \ No newline at end of file + + print("Selected items:", root.widgets[-1].get()) diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/path_selector.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/path_selector.py index 6e9e7329..fc6d69d7 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/path_selector.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/path_selector.py @@ -1,39 +1,40 @@ """Path selection widget for file or directory browsing.""" import tkinter as tk -from tkinter import filedialog, ttk from pathlib import Path -from typing import Optional, Literal +from tkinter import filedialog, ttk +from typing import Literal +from python_toolkit.bhom_tkinter.theming.scaling import scale_pad from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget from python_toolkit.bhom_tkinter.widgets.button import Button -from python_toolkit.bhom_tkinter.theming.scaling import scale_pad + class PathSelector(BHoMBaseWidget): """A reusable path/file selector widget with a button and a readonly entry.""" def __init__( - self, - parent: ttk.Frame, - button_text="Browse...", - filetypes=None, - command=None, - initialdir=None, - entry_width=40, - button_width=25, - mode="file", - **kwargs): - """ - Args: - parent (tk.Widget): The parent widget. - button_text (str): The text to display on the button. - filetypes (list, optional): List of filetypes for the dialog. - command (callable, optional): Called with the file path after selection. - initialdir (str, optional): Initial directory for the file dialog. - mode (str): Either "file" or "directory" to select files or directories. - item_title (str, optional): Optional header text shown at the top of the widget frame. - helper_text (str, optional): Optional helper text shown above the entry box. - **kwargs: Additional Frame options. + self, + parent: ttk.Frame, + button_text="Browse...", + filetypes=None, + command=None, + initialdir=None, + entry_width=40, + button_width=25, + mode="file", + **kwargs, + ): + """Args: + parent (tk.Widget): The parent widget. + button_text (str): The text to display on the button. + filetypes (list, optional): List of filetypes for the dialog. + command (callable, optional): Called with the file path after selection. + initialdir (str, optional): Initial directory for the file dialog. + mode (str): Either "file" or "directory" to select files or directories. + item_title (str, optional): Optional header text shown at the top of the widget frame. + helper_text (str, optional): Optional helper text shown above the entry box. + **kwargs: Additional Frame options. """ super().__init__(parent, **kwargs) self.path_var = tk.StringVar() @@ -51,14 +52,9 @@ def __init__( def _on_click(self): if self.mode == "directory": - path = filedialog.askdirectory( - initialdir=self.initialdir - ) + path = filedialog.askdirectory(initialdir=self.initialdir) else: - path = filedialog.askopenfilename( - filetypes=self.filetypes, - initialdir=self.initialdir - ) + path = filedialog.askopenfilename(filetypes=self.filetypes, initialdir=self.initialdir) if path: selected_path = Path(path) self.path_var.set(str(selected_path)) @@ -73,8 +69,8 @@ def get(self) -> str: str: Selected file or directory path. """ return self.path_var.get() - - def set(self, value: Optional[str]): + + def set(self, value: str | None): """Set the file path in the entry. Args: @@ -86,7 +82,7 @@ def set(self, value: Optional[str]): self.path_var.set(str(Path(value))) - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: """Validate the currently selected path. Returns: @@ -110,7 +106,6 @@ def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warni if __name__ == "__main__": - from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions @@ -122,17 +117,17 @@ def on_file_selected(path): print(f"Selected: {path}") path_selector = PathSelector( - parent_container, - button_text="Select File", - filetypes=[("All Files", "*.*")], + parent_container, + button_text="Select File", + filetypes=[("All Files", "*.*")], command=on_file_selected, item_title="Path Selector", helper_text="Select a file from your system.", build_options=PackingOptions(padx=20, pady=20), button_width=15, entry_width=50, - alignment="center" + alignment="center", ) path_selector.build() - root.mainloop() \ No newline at end of file + root.mainloop() diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/radio_selection.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/radio_selection.py index 95c573d7..1ae5e643 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/radio_selection.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/radio_selection.py @@ -2,202 +2,202 @@ import tkinter as tk from tkinter import ttk -from typing import Optional, Literal +from typing import Literal -from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget from python_toolkit.bhom_tkinter.theming.scaling import scale_pad +from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget + class RadioSelection(BHoMBaseWidget): - """A reusable radio selection widget built from a list of fields.""" - - def __init__( - self, - parent, - fields=None, - command=None, - default=None, - orient="vertical", - options_fill_extents: bool = False, - max_per_line=None, - **kwargs): - """ - Args: - parent (tk.Widget): The parent widget. - fields (list, optional): List of selectable fields. - command (callable, optional): Called with selected value when changed. - default (str, optional): Default selected value. - orient (str): Either "vertical" or "horizontal". - options_fill_extents (bool): If `True`, radio option rows expand to - fill their available width in the options frame. - max_per_line (int, optional): Maximum items per row/column before wrapping. - item_title (str, optional): Optional header text shown at the top of the widget frame. - helper_text (str, optional): Optional helper text shown above the entry box. - **kwargs: Additional Frame options. - """ - super().__init__(parent, **kwargs) - - self.fields = [str(field) for field in (fields or [])] - self.command = command - self.orient = orient.lower() - self.options_fill_extents = self._normalise_bool(options_fill_extents) - self.max_per_line = max_per_line - self.value_var = tk.StringVar() - self._buttons = [] - - # Sub-frame for radio button controls - self.buttons_frame = ttk.Frame(self.content_frame) - if self.options_fill_extents: - self.buttons_frame.pack(side="top", fill="x", expand=True) - else: - self.buttons_frame.pack(side="top", anchor=self._pack_anchor) - - self._build_buttons() - - if default is not None: - self.set(default) - elif self.fields: - self.value_var.set(self.fields[0]) - - def _build_buttons(self): - """Create radio buttons from current fields.""" - for button in self._buttons: - button.destroy() - self._buttons.clear() - for index in range(self.buttons_frame.grid_size()[0] + 1): - self.buttons_frame.grid_columnconfigure(index, weight=0) - - for index, field in enumerate(self.fields): - sticky = self._grid_sticky - button = ttk.Radiobutton( - self.buttons_frame, - text=field, - variable=self.value_var, - value=field, - style="Radio.TRadiobutton", - command=lambda f=field: self._select_field(f), - ) - self.align_child_text(button) - - if self.max_per_line and self.max_per_line > 0: - if self.orient == "horizontal": - row = index // self.max_per_line - column = index % self.max_per_line - else: - row = index % self.max_per_line - column = index // self.max_per_line - button.grid( - row=row, - column=column, - padx=scale_pad((0, 10)), - pady=scale_pad((0, 4)), - sticky=("ew" if self.options_fill_extents else sticky), - ) - if self.options_fill_extents: - self.buttons_frame.grid_columnconfigure(column, weight=1) - elif self.orient == "horizontal": - button.grid( - row=0, - column=index, - padx=scale_pad((0, 10)), - pady=scale_pad((0, 4)), - sticky=("ew" if self.options_fill_extents else sticky), - ) - if self.options_fill_extents: - self.buttons_frame.grid_columnconfigure(index, weight=1) - else: - button.grid( - row=index, - column=0, - padx=scale_pad((0, 10)), - pady=scale_pad((0, 4)), - sticky=("ew" if self.options_fill_extents else sticky), - ) - if self.options_fill_extents: - self.buttons_frame.grid_columnconfigure(0, weight=1) - self._buttons.append(button) - - def _select_field(self, field): - """Handle radio button selection.""" - if self.command: - self.command(self.get()) - self._fire_on_change(self.get()) - - def get(self): - """Return the currently selected value. - - Returns: - str: Currently selected field label. - """ - return self.value_var.get() - - def set(self, value): - """Set the selected value if it exists in fields. - - Args: - value: Field label to select. - """ - value = str(value) - if value in self.fields: - self.value_var.set(value) - - def set_fields(self, fields, default=None): - """Replace the available fields and rebuild the widget. - - Args: - fields: New available field names. - default: Optional default field to select. - """ - self.fields = [str(field) for field in (fields or [])] - self._build_buttons() - - if default is not None: - self.set(default) - elif self.fields: - self.value_var.set(self.fields[0]) - else: - self.value_var.set("") - - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: - """Validate the currently selected radio option. - - Returns: - tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: - `(is_valid, message, severity)` where severity is `None` when - valid, or `"error"` for an invalid selection. - """ - selected = self.get() - if not selected: - return self.apply_validation((False, "No option selected.", "error")) - if selected not in self.fields: - return self.apply_validation((False, f"Selected option '{selected}' is not available.", "error")) - return self.apply_validation((True, None, None)) + """A reusable radio selection widget built from a list of fields.""" + + def __init__( + self, + parent, + fields=None, + command=None, + default=None, + orient="vertical", + options_fill_extents: bool = False, + max_per_line=None, + **kwargs, + ): + """Args: + parent (tk.Widget): The parent widget. + fields (list, optional): List of selectable fields. + command (callable, optional): Called with selected value when changed. + default (str, optional): Default selected value. + orient (str): Either "vertical" or "horizontal". + options_fill_extents (bool): If `True`, radio option rows expand to + fill their available width in the options frame. + max_per_line (int, optional): Maximum items per row/column before wrapping. + item_title (str, optional): Optional header text shown at the top of the widget frame. + helper_text (str, optional): Optional helper text shown above the entry box. + **kwargs: Additional Frame options. + """ + super().__init__(parent, **kwargs) + + self.fields = [str(field) for field in (fields or [])] + self.command = command + self.orient = orient.lower() + self.options_fill_extents = self._normalise_bool(options_fill_extents) + self.max_per_line = max_per_line + self.value_var = tk.StringVar() + self._buttons = [] + + # Sub-frame for radio button controls + self.buttons_frame = ttk.Frame(self.content_frame) + if self.options_fill_extents: + self.buttons_frame.pack(side="top", fill="x", expand=True) + else: + self.buttons_frame.pack(side="top", anchor=self._pack_anchor) + + self._build_buttons() + + if default is not None: + self.set(default) + elif self.fields: + self.value_var.set(self.fields[0]) + + def _build_buttons(self): + """Create radio buttons from current fields.""" + for button in self._buttons: + button.destroy() + self._buttons.clear() + for index in range(self.buttons_frame.grid_size()[0] + 1): + self.buttons_frame.grid_columnconfigure(index, weight=0) + + for index, field in enumerate(self.fields): + sticky = self._grid_sticky + button = ttk.Radiobutton( + self.buttons_frame, + text=field, + variable=self.value_var, + value=field, + style="Radio.TRadiobutton", + command=lambda f=field: self._select_field(f), + ) + self.align_child_text(button) + + if self.max_per_line and self.max_per_line > 0: + if self.orient == "horizontal": + row = index // self.max_per_line + column = index % self.max_per_line + else: + row = index % self.max_per_line + column = index // self.max_per_line + button.grid( + row=row, + column=column, + padx=scale_pad((0, 10)), + pady=scale_pad((0, 4)), + sticky=("ew" if self.options_fill_extents else sticky), + ) + if self.options_fill_extents: + self.buttons_frame.grid_columnconfigure(column, weight=1) + elif self.orient == "horizontal": + button.grid( + row=0, + column=index, + padx=scale_pad((0, 10)), + pady=scale_pad((0, 4)), + sticky=("ew" if self.options_fill_extents else sticky), + ) + if self.options_fill_extents: + self.buttons_frame.grid_columnconfigure(index, weight=1) + else: + button.grid( + row=index, + column=0, + padx=scale_pad((0, 10)), + pady=scale_pad((0, 4)), + sticky=("ew" if self.options_fill_extents else sticky), + ) + if self.options_fill_extents: + self.buttons_frame.grid_columnconfigure(0, weight=1) + self._buttons.append(button) + + def _select_field(self, field): + """Handle radio button selection.""" + if self.command: + self.command(self.get()) + self._fire_on_change(self.get()) + + def get(self): + """Return the currently selected value. + + Returns: + str: Currently selected field label. + """ + return self.value_var.get() + + def set(self, value): + """Set the selected value if it exists in fields. + + Args: + value: Field label to select. + """ + value = str(value) + if value in self.fields: + self.value_var.set(value) + + def set_fields(self, fields, default=None): + """Replace the available fields and rebuild the widget. + + Args: + fields: New available field names. + default: Optional default field to select. + """ + self.fields = [str(field) for field in (fields or [])] + self._build_buttons() + + if default is not None: + self.set(default) + elif self.fields: + self.value_var.set(self.fields[0]) + else: + self.value_var.set("") + + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: + """Validate the currently selected radio option. + + Returns: + tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + `(is_valid, message, severity)` where severity is `None` when + valid, or `"error"` for an invalid selection. + """ + selected = self.get() + if not selected: + return self.apply_validation((False, "No option selected.", "error")) + if selected not in self.fields: + return self.apply_validation((False, f"Selected option '{selected}' is not available.", "error")) + return self.apply_validation((True, None, None)) if __name__ == "__main__": - - from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow - from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions - - def on_selection(value): - """Print selected option in the standalone example.""" - print(f"Selected: {value}") - - root = BHoMBaseWindow() - parent_frame = root.content_frame - - widget = RadioSelection( - parent_frame, - fields=["Option A", "Option B", "Option C"], - command=on_selection, - default="Option B", - alignment="center", - options_fill_extents=True, - orient="horizontal", - max_per_line=3, - item_title="Choose an Option", - helper_text="Select one of the options below:", - build_options=PackingOptions(pady=20) - ) - widget.build() - - root.mainloop() + from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow + from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions + + def on_selection(value): + """Print selected option in the standalone example.""" + print(f"Selected: {value}") + + root = BHoMBaseWindow() + parent_frame = root.content_frame + + widget = RadioSelection( + parent_frame, + fields=["Option A", "Option B", "Option C"], + command=on_selection, + default="Option B", + alignment="center", + options_fill_extents=True, + orient="horizontal", + max_per_line=3, + item_title="Choose an Option", + helper_text="Select one of the options below:", + build_options=PackingOptions(pady=20), + ) + widget.build() + + root.mainloop() diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/searchable_list_box.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/searchable_list_box.py index cec23f55..1afed764 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/searchable_list_box.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/searchable_list_box.py @@ -6,14 +6,15 @@ import re import sys import tkinter as tk +from collections.abc import Callable, Iterable from tkinter import ttk -from typing import Callable, Iterable, List, Literal, Optional +from typing import Literal from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget from python_toolkit.bhom_tkinter.widgets.list_box import ScrollableListBox -Scorer = Callable[[str, str], Optional[float]] # (query, item) -> score (higher is better), or None for no match +Scorer = Callable[[str, str], float | None] # (query, item) -> score (higher is better), or None for no match _NON_ALNUM = re.compile(r"[\W_]+") _BHOM_SEARCH = None # (Compute, Scorer) from the BHoM Search_Engine, loaded on first use @@ -35,7 +36,7 @@ def _load_bhom_search(): return _BHOM_SEARCH -def default_scorer(query: str, text: str, min_score: float = 75) -> Optional[float]: +def default_scorer(query: str, text: str, min_score: float = 75) -> float | None: """Score how well `query` matches `text` using the BHoM Search_Engine fuzzy match, or None if it is a weak match. Uses BH.Engine.Search.Compute.MatchScore with the WeightedRatio scorer. Case and punctuation are ignored. @@ -64,41 +65,41 @@ class SearchableListBox(BHoMBaseWidget): """ def __init__( - self, - parent: ttk.Frame, - items=None, - selectmode=tk.MULTIPLE, - height: int = 8, - width: Optional[int] = None, - show_selection_controls: bool = False, - keep_hidden_selection: bool = True, - show_summary: Optional[bool] = None, - filter_label: str = "Filter", - scorer: Scorer = default_scorer, - **kwargs): - """ - Args: - parent (ttk.Frame): The parent widget. - items (list, optional): Items to choose from. - selectmode (str): tk.MULTIPLE / tk.EXTENDED for multi-select, tk.SINGLE / tk.BROWSE for one item. - height (int): Visible rows in the list. - width (int, optional): Width of the list in characters. If None, it expands to fill the space. - show_selection_controls (bool): Show Select All / Deselect All buttons. They act on the items - currently shown by the filter. - keep_hidden_selection (bool): Keep items selected while the filter hides them. If False, the - selection is limited to the visible items each time the filter changes. - show_summary (bool, optional): Show a caption listing the selected items. Defaults to True for - multi-select lists. - filter_label (str): Caption shown above the filter entry. - scorer (Callable): Called as scorer(query, item); returns a score (higher ranks first) or None to - hide the item. Defaults to the BHoM Search_Engine fuzzy match. - **kwargs: Additional BHoMBaseWidget / Frame options (id, item_title, helper_text, on_change, ...). + self, + parent: ttk.Frame, + items=None, + selectmode=tk.MULTIPLE, + height: int = 8, + width: int | None = None, + show_selection_controls: bool = False, + keep_hidden_selection: bool = True, + show_summary: bool | None = None, + filter_label: str = "Filter", + scorer: Scorer = default_scorer, + **kwargs, + ): + """Args: + parent (ttk.Frame): The parent widget. + items (list, optional): Items to choose from. + selectmode (str): tk.MULTIPLE / tk.EXTENDED for multi-select, tk.SINGLE / tk.BROWSE for one item. + height (int): Visible rows in the list. + width (int, optional): Width of the list in characters. If None, it expands to fill the space. + show_selection_controls (bool): Show Select All / Deselect All buttons. They act on the items + currently shown by the filter. + keep_hidden_selection (bool): Keep items selected while the filter hides them. If False, the + selection is limited to the visible items each time the filter changes. + show_summary (bool, optional): Show a caption listing the selected items. Defaults to True for + multi-select lists. + filter_label (str): Caption shown above the filter entry. + scorer (Callable): Called as scorer(query, item); returns a score (higher ranks first) or None to + hide the item. Defaults to the BHoM Search_Engine fuzzy match. + **kwargs: Additional BHoMBaseWidget / Frame options (id, item_title, helper_text, on_change, ...). """ super().__init__(parent, **kwargs) self.scorer = scorer - self._all_items: List[str] = [str(item) for item in (items or [])] - self._shown: List[str] = list(self._all_items) + self._all_items: list[str] = [str(item) for item in (items or [])] + self._shown: list[str] = list(self._all_items) self._multi = selectmode in (tk.MULTIPLE, tk.EXTENDED, "multiple", "extended") self._keep_hidden = bool(keep_hidden_selection) self._selected: set[str] = set() @@ -132,27 +133,31 @@ def __init__( controls.columnconfigure(0, weight=1) controls.columnconfigure(1, weight=1) ttk.Button(controls, text="Select All", command=self.select_all).grid( - row=0, column=0, sticky="ew", padx=(0, 4)) + row=0, column=0, sticky="ew", padx=(0, 4) + ) ttk.Button(controls, text="Deselect All", command=self.deselect_all).grid( - row=0, column=1, sticky="ew", padx=(4, 0)) + row=0, column=1, sticky="ew", padx=(4, 0) + ) - self.summary_label: Optional[ttk.Label] = None + self.summary_label: ttk.Label | None = None if self._show_summary: self.summary_label = ttk.Label(self.content_frame, text="", style="Caption.TLabel", justify="left") self.summary_label.pack(side="top", anchor=self._pack_anchor, pady=(4, 0)) self.content_frame.bind( - "", lambda e: self.summary_label.configure(wraplength=max(e.width - 4, 100)), add="+") + "", lambda e: self.summary_label.configure(wraplength=max(e.width - 4, 100)), add="+" + ) self._update_summary() # ------------------------------------------------------------------ internals - def _matching(self, query: str) -> List[str]: + def _matching(self, query: str) -> list[str]: query = query.strip().lower() if not query: return list(self._all_items) scored = [(self.scorer(query, item), index, item) for index, item in enumerate(self._all_items)] - return [item for score, index, item in sorted((s for s in scored if s[0] is not None), - key=lambda s: (-s[0], s[1]))] + return [ + item for score, index, item in sorted((s for s in scored if s[0] is not None), key=lambda s: (-s[0], s[1])) + ] def _apply_filter(self) -> None: shown = self._matching(self.filter_var.get()) @@ -193,11 +198,11 @@ def _update_summary(self) -> None: # ------------------------------------------------------------------ public API - def get(self) -> List[str]: + def get(self) -> list[str]: """Return all selected items (including any hidden by the filter), in item order.""" return [item for item in self._all_items if item in self._selected] - def get_selection(self) -> List[str]: + def get_selection(self) -> list[str]: """Alias of get() for parity with ScrollableListBox.""" return self.get() @@ -217,11 +222,11 @@ def set(self, value) -> None: self._update_summary() self._fire_on_change(self.get()) - def get_options(self) -> List[str]: + def get_options(self) -> list[str]: """Return every item, whatever the filter shows.""" return list(self._all_items) - def get_visible(self) -> List[str]: + def get_visible(self) -> list[str]: """Return the items currently shown by the filter.""" return list(self._shown) @@ -265,20 +270,22 @@ def clear(self) -> None: self._update_summary() self._fire_on_change(self.get()) - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: """All states are valid unless a custom validation says otherwise.""" return self.apply_validation((True, None, None)) if __name__ == "__main__": - from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow root = BHoMBaseWindow(title="SearchableListBox demo", theme_mode="light") widget = SearchableListBox( root.content_frame, - items=[f"{city}_{kind}.epw" for city in ["London", "Birmingham", "Manchester", "Glasgow", "Belfast", "Cardiff"] - for kind in ["TRY", "DSY1", "DSY2", "DSY3"]], + items=[ + f"{city}_{kind}.epw" + for city in ["London", "Birmingham", "Manchester", "Glasgow", "Belfast", "Cardiff"] + for kind in ["TRY", "DSY1", "DSY2", "DSY3"] + ], height=8, width=40, show_selection_controls=True, diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/spinbox.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/spinbox.py index e29e29e2..e59344be 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/spinbox.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/spinbox.py @@ -1,202 +1,202 @@ """Spinbox widget for numeric or list-based stepped input.""" import tkinter as tk +from collections.abc import Callable from tkinter import ttk -from typing import Optional, Callable, List, Union, Literal +from typing import Literal from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget class Spinbox(BHoMBaseWidget): - """A spinbox widget supporting numeric ranges or explicit value lists.""" - - def __init__( - self, - parent, - values: Optional[Union[List[str], List[int], List[float]]] = None, - from_: Optional[Union[int, float]] = None, - to: Optional[Union[int, float]] = None, - increment: Union[int, float] = 1, - default: Optional[Union[str, int, float]] = None, - command: Optional[Callable[[str], None]] = None, - width: int = 10, - wrap: bool = False, - **kwargs): - """ - Args: - parent (tk.Widget): The parent widget. - values (list, optional): Explicit list of string values to step through. - If provided, `from_`, `to` and `increment` are ignored. - from_ (int | float, optional): Minimum value for numeric mode. - to (int | float, optional): Maximum value for numeric mode. - increment (int | float): Step size for numeric mode. Defaults to 1. - default (str | int | float, optional): Initial value. - command (callable, optional): Called with the current value (str) on change. - width (int): Width of the entry in characters. - wrap (bool): Whether stepping wraps around at the limits. - item_title (str, optional): Optional header text. - helper_text (str, optional): Optional helper text. - **kwargs: Additional Frame options. - """ - super().__init__(parent, **kwargs) - - self.command = command - self._value_var = tk.StringVar() - - # Store range/list constraints for validation - self._from = from_ - self._to = to - self._allowed_values: Optional[list] = [str(v) for v in values] if values else None - - # Determine the native type for get() coercion - if values and len(values) > 0: - self._value_type = type(values[0]) - elif from_ is not None: - self._value_type = type(from_) - else: - self._value_type = str - - spinbox_kwargs: dict = dict( - textvariable=self._value_var, - width=width, - wrap=wrap, - ) - - if values: - spinbox_kwargs["values"] = [str(v) for v in values] - else: - if from_ is not None: - spinbox_kwargs["from_"] = from_ - if to is not None: - spinbox_kwargs["to"] = to - spinbox_kwargs["increment"] = increment - - self.spinbox = ttk.Spinbox(self.content_frame, **spinbox_kwargs) - self.spinbox.pack(side="top", anchor=self._pack_anchor) - - if default is not None: - self.set(default) - elif values: - self._value_var.set(str(values[0])) - elif from_ is not None: - self._value_var.set(str(from_)) - - # Attach the trace after the initial value is set so the callback - # does not fire during construction. - self._value_var.trace_add("write", self._on_change) - - def _on_change(self, *_): - """Fire the command callback when the value changes.""" - if self.command: - self.command(self.get()) - self._fire_on_change(self.get()) - - def get(self) -> Union[str, int, float]: - """Return the current value cast to its original type. - - Returns: - str | int | float: Current spinbox value in its original type. - """ - raw = self._value_var.get() - try: - return self._value_type(raw) - except (ValueError, TypeError): - return raw - - def get_int(self) -> int: - """Return the current value as an integer. - - Returns: - int: Current spinbox value. - - Raises: - ValueError: If the value cannot be converted to int. - """ - return int(self.get()) - - def get_float(self) -> float: - """Return the current value as a float. - - Returns: - float: Current spinbox value. - - Raises: - ValueError: If the value cannot be converted to float. - """ - return float(self.get()) - - def set(self, value: Union[str, int, float]): - """Set the spinbox value. - - Args: - value: New value to display. - """ - self._value_var.set(str(value)) - - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: - """Validate that the current value is non-empty and within any configured range. - - Returns: - tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: - `(is_valid, message, severity)`. - """ - raw = str(self.get()).strip() - if not raw: - return self.apply_validation((False, "A value is required.", "error")) - - if self._value_type in (int, float): - try: - numeric_val = self._value_type(raw) - except (ValueError, TypeError): - label = "integer" if self._value_type == int else "number" - return self.apply_validation((False, f"Must be a valid {label}.", "error")) - if self._from is not None and numeric_val < self._from: - return self.apply_validation((False, f"Must be >= {self._from}.", "error")) - if self._to is not None and numeric_val > self._to: - return self.apply_validation((False, f"Must be <= {self._to}.", "error")) - elif self._allowed_values is not None and raw not in self._allowed_values: - return self.apply_validation((False, f"Value must be one of: {', '.join(self._allowed_values)}.", "error")) - - return self.apply_validation((True, None, None)) + """A spinbox widget supporting numeric ranges or explicit value lists.""" + + def __init__( + self, + parent, + values: list[str] | list[int] | list[float] | None = None, + from_: int | float | None = None, + to: int | float | None = None, + increment: int | float = 1, + default: str | int | float | None = None, + command: Callable[[str], None] | None = None, + width: int = 10, + wrap: bool = False, + **kwargs, + ): + """Args: + parent (tk.Widget): The parent widget. + values (list, optional): Explicit list of string values to step through. + If provided, `from_`, `to` and `increment` are ignored. + from_ (int | float, optional): Minimum value for numeric mode. + to (int | float, optional): Maximum value for numeric mode. + increment (int | float): Step size for numeric mode. Defaults to 1. + default (str | int | float, optional): Initial value. + command (callable, optional): Called with the current value (str) on change. + width (int): Width of the entry in characters. + wrap (bool): Whether stepping wraps around at the limits. + item_title (str, optional): Optional header text. + helper_text (str, optional): Optional helper text. + **kwargs: Additional Frame options. + """ + super().__init__(parent, **kwargs) + + self.command = command + self._value_var = tk.StringVar() + + # Store range/list constraints for validation + self._from = from_ + self._to = to + self._allowed_values: list | None = [str(v) for v in values] if values else None + + # Determine the native type for get() coercion + if values and len(values) > 0: + self._value_type = type(values[0]) + elif from_ is not None: + self._value_type = type(from_) + else: + self._value_type = str + + spinbox_kwargs: dict = { + "textvariable": self._value_var, + "width": width, + "wrap": wrap, + } + + if values: + spinbox_kwargs["values"] = [str(v) for v in values] + else: + if from_ is not None: + spinbox_kwargs["from_"] = from_ + if to is not None: + spinbox_kwargs["to"] = to + spinbox_kwargs["increment"] = increment + + self.spinbox = ttk.Spinbox(self.content_frame, **spinbox_kwargs) + self.spinbox.pack(side="top", anchor=self._pack_anchor) + + if default is not None: + self.set(default) + elif values: + self._value_var.set(str(values[0])) + elif from_ is not None: + self._value_var.set(str(from_)) + + # Attach the trace after the initial value is set so the callback + # does not fire during construction. + self._value_var.trace_add("write", self._on_change) + + def _on_change(self, *_): + """Fire the command callback when the value changes.""" + if self.command: + self.command(self.get()) + self._fire_on_change(self.get()) + + def get(self) -> str | int | float: + """Return the current value cast to its original type. + + Returns: + str | int | float: Current spinbox value in its original type. + """ + raw = self._value_var.get() + try: + return self._value_type(raw) + except (ValueError, TypeError): + return raw + + def get_int(self) -> int: + """Return the current value as an integer. + + Returns: + int: Current spinbox value. + + Raises: + ValueError: If the value cannot be converted to int. + """ + return int(self.get()) + + def get_float(self) -> float: + """Return the current value as a float. + + Returns: + float: Current spinbox value. + + Raises: + ValueError: If the value cannot be converted to float. + """ + return float(self.get()) + + def set(self, value: str | int | float): + """Set the spinbox value. + + Args: + value: New value to display. + """ + self._value_var.set(str(value)) + + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: + """Validate that the current value is non-empty and within any configured range. + + Returns: + tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + `(is_valid, message, severity)`. + """ + raw = str(self.get()).strip() + if not raw: + return self.apply_validation((False, "A value is required.", "error")) + + if self._value_type in (int, float): + try: + numeric_val = self._value_type(raw) + except (ValueError, TypeError): + label = "integer" if self._value_type is int else "number" + return self.apply_validation((False, f"Must be a valid {label}.", "error")) + if self._from is not None and numeric_val < self._from: + return self.apply_validation((False, f"Must be >= {self._from}.", "error")) + if self._to is not None and numeric_val > self._to: + return self.apply_validation((False, f"Must be <= {self._to}.", "error")) + elif self._allowed_values is not None and raw not in self._allowed_values: + return self.apply_validation((False, f"Value must be one of: {', '.join(self._allowed_values)}.", "error")) + + return self.apply_validation((True, None, None)) if __name__ == "__main__": - - from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow - from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions - - def on_change(value): - print(f"Value: {value}") - - root = BHoMBaseWindow() - parent_frame = root.content_frame - - # Numeric spinbox - numeric = Spinbox( - parent_frame, - from_=0, - to=100, - increment=5, - default=25, - command=on_change, - item_title="Numeric", - helper_text="Pick a value between 0 and 100", - build_options=PackingOptions(padx=20, pady=(20, 8)), - width = 1, - ) - numeric.build() - - # List-based spinbox - list_spin = Spinbox( - parent_frame, - values=["Small", "Medium", "Large", "X-Large"], - default="Medium", - command=on_change, - item_title="Size", - helper_text="Step through available sizes", - build_options=PackingOptions(padx=20, pady=(0, 20)), - width=100 - ) - list_spin.build() - - root.mainloop() + from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow + from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions + + def on_change(value): + print(f"Value: {value}") + + root = BHoMBaseWindow() + parent_frame = root.content_frame + + # Numeric spinbox + numeric = Spinbox( + parent_frame, + from_=0, + to=100, + increment=5, + default=25, + command=on_change, + item_title="Numeric", + helper_text="Pick a value between 0 and 100", + build_options=PackingOptions(padx=20, pady=(20, 8)), + width=1, + ) + numeric.build() + + # List-based spinbox + list_spin = Spinbox( + parent_frame, + values=["Small", "Medium", "Large", "X-Large"], + default="Medium", + command=on_change, + item_title="Size", + helper_text="Step through available sizes", + build_options=PackingOptions(padx=20, pady=(0, 20)), + width=100, + ) + list_spin.build() + + root.mainloop() diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/validated_entry_box.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/validated_entry_box.py index a6b88181..15292d75 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/validated_entry_box.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/validated_entry_box.py @@ -1,45 +1,45 @@ """Validated entry widget supporting typed value and constraint checks.""" import tkinter as tk +from collections.abc import Callable from tkinter import ttk -from python_toolkit.bhom_tkinter.widgets.label import Label -from typing import Optional, Callable, Any, Union, Literal +from typing import Any, Literal, Union -from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget from python_toolkit.bhom_tkinter.theming.scaling import scale_pad +from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget +from python_toolkit.bhom_tkinter.widgets.label import Label _TkVar = Union[tk.StringVar, tk.IntVar, tk.DoubleVar, tk.BooleanVar] + class ValidatedEntryBox(BHoMBaseWidget): - """ - A reusable entry box component with built-in validation for different data types. - + """A reusable entry box component with built-in validation for different data types. + Supports validation for: - String (required/optional, min/max length) - Integer (min/max value) - Float (min/max value) - Custom validation via callback """ - + def __init__( self, parent, - variable: Optional[_TkVar] = None, - default_value: Optional[Union[str, int, float, bool]] = None, + variable: _TkVar | None = None, + default_value: str | int | float | bool | None = None, width: int = 15, value_type: type = str, - min_value: Optional[Union[int, float]] = None, - max_value: Optional[Union[int, float]] = None, - min_length: Optional[int] = None, - max_length: Optional[int] = None, + min_value: int | float | None = None, + max_value: int | float | None = None, + min_length: int | None = None, + max_length: int | None = None, required: bool = True, - custom_validator: Optional[Callable[[Any], tuple[bool, str]]] = None, - on_validate: Optional[Callable[[bool], None]] = None, - **kwargs + custom_validator: Callable[[Any], tuple[bool, str]] | None = None, + on_validate: Callable[[bool], None] | None = None, + **kwargs, ) -> None: - """ - Initialize the ValidatedEntryBox. - + """Initialize the ValidatedEntryBox. + Args: parent: Parent item_title: Optional header text shown at the top of the widget frame @@ -79,7 +79,7 @@ def __init__( self.default_value = default_value # Store the external variable (any tkinter var type) - self._external_var: Optional[_TkVar] = variable + self._external_var: _TkVar | None = variable # ttk.Entry only works with StringVar — always use one internally self.variable = tk.StringVar(value="") @@ -98,7 +98,7 @@ def __init__( # Create frame for entry and success indicator self.entry_frame = ttk.Frame(self.content_frame) self.entry_frame.pack(side="top", fill="x", anchor=self._pack_anchor) - + # Create entry widget self.entry = ttk.Entry( self.entry_frame, @@ -107,7 +107,7 @@ def __init__( justify=self._text_justify, ) self.entry.pack(side="left", fill="x", expand=True) - + # Create success indicator label at end of entry self.success_label = Label( self.entry_frame, @@ -117,7 +117,7 @@ def __init__( alignment=self.alignment, ) self.success_label.pack(side="left", padx=scale_pad((5, 0))) - + # Create error label below entry with fixed height to prevent layout shifts self.error_label = Label( self.content_frame, @@ -126,7 +126,7 @@ def __init__( alignment=self.alignment, ) self.error_label.pack(side="top", fill="x", anchor=self._pack_anchor) - + # Bind validation events self.entry.bind("", lambda _: self.validate()) self.entry.bind("", lambda _: self.validate()) @@ -156,7 +156,7 @@ def _sync_to_external(self, *_) -> None: self._external_var.set(raw.lower() in ("1", "true", "yes")) except (ValueError, TypeError): pass # Ignore mid-edit invalid states - + def get(self) -> str: """Get the current value as a string. @@ -164,8 +164,8 @@ def get(self) -> str: str: Trimmed entry value. """ return self.variable.get().strip() - - def get_value(self) -> Optional[Union[str, int, float, bool]]: + + def get_value(self) -> str | int | float | bool | None: """Get the current value converted to the specified type. Returns: @@ -174,31 +174,30 @@ def get_value(self) -> Optional[Union[str, int, float, bool]]: value_str = self.get() if not value_str: return None - + try: - if self.value_type == int: + if self.value_type is int: return int(value_str) - elif self.value_type == float: + elif self.value_type is float: return float(value_str) - elif self.value_type == bool: + elif self.value_type is bool: return value_str.lower() in ("1", "true", "yes") else: return value_str except (ValueError, TypeError): return None - - def set(self, value: Union[str, int, float, bool]) -> None: + + def set(self, value: str | int | float | bool) -> None: """Set the entry value. Args: value: Value to display in the entry. """ self.variable.set(str(value)) - - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: - """ - Validate the current entry value. - + + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: + """Validate the current entry value. + Returns: tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: `(is_valid, message, severity)` where severity is `None` when @@ -210,30 +209,30 @@ def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warni return self.apply_validation((True, None, None)) value_str = self.get() - base_result: tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]] - + base_result: tuple[bool, str | None, Literal["info", "warning", "error"] | None] + # Check if required if self.required and not value_str: self._show_error("Required") self._call_validate_callback(False) base_result = (False, "Required", "error") return self.apply_validation(base_result) - + # If not required and empty, it's valid if not self.required and not value_str: self._show_success() self._call_validate_callback(True) base_result = (True, None, None) return self.apply_validation(base_result) - + # Type-specific validation - if self.value_type == str: + if self.value_type is str: is_valid = self._validate_string(value_str) - elif self.value_type == int: + elif self.value_type is int: is_valid = self._validate_int(value_str) - elif self.value_type == float: + elif self.value_type is float: is_valid = self._validate_float(value_str) - elif self.value_type == bool: + elif self.value_type is bool: is_valid = self._validate_bool(value_str) else: self._show_error(f"Unsupported type: {self.value_type}") @@ -261,7 +260,7 @@ def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warni self._call_validate_callback(False) return final_result - + def _validate_string(self, value: str) -> bool: """Validate string value. @@ -275,20 +274,20 @@ def _validate_string(self, value: str) -> bool: if self.min_length is not None and len(value) < self.min_length: self._show_error(f"Minimum length: {self.min_length}") return False - + if self.max_length is not None and len(value) > self.max_length: self._show_error(f"Maximum length: {self.max_length}") return False - + # Custom validation if self.custom_validator: is_valid, error_msg = self.custom_validator(value) if not is_valid: self._show_error(error_msg) return False - + return True - + def _validate_int(self, value_str: str) -> bool: """Validate integer value. @@ -303,25 +302,25 @@ def _validate_int(self, value_str: str) -> bool: except ValueError: self._show_error("Must be a valid integer") return False - + # Check range constraints if self.min_value is not None and value < self.min_value: self._show_error(f"Must be >= {self.min_value}") return False - + if self.max_value is not None and value > self.max_value: self._show_error(f"Must be <= {self.max_value}") return False - + # Custom validation if self.custom_validator: is_valid, error_msg = self.custom_validator(value) if not is_valid: self._show_error(error_msg) return False - + return True - + def _validate_float(self, value_str: str) -> bool: """Validate float value. @@ -336,7 +335,7 @@ def _validate_float(self, value_str: str) -> bool: except ValueError: self._show_error("Must be a valid number") return False - + # Check range constraints if self.min_value is not None and value < self.min_value: if self.max_value is not None: @@ -344,23 +343,23 @@ def _validate_float(self, value_str: str) -> bool: else: self._show_error(f"Must be >= {self.min_value}") return False - + if self.max_value is not None and value > self.max_value: if self.min_value is not None: self._show_error(f"Must be between {self.min_value} and {self.max_value}") else: self._show_error(f"Must be <= {self.max_value}") return False - + # Custom validation if self.custom_validator: is_valid, error_msg = self.custom_validator(value) if not is_valid: self._show_error(error_msg) return False - + return True - + def _validate_bool(self, value_str: str) -> bool: """Validate boolean value (accepts 1/0, true/false, yes/no). @@ -388,23 +387,23 @@ def _show_error(self, message: str) -> None: self.error_label.set(message) self.error_label.label.configure(foreground="#ff4444") self.success_label.set(" ") - + def _show_success(self) -> None: """Display success indicator.""" self.error_label.set(" ") self.success_label.set("✓") - + def clear_error(self) -> None: """Clear the error message.""" self.error_label.set(" ") self.success_label.set(" ") - + def _call_validate_callback(self, is_valid: bool) -> None: """Call the validation callback if provided.""" if self.on_validate: self.on_validate(is_valid) - def set_alignment(self, alignment: Literal['left', 'center', 'right']) -> None: + def set_alignment(self, alignment: Literal["left", "center", "right"]) -> None: """Set widget alignment and refresh entry + labels accordingly.""" super().set_alignment(alignment) self.entry.configure(justify=self._text_justify) @@ -414,20 +413,19 @@ def set_alignment(self, alignment: Literal['left', 'center', 'right']) -> None: self.success_label.set_alignment(self.alignment) - if __name__ == "__main__": # Test the ValidatedEntryBox from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions - + root = BHoMBaseWindow(title="Validated Entry Box Test") parent_container = getattr(root, "content_frame", root) def on_validate(is_valid): """Print validation state in the standalone example.""" print(f"Validation result: {is_valid}") - + entry_box = ValidatedEntryBox( parent_container, item_title="Integer Field", @@ -436,8 +434,8 @@ def on_validate(is_valid): min_value=0, max_value=100, on_validate=on_validate, - build_options=PackingOptions(padx=20, pady=20) + build_options=PackingOptions(padx=20, pady=20), ) entry_box.build() - - root.mainloop() \ No newline at end of file + + root.mainloop() diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/widget_calendar.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/widget_calendar.py index 078d9734..aa973353 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/widget_calendar.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/widget_calendar.py @@ -1,38 +1,39 @@ """Calendar date-picker widget with optional year selector.""" -import tkinter as tk -from typing import Optional, Literal -from tkinter import ttk -from python_toolkit.bhom_tkinter.widgets.label import Label import calendar import datetime +from tkinter import ttk +from typing import Literal +from python_toolkit.bhom_tkinter.theming.scaling import scale_pad from python_toolkit.bhom_tkinter.widgets._widgets_base import BHoMBaseWidget from python_toolkit.bhom_tkinter.widgets.button import Button from python_toolkit.bhom_tkinter.widgets.drop_down_selection import DropDownSelection -from python_toolkit.bhom_tkinter.theming.scaling import scale_pad +from python_toolkit.bhom_tkinter.widgets.label import Label + class CalendarWidget(BHoMBaseWidget): """Render a month grid and allow date selection.""" def __init__( - self, - parent: ttk.Frame, - def_year: int = 2026, - def_month: int = 1, - def_day: int = 1, - show_year_selector: bool = True, - year_min: int = 1900, - year_max: int = 2100, - day_button_width: int = 4, - day_button_padx: int = 1, - day_button_pady: int = 1, - day_button_text_alignment: Literal["left", "center", "right"] = "center", - fixed_week_rows: int | None = None, - selector_position: Literal["top", "bottom"] = "bottom", - selection_label_format: Literal["short", "long"] = "short", - **kwargs): - + self, + parent: ttk.Frame, + def_year: int = 2026, + def_month: int = 1, + def_day: int = 1, + show_year_selector: bool = True, + year_min: int = 1900, + year_max: int = 2100, + day_button_width: int = 4, + day_button_padx: int = 1, + day_button_pady: int = 1, + day_button_text_alignment: Literal["left", "center", "right"] = "center", + fixed_week_rows: int | None = None, + selector_position: Literal["top", "bottom"] = "bottom", + selection_label_format: Literal["short", "long"] = "short", + **kwargs, + ): + super().__init__(parent, **kwargs) self.year = def_year @@ -49,17 +50,11 @@ def __init__( alignment_candidate = "center" self.day_button_text_alignment = alignment_candidate self.day_button_style = f"CalendarDay.{id(self)}.TButton" - self.fixed_week_rows = ( - max(1, int(fixed_week_rows)) if fixed_week_rows is not None else None - ) + self.fixed_week_rows = max(1, int(fixed_week_rows)) if fixed_week_rows is not None else None selector_candidate = str(selector_position).strip().lower() - self.selector_position = ( - selector_candidate if selector_candidate in {"top", "bottom"} else "bottom" - ) + self.selector_position = selector_candidate if selector_candidate in {"top", "bottom"} else "bottom" label_format = str(selection_label_format).strip().lower() - self.selection_label_format = ( - label_format if label_format in {"short", "long"} else "short" - ) + self.selection_label_format = label_format if label_format in {"short", "long"} else "short" anchor_map = { "left": "w", @@ -96,7 +91,20 @@ def year_selector(self): def month_selector(self): """Build the month dropdown selector.""" - self.months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] + self.months = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", + ] self.month_dropdown = DropDownSelection( self.month_frame, options=self.months, @@ -184,7 +192,7 @@ def redraw(self): while len(weeks) < self.fixed_week_rows: weeks.append([0, 0, 0, 0, 0, 0, 0]) weeks = weeks[: self.fixed_week_rows] - + for row, week in enumerate(weeks): for col, day in enumerate(week): text = "" if day == 0 else day @@ -197,13 +205,13 @@ def redraw(self): ) cell_widget.button.configure(style=self.day_button_style, state=state) cell_widget.grid( - row=row+1, + row=row + 1, column=col, sticky="nsew", padx=self.day_button_padx, pady=self.day_button_pady, ) - + def set_day(self, num): """Set the selected day and refresh the date summary label. @@ -217,7 +225,7 @@ def set_day(self, num): if self._initialized: self._fire_on_change(self.get()) - + def get_date(self): """Return the selected date as a `datetime.date` instance. @@ -225,7 +233,7 @@ def get_date(self): datetime.date: Currently selected date. """ return datetime.date(self.year, self.month, self.day) - + def get(self): """Return the selected date value. @@ -233,7 +241,7 @@ def get(self): datetime.date: Currently selected date. """ return datetime.date(self.year, self.month, self.day) - + def set(self, value: datetime.date): """Set the selected date from a `datetime.date` value. @@ -243,15 +251,15 @@ def set(self, value: datetime.date): self.year = value.year self.month = value.month self.day = value.day - if hasattr(self, 'year_dropdown'): + if hasattr(self, "year_dropdown"): self.year_dropdown.set(str(self.year)) - if hasattr(self, 'month_dropdown'): + if hasattr(self, "month_dropdown"): self.month_dropdown.set(self.months[self.month - 1]) self._clamp_day() self.redraw() self._refresh_selection_label() - def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warning', 'error']]]: + def validate(self) -> tuple[bool, str | None, Literal["info", "warning", "error"] | None]: """Validate the currently selected date. Returns: @@ -264,7 +272,7 @@ def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warni return self.apply_validation((True, None, None)) except ValueError as ex: return self.apply_validation((False, f"Invalid date: {ex}", "error")) - + def pack(self, **kwargs): """Pack the widget and ensure the calendar grid is rendered. @@ -273,9 +281,9 @@ def pack(self, **kwargs): """ super().pack(**kwargs) self.redraw() - -if __name__ == "__main__": + +if __name__ == "__main__": from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions @@ -294,7 +302,7 @@ def pack(self, **kwargs): day_button_text_alignment="center", item_title="Select a Date", helper_text="Choose a date from the calendar below.", - build_options=PackingOptions(padx=20, pady=20) + build_options=PackingOptions(padx=20, pady=20), ) cal_widget1.build() diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/__init__.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/__init__.py index cdd1dabd..241f756e 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/__init__.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/__init__.py @@ -1,4 +1,5 @@ from python_toolkit.bhom_tkinter.bhom_base_child_window import BHoMBaseChildWindow + from .directory_file_selector import DirectoryFileSelector from .landing_page import LandingPage from .modal_window import BHoMModalWindow diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/directory_file_selector.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/directory_file_selector.py index 431a74d3..460724d3 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/directory_file_selector.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/directory_file_selector.py @@ -1,15 +1,15 @@ """Window for selecting multiple files by extension from a directory tree.""" import tkinter as tk -from tkinter import ttk -from python_toolkit.bhom_tkinter.widgets.label import Label +from collections.abc import Iterable from pathlib import Path -from typing import Iterable, List, Optional -from python_toolkit.bhom_tkinter.widgets.list_box import ScrollableListBox -from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions from python_toolkit.bhom_tkinter.bhom_base_child_window import BHoMBaseChildWindow from python_toolkit.bhom_tkinter.theming.scaling import scale_pad +from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions +from python_toolkit.bhom_tkinter.widgets.label import Label +from python_toolkit.bhom_tkinter.widgets.list_box import ScrollableListBox + class DirectoryFileSelector(BHoMBaseChildWindow): """Display matching files and return the user's multi-selection.""" @@ -25,12 +25,12 @@ def __init__( self.file_types = self._normalise_file_types(file_types) self.selection_label = selection_label self._cancelled = False - self.selected_files: List[Path] = [] + self.selected_files: list[Path] = [] self.files = self._discover_files() self.display_items = [self._display_value(file) for file in self.files] self.file_lookup = dict(zip(self.display_items, self.files)) - self.file_selector_listbox: Optional[ScrollableListBox] = None + self.file_selector_listbox: ScrollableListBox | None = None super().__init__( title=f"Select {selection_label}", @@ -46,7 +46,6 @@ def __init__( def build(self): """Build the list-based file selection UI.""" - instruction_label = Label( self.content_frame, text=f"Select the {self.selection_label} to analyse.", @@ -61,13 +60,13 @@ def build(self): selectmode=tk.MULTIPLE, height=12, show_selection_controls=True, - build_options=PackingOptions(fill='both', expand=True), + build_options=PackingOptions(fill="both", expand=True), ) self.widgets.append(self.file_selector_listbox) super().build() - def _normalise_file_types(self, file_types: Iterable[str]) -> List[str]: + def _normalise_file_types(self, file_types: Iterable[str]) -> list[str]: normalised = [] for file_type in file_types: suffix = str(file_type).strip() @@ -78,7 +77,7 @@ def _normalise_file_types(self, file_types: Iterable[str]) -> List[str]: normalised.append(suffix.lower()) return normalised - def _discover_files(self) -> List[Path]: + def _discover_files(self) -> list[Path]: if not self.directory.exists(): return [] @@ -105,8 +104,8 @@ def _on_cancel(self): self._cancelled = True self.destroy_root() -if __name__ == "__main__": +if __name__ == "__main__": print(Path(__file__).resolve().parent, flush=True) # Example usage selector = DirectoryFileSelector( @@ -117,4 +116,4 @@ def _on_cancel(self): selector.mainloop() for file in selector.selected_files: - print(file) \ No newline at end of file + print(file) diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/landing_page.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/landing_page.py index 2ffbc0f7..bd7e95be 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/landing_page.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/landing_page.py @@ -1,30 +1,29 @@ """Landing page window with configurable header, message text, and custom actions.""" +from collections.abc import Callable from tkinter import ttk -from typing import Optional, Callable + from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow +from python_toolkit.bhom_tkinter.theming.scaling import scale_pad +from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions from python_toolkit.bhom_tkinter.widgets.button import Button from python_toolkit.bhom_tkinter.widgets.label import Label -from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions -from python_toolkit.bhom_tkinter.theming.scaling import scale_pad class LandingPage(BHoMBaseWindow): - """ - A reusable landing page GUI with configurable title, message, and buttons. + """A reusable landing page GUI with configurable title, message, and buttons. Uses BHoMBaseWindow as the base template. """ def __init__( self, title: str = "Landing Page", - header: Optional[str] = None, - message: Optional[str] = None, - sub_title: Optional[str] = None, + header: str | None = None, + message: str | None = None, + sub_title: str | None = None, **kwargs, ): - """ - Initializes the landing page GUI. + """Initializes the landing page GUI. Args: title (str): Window and header title text. @@ -33,7 +32,7 @@ def __init__( self.header = header self.message = message self.sub_title = sub_title - self.custom_buttons_frame: Optional[ttk.Frame] = None + self.custom_buttons_frame: ttk.Frame | None = None super().__init__( title=title, @@ -62,7 +61,7 @@ def build(self): build_options=PackingOptions(side="top", anchor="w", pady=(0, 10)), ) message_label.build() - + if self.sub_title: sub_title_label = Label( self.content_frame, @@ -79,8 +78,7 @@ def build(self): super().build() def add_custom_button(self, text: str, command: Callable, **kwargs) -> ttk.Button: - """ - Add a custom button to the landing page. + """Add a custom button to the landing page. Args: text (str): Button text. @@ -103,12 +101,11 @@ def add_custom_button(self, text: str, command: Callable, **kwargs) -> ttk.Butto if __name__ == "__main__": - - #simple example of using the landing page + # simple example of using the landing page def on_button_click(): """Handle demo button clicks in the standalone example.""" print("Button clicked!") - + def on_button_click_2(): """Handle demo button clicks in the standalone example.""" print("Second button clicked!") @@ -123,4 +120,4 @@ def on_button_click_2(): ) landing_page.add_custom_button(text="Click Me", command=on_button_click, width=100) landing_page.add_custom_button(text="Click Me 2", command=on_button_click_2) - landing_page.mainloop() \ No newline at end of file + landing_page.mainloop() diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/modal_window.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/modal_window.py index 9ed71d82..618539a5 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/modal_window.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/modal_window.py @@ -3,7 +3,7 @@ from __future__ import annotations import tkinter as tk -from typing import Callable, Optional +from collections.abc import Callable from python_toolkit.bhom_tkinter.bhom_base_child_window import BHoMBaseChildWindow @@ -23,7 +23,7 @@ def __init__( resizable: bool = False, show_close: bool = True, close_text: str = "Close", - close_command: Optional[Callable[[], None]] = None, + close_command: Callable[[], None] | None = None, theme_mode: str | None = None, content_padding: int = 20, **kwargs, diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/processing_window.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/processing_window.py index 3649528f..16698711 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/processing_window.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/processing_window.py @@ -1,21 +1,18 @@ -import tkinter as tk -from tkinter import ttk -import os - -import time import threading +import time +from tkinter import ttk from python_toolkit.bhom_tkinter.bhom_base_child_window import BHoMBaseChildWindow from python_toolkit.bhom_tkinter.theming.scaling import scale, scale_pad + class ProcessingWindow(BHoMBaseChildWindow): """A simple processing window with animated indicator.""" def __init__(self, title="Processing", message="Processing...", *args, **kwargs): - """ - Args: - title (str): Window title. - message (str): Message to display. + """Args: + title (str): Window title. + message (str): Message to display. """ super().__init__( title=title, @@ -29,7 +26,7 @@ def __init__(self, title="Processing", message="Processing...", *args, **kwargs) show_banner=False, top_most=True, *args, - **kwargs + **kwargs, ) self.attributes("-topmost", True) @@ -39,11 +36,7 @@ def __init__(self, title="Processing", message="Processing...", *args, **kwargs) container.pack(fill="both", expand=True) self.message_label = ttk.Label( - container, - text=message, - style="Title.TLabel", - justify="center", - wraplength=scale(400) + container, text=message, style="Title.TLabel", justify="center", wraplength=scale(400) ) try: title_font = ttk.Style(self).lookup("Title.TLabel", "font") @@ -56,12 +49,7 @@ def __init__(self, title="Processing", message="Processing...", *args, **kwargs) animation_frame = ttk.Frame(container) animation_frame.pack(expand=True) - self.animation_label = ttk.Label( - animation_frame, - text="●", - style="Title.TLabel", - foreground="#0078d4" - ) + self.animation_label = ttk.Label(animation_frame, text="●", style="Title.TLabel", foreground="#0078d4") try: title_font = ttk.Style(self).lookup("Title.TLabel", "font") if title_font: @@ -77,7 +65,6 @@ def __init__(self, title="Processing", message="Processing...", *args, **kwargs) self.update_idletasks() self.refresh_sizing() - def start(self): """Start the processing window and animation.""" if self.is_running: @@ -154,11 +141,12 @@ def update_message(self, message: str): if __name__ == "__main__": processing = ProcessingWindow(title="Test Processing", message="Running Comfort and Safety Calculation...") + def worker(): for i in range(50): time.sleep(0.1) try: - processing.after(0, processing.update_message, f"Step {i+1}/50") + processing.after(0, processing.update_message, f"Step {i + 1}/50") except Exception: pass diff --git a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/warning_box.py b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/warning_box.py index 0667bb6c..aa199e0c 100644 --- a/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/warning_box.py +++ b/Python_Engine/Python/src/python_toolkit/bhom_tkinter/windows/warning_box.py @@ -1,35 +1,28 @@ """Standardized warning dialog window for errors, warnings, and info messages.""" -from python_toolkit.bhom_tkinter.widgets.label import Label from python_toolkit.bhom_tkinter.bhom_base_child_window import BHoMBaseChildWindow -from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions from python_toolkit.bhom_tkinter.theming.scaling import scale +from python_toolkit.bhom_tkinter.widgets._packing_options import PackingOptions +from python_toolkit.bhom_tkinter.widgets.label import Label class WarningBox(BHoMBaseChildWindow): """Show categorized messages using the shared BHoM window styling.""" def __init__( - self, - title: str= 'Warning', - warnings: list[str] | str | None = None, - errors: list[str] | str | None = None, - infos: list[str] | str | None = None, - **kwargs - ): + self, + title: str = "Warning", + warnings: list[str] | str | None = None, + errors: list[str] | str | None = None, + infos: list[str] | str | None = None, + **kwargs, + ): self.warnings = self._normalise_messages(warnings) self.errors = self._normalise_messages(errors) self.infos = self._normalise_messages(infos) - super().__init__( - title=title, - show_submit=False, - close_text="Continue", - min_width=250, - min_height=150, - **kwargs - ) + super().__init__(title=title, show_submit=False, close_text="Continue", min_width=250, min_height=150, **kwargs) def build(self): """Render current messages into the content area.""" @@ -115,10 +108,12 @@ def add_info_message(self, message: str): if __name__ == "__main__": - root = WarningBox(title="Validation Error", warnings="This is a warning message to alert the user about something important.") + root = WarningBox( + title="Validation Error", warnings="This is a warning message to alert the user about something important." + ) for message in ["This is the first error message.", "This is the second error message."]: root.add_error_message(message) root.add_info_message("This is some additional information for the user.") - root.mainloop() \ No newline at end of file + root.mainloop() diff --git a/Python_Engine/Python/src/python_toolkit/helpers/__init__.py b/Python_Engine/Python/src/python_toolkit/helpers/__init__.py index b0ee9a8a..eda8267a 100644 --- a/Python_Engine/Python/src/python_toolkit/helpers/__init__.py +++ b/Python_Engine/Python/src/python_toolkit/helpers/__init__.py @@ -1,22 +1,10 @@ -from .timeseries import ( - validate_timeseries, - timeseries_summary_monthly -) -from .cardinality import ( - cardinality, - angle_from_cardinal, - angle_from_north, - angle_to_vector -) -from .decay_rate import ( - DecayMethod, - proximity_decay, - decay_rate_smoother -) -from .helpers import ( - sanitise_string, - convert_keys_to_snake_case, - remove_leap_days, - timedelta_tostring, - safe_filename -) \ No newline at end of file +"""Data helpers (requires the "plot" extra: ``python_toolkit[plot]``).""" + +from .._optional import require_extra + +require_extra("plot", "numpy", "pandas", "caseconverter") + +from .cardinality import angle_from_cardinal, angle_from_north, angle_to_vector, cardinality +from .decay_rate import DecayMethod, decay_rate_smoother, proximity_decay +from .helpers import convert_keys_to_snake_case, remove_leap_days, safe_filename, sanitise_string, timedelta_tostring +from .timeseries import timeseries_summary_monthly, validate_timeseries diff --git a/Python_Engine/Python/src/python_toolkit/helpers/cardinality.py b/Python_Engine/Python/src/python_toolkit/helpers/cardinality.py index 1bf64732..30732591 100644 --- a/Python_Engine/Python/src/python_toolkit/helpers/cardinality.py +++ b/Python_Engine/Python/src/python_toolkit/helpers/cardinality.py @@ -1,11 +1,13 @@ -import numpy as np +import numpy as np from ..bhom.analytics import bhom_analytics + @bhom_analytics() def cardinality(direction_angle: float, directions: int = 16): """Returns the cardinal orientation of a given angle, where that angle is related to north at 0 degrees. + Args: direction_angle (float): The angle to north in degrees (+Ve is interpreted as clockwise from north at 0.0 @@ -13,15 +15,13 @@ def cardinality(direction_angle: float, directions: int = 16): directions (int): The number of cardinal directions into which angles shall be binned (This value should be one of 4, 8, 16 or 32, and is centred about "north"). + Returns: int: The cardinal direction the angle represents. """ - if direction_angle > 360 or direction_angle < 0: - raise ValueError( - "The angle entered is beyond the normally expected range for an orientation in degrees." - ) + raise ValueError("The angle entered is beyond the normally expected range for an orientation in degrees.") cardinal_directions = { 4: ["N", "E", "S", "W"], @@ -81,9 +81,7 @@ def cardinality(direction_angle: float, directions: int = 16): } if directions not in cardinal_directions: - raise ValueError( - f'The input "directions" must be one of {list(cardinal_directions.keys())}.' - ) + raise ValueError(f'The input "directions" must be one of {list(cardinal_directions.keys())}.') val = int((direction_angle / (360 / directions)) + 0.5) @@ -91,14 +89,15 @@ def cardinality(direction_angle: float, directions: int = 16): return arr[(val % directions)] + @bhom_analytics() def angle_from_cardinal(cardinal_direction: str) -> float: - """ - For a given cardinal direction, return the corresponding angle in degrees. + """For a given cardinal direction, return the corresponding angle in degrees. Args: cardinal_direction (str): The cardinal direction. + Returns: float: The angle associated with the cardinal direction. @@ -145,6 +144,7 @@ def angle_from_cardinal(cardinal_direction: str) -> float: return lookup[cardinal_direction] + def angle_from_north(vector: list[float]) -> float: """For an X, Y vector, determine the clockwise angle to north at [0, 1]. @@ -161,6 +161,7 @@ def angle_from_north(vector: list[float]) -> float: angle2 = np.arctan2(*vector[::-1]) return np.rad2deg((angle1 - angle2) % (2 * np.pi)) + def angle_to_vector(clockwise_angle_from_north: float) -> list[float]: """Return the X, Y vector from of an angle from north at 0-degrees. @@ -173,7 +174,6 @@ def angle_to_vector(clockwise_angle_from_north: float) -> list[float]: list[float]: A vector of length 2. """ - clockwise_angle_from_north = np.radians(clockwise_angle_from_north) return np.sin(clockwise_angle_from_north), np.cos(clockwise_angle_from_north) diff --git a/Python_Engine/Python/src/python_toolkit/helpers/decay_rate.py b/Python_Engine/Python/src/python_toolkit/helpers/decay_rate.py index 99f2e657..050824de 100644 --- a/Python_Engine/Python/src/python_toolkit/helpers/decay_rate.py +++ b/Python_Engine/Python/src/python_toolkit/helpers/decay_rate.py @@ -1,4 +1,3 @@ -import re from enum import Enum, auto import numpy as np @@ -6,6 +5,7 @@ from ..bhom.analytics import bhom_analytics + class DecayMethod(Enum): """An enumeration of decay methods.""" @@ -13,6 +13,7 @@ class DecayMethod(Enum): PARABOLIC = auto() SIGMOID = auto() + @bhom_analytics() def proximity_decay( value: float, @@ -37,7 +38,6 @@ def proximity_decay( float: The value at the given distance. """ - distance_to_value = np.interp(distance_to_value, [0, max_distance], [0, 1]) if decay_method == DecayMethod.LINEAR: @@ -49,6 +49,7 @@ def proximity_decay( raise ValueError(f"Unknown curve type: {decay_method}") + @bhom_analytics() def decay_rate_smoother( series: pd.Series, @@ -75,7 +76,6 @@ def decay_rate_smoother( pd.Series: A modified series """ - # Find periods of major transition (where values vary significantly) transition_index = series.diff() < difference_threshold diff --git a/Python_Engine/Python/src/python_toolkit/helpers/helpers.py b/Python_Engine/Python/src/python_toolkit/helpers/helpers.py index 7f8cad97..78feb6ea 100644 --- a/Python_Engine/Python/src/python_toolkit/helpers/helpers.py +++ b/Python_Engine/Python/src/python_toolkit/helpers/helpers.py @@ -1,4 +1,4 @@ -import re +import re from datetime import timedelta from typing import Any @@ -7,33 +7,33 @@ from ..bhom.analytics import bhom_analytics + def sanitise_string(string: str) -> str: """Sanitise a string so that only path-safe characters remain.""" - keep_characters = r"[^.A-Za-z0-9_-]" return re.sub(keep_characters, "_", string).replace("__", "_").rstrip() + def convert_keys_to_snake_case(d: dict | list | Any): """Given a dictionary, convert all keys to snake_case.""" keys_to_skip = ["_t"] if isinstance(d, dict): - return { - snakecase(k) if k not in keys_to_skip else k: convert_keys_to_snake_case(v) - for k, v in d.items() - } + return {snakecase(k) if k not in keys_to_skip else k: convert_keys_to_snake_case(v) for k, v in d.items()} if isinstance(d, list): return [convert_keys_to_snake_case(x) for x in d] return d + @bhom_analytics() def timedelta_tostring(time_delta: timedelta) -> str: - """timedelta objects don't have a nice string representation, so this function converts them. + """Timedelta objects don't have a nice string representation, so this function converts them. Args: time_delta (datetime.timedelta): The timedelta object to convert. + Returns: str: A string representation of the timedelta object. @@ -43,6 +43,7 @@ def timedelta_tostring(time_delta: timedelta) -> str: minutes, _ = divmod(remainder, 60) return f"{hours:02d}:{minutes:02d}" + @bhom_analytics() def decay_rate_smoother( series: pd.Series, @@ -69,7 +70,6 @@ def decay_rate_smoother( pd.Series: A modified series """ - # Find periods of major transition (where values vary significantly) transition_index = series.diff() < difference_threshold @@ -93,11 +93,12 @@ def decay_rate_smoother( return new_series + @bhom_analytics() def remove_leap_days(pd_object: pd.DataFrame | pd.Series) -> pd.DataFrame | pd.Series: """A removal of all timesteps within a time-indexed pandas - object where the day is the 29th of February.""" - + object where the day is the 29th of February. + """ if not isinstance(pd_object.index, pd.DatetimeIndex): raise ValueError("The object provided should be datetime-indexed.") @@ -105,9 +106,8 @@ def remove_leap_days(pd_object: pd.DataFrame | pd.Series) -> pd.DataFrame | pd.S return pd_object[~mask] + @bhom_analytics() def safe_filename(filename: str) -> str: """Remove all non-alphanumeric characters from a filename.""" - return "".join( - [c for c in filename if c.isalpha() or c.isdigit() or c == " "] - ).strip() + return "".join([c for c in filename if c.isalpha() or c.isdigit() or c == " "]).strip() diff --git a/Python_Engine/Python/src/python_toolkit/helpers/timeseries.py b/Python_Engine/Python/src/python_toolkit/helpers/timeseries.py index ea02a46a..e1088744 100644 --- a/Python_Engine/Python/src/python_toolkit/helpers/timeseries.py +++ b/Python_Engine/Python/src/python_toolkit/helpers/timeseries.py @@ -1,8 +1,10 @@ -from typing import Any +from typing import Any + import pandas as pd from ..bhom.analytics import bhom_analytics + @bhom_analytics() def validate_timeseries( obj: Any, @@ -34,9 +36,7 @@ def validate_timeseries( if not isinstance(obj.index, pd.DatetimeIndex): raise TypeError("series must have a datetime index") if is_annual: - if (obj.index.day_of_year.nunique() != 365) or ( - obj.index.day_of_year.nunique() != 366 - ): + if (obj.index.day_of_year.nunique() != 365) or (obj.index.day_of_year.nunique() != 366): raise ValueError("series is not annual") if is_hourly: if obj.index.hour.nunique() != 24: @@ -47,7 +47,9 @@ def validate_timeseries( @bhom_analytics() -def timeseries_summary_monthly(series: pd.Series, bins: list[float], bin_names: list[str] = None, density: bool = False): +def timeseries_summary_monthly( + series: pd.Series, bins: list[float], bin_names: list[str] | None = None, density: bool = False +): if not isinstance(series, pd.Series): raise ValueError("The series must be a pandas series.") @@ -57,13 +59,11 @@ def timeseries_summary_monthly(series: pd.Series, bins: list[float], bin_names: df = pd.cut(series, bins=bins, labels=bin_names, include_lowest=True) if df.isna().any(): - raise ValueError( - f"The input value/s are outside the range of the given bins ({bins[0]} <= x <= {bins[-1]})." - ) - + raise ValueError(f"The input value/s are outside the range of the given bins ({bins[0]} <= x <= {bins[-1]}).") + counts = df.groupby(series.index.month).value_counts().unstack().sort_index(axis=0) counts.columns.name = None counts.index.name = "Month" if density: return counts.div(counts.sum(axis=1), axis=0) - return counts \ No newline at end of file + return counts diff --git a/Python_Engine/Python/src/python_toolkit/plot/__init__.py b/Python_Engine/Python/src/python_toolkit/plot/__init__.py new file mode 100644 index 00000000..eaf31df2 --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/plot/__init__.py @@ -0,0 +1,5 @@ +"""Plotting methods (requires the "plot" extra: ``python_toolkit[plot]``).""" + +from .._optional import require_extra + +require_extra("plot", "matplotlib", "numpy", "pandas") diff --git a/Python_Engine/Python/src/python_toolkit/plot/cmap_sample.py b/Python_Engine/Python/src/python_toolkit/plot/cmap_sample.py index 89079214..090f7e7d 100644 --- a/Python_Engine/Python/src/python_toolkit/plot/cmap_sample.py +++ b/Python_Engine/Python/src/python_toolkit/plot/cmap_sample.py @@ -1,42 +1,37 @@ +import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import Colormap, Normalize from matplotlib.figure import Figure -import numpy as np -from typing import Union, Optional plt.rcParams["figure.max_open_warning"] = 0 + def cmap_sample_plot( - cmap: Union[str, Colormap], - bounds: Optional[tuple] = None, - figsize: tuple = (9, 1), - bins: int = 256 + cmap: str | Colormap, bounds: tuple | None = None, figsize: tuple = (9, 1), bins: int = 256 ) -> Figure: + """Generate a sample plot for a given colormap. - """ - Generate a sample plot for a given colormap. - Args: cmap: Either a colormap string (e.g., 'viridis') or a custom Colormap object bounds: Optional tuple of (vmin, vmax) for normalization. If None, uses (0, 1) figsize: Figure size as (width, height) bins: Number of discrete bins for the gradient. Defaults to 256. + Returns: Matplotlib Figure object """ - # Set bounds if bounds is None: bounds = (0, 1) - + vmin, vmax = bounds - + # Create a gradient image with appropriate range. # Use endpoint=False to avoid an emphasized terminal color column at the # right edge when rasterized into a small preview. gradient_row = np.linspace(vmin, vmax, bins, endpoint=False) gradient = np.vstack([gradient_row, gradient_row]) - + # Create the figure and axis fig, ax = plt.subplots(figsize=figsize) fig.patch.set_alpha(0) @@ -46,10 +41,10 @@ def cmap_sample_plot( ax.set_facecolor("none") ax.set_position([0, 0, 1, 1]) ax.margins(x=0, y=0) - + # Create normalization if custom colormap or custom bounds norm = Normalize(vmin=vmin, vmax=vmax) - + # Display the gradient with the specified colormap ax.imshow( gradient, @@ -59,23 +54,25 @@ def cmap_sample_plot( interpolation="nearest", resample=False, ) - + # Remove axes for a cleaner look ax.set_axis_off() - + return fig + if __name__ == "__main__": # Example 1: Using a preset colormap string - fig1 = cmap_sample_plot('viridis') - + fig1 = cmap_sample_plot("viridis") + # Example 2: Using a custom colormap with bounds - fig2 = cmap_sample_plot('plasma', bounds=(0, 100), bins=6) - + fig2 = cmap_sample_plot("plasma", bounds=(0, 100), bins=6) + # Example 3: Creating and using a custom colormap from matplotlib.colors import ListedColormap - custom_colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728'] + + custom_colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728"] custom_cmap = ListedColormap(custom_colors) fig3 = cmap_sample_plot(custom_cmap, bounds=(0, 3)) - - plt.show() \ No newline at end of file + + plt.show() diff --git a/Python_Engine/Python/src/python_toolkit/plot/diurnal.py b/Python_Engine/Python/src/python_toolkit/plot/diurnal.py index ed42fdaf..b7fcbcdf 100644 --- a/Python_Engine/Python/src/python_toolkit/plot/diurnal.py +++ b/Python_Engine/Python/src/python_toolkit/plot/diurnal.py @@ -1,8 +1,7 @@ -"""Methods for plotting diurnal profiles from time-indexed data.""" +"""Methods for plotting diurnal profiles from time-indexed data.""" import calendar import textwrap -from typing import Tuple import matplotlib.collections as mcollections import matplotlib.lines as mlines @@ -21,7 +20,7 @@ def diurnal( series: pd.Series, ax: plt.Axes = None, period: str = "daily", - quantile_range: Tuple[float, float] = (0.05, 0.95), + quantile_range: tuple[float, float] = (0.05, 0.95), median: bool = True, mean: bool = True, **kwargs, @@ -52,7 +51,6 @@ def diurnal( plt.Axes: A matplotlib Axes object. """ - if not isinstance(series.index, pd.DatetimeIndex): raise ValueError("Series passed is not datetime indexed.") @@ -86,10 +84,7 @@ def diurnal( series = series.replace([-np.inf, np.inf], np.nan).dropna() # Remove outliers - series = series[ - (series >= series.quantile(minmax_range[0])) - & (series <= series.quantile(minmax_range[1])) - ] + series = series[(series >= series.quantile(minmax_range[0])) & (series <= series.quantile(minmax_range[1]))] # group data if period == "daily": @@ -161,9 +156,7 @@ def diurnal( color=color, lw=None, ec=None, - label=f"{quantile_range[0]:0.0%}-{quantile_range[1]:0.0%}ile" - if n == 0 - else "_nolegend_", + label=f"{quantile_range[0]:0.0%}-{quantile_range[1]:0.0%}ile" if n == 0 else "_nolegend_", ) # q-extreme ax.fill_between( @@ -235,9 +228,7 @@ def diurnal( @bhom_analytics() -def stacked_diurnals( - datasets: list[pd.Series], period: str = "monthly", **kwargs -) -> plt.Figure: +def stacked_diurnals(datasets: list[pd.Series], period: str = "monthly", **kwargs) -> plt.Figure: """Create a matplotlib figure with stacked diurnal profiles. Args: @@ -256,16 +247,13 @@ def stacked_diurnals( plt.Figure: A matplotlib Figure object. """ - if len(datasets) <= 1: raise ValueError("stacked_diurnals requires at least two datasets.") - + style_context = kwargs.pop("style_context", "python_toolkit.bhom") with plt.style.context(style_context): - fig, axes = plt.subplots( - len(datasets), 1, figsize=(12, 2 * len(datasets)), sharex=True - ) + fig, axes = plt.subplots(len(datasets), 1, figsize=(12, 2 * len(datasets)), sharex=True) for n, (ax, series) in enumerate(zip(axes, datasets)): if "colors" in kwargs: @@ -279,21 +267,11 @@ def stacked_diurnals( new_handles = [] for handle in handles: if isinstance(handle, mcollections.PolyCollection): - new_handles.append( - mpatches.Patch( - color="slategray", alpha=handle.get_alpha(), edgecolor=None - ) - ) + new_handles.append(mpatches.Patch(color="slategray", alpha=handle.get_alpha(), edgecolor=None)) if isinstance(handle, mlines.Line2D): - new_handles.append( - mlines.Line2D( - (0,), (0,), color="slategray", linestyle=handle.get_linestyle() - ) - ) + new_handles.append(mlines.Line2D((0,), (0,), color="slategray", linestyle=handle.get_linestyle())) - plt.legend( - new_handles, labels, bbox_to_anchor=(0.5, -0.12), loc="upper center", ncol=4 - ) + plt.legend(new_handles, labels, bbox_to_anchor=(0.5, -0.12), loc="upper center", ncol=4) fig.suptitle( create_title( diff --git a/Python_Engine/Python/src/python_toolkit/plot/heatmap.py b/Python_Engine/Python/src/python_toolkit/plot/heatmap.py index 2eb7e280..b15314bd 100644 --- a/Python_Engine/Python/src/python_toolkit/plot/heatmap.py +++ b/Python_Engine/Python/src/python_toolkit/plot/heatmap.py @@ -1,4 +1,4 @@ -"""Methods for plotting heatmaps from time-indexed data.""" +"""Methods for plotting heatmaps from time-indexed data.""" import matplotlib.dates as mdates import matplotlib.pyplot as plt @@ -46,27 +46,22 @@ def heatmap( The populated plt.Axes object. """ validate_timeseries(series) - - + day_time_matrix = ( - series.dropna() - .to_frame() - .pivot_table(columns=series.dropna().index.date, index=series.dropna().index.time) + series.dropna().to_frame().pivot_table(columns=series.dropna().index.date, index=series.dropna().index.time) ) x = mdates.date2num(day_time_matrix.columns.get_level_values(1)) - y = mdates.date2num( - pd.to_datetime([f"2017-01-01 {i}" for i in day_time_matrix.index]) - ) + y = mdates.date2num(pd.to_datetime([f"2017-01-01 {i}" for i in day_time_matrix.index])) z = day_time_matrix.values if "mask" in kwargs: if not isinstance(kwargs["mask"], (list, np.ndarray, pd.Series)): raise TypeError("The type of 'mask' must be a list, numpy ndarray or pandas Series") if len(kwargs["mask"]) != len(series): - raise ValueError( - f"Length of mask ({len(kwargs['mask'])}) must match length of data ({len(series)})." - ) - mask_flip = pd.Series(kwargs.pop("mask")).to_frame().pivot_table(columns=series.index.date, index=series.index.time) + raise ValueError(f"Length of mask ({len(kwargs['mask'])}) must match length of data ({len(series)}).") + mask_flip = ( + pd.Series(kwargs.pop("mask")).to_frame().pivot_table(columns=series.index.date, index=series.index.time) + ) z = np.ma.masked_array(z, mask=mask_flip) # handle non-standard kwargs @@ -126,4 +121,4 @@ def heatmap( ax.set_title(title) - return ax \ No newline at end of file + return ax diff --git a/Python_Engine/Python/src/python_toolkit/plot/histogram.py b/Python_Engine/Python/src/python_toolkit/plot/histogram.py index 97a3b833..bf294b37 100644 --- a/Python_Engine/Python/src/python_toolkit/plot/histogram.py +++ b/Python_Engine/Python/src/python_toolkit/plot/histogram.py @@ -1,23 +1,25 @@ -"""Methods for plotting binned data""" +"""Methods for plotting binned data.""" import calendar -import pandas as pd -import numpy as np + import matplotlib.pyplot as plt import matplotlib.ticker as mticker +import numpy as np +import pandas as pd from ..bhom.analytics import bhom_analytics -from ..helpers.timeseries import validate_timeseries, timeseries_summary_monthly +from ..helpers.timeseries import timeseries_summary_monthly, validate_timeseries from .utilities import contrasting_colour + @bhom_analytics() def histogram( series: pd.Series, ax: plt.Axes = None, - bins: list[float] | list[int] = None, + bins: list[float] | list[int] | None = None, **kwargs, - ) -> plt.Axes: - """Create a histogram of a pandas series +) -> plt.Axes: + """Create a histogram of a pandas series. Args: series (pd.Series): @@ -37,11 +39,9 @@ def histogram( plt.Axes: The populated plt.Axes object. """ - if bins is None: + if bins is None or len(bins) <= 1: bins = np.linspace(series.values.min(), series.values.max(), 31) - elif len(bins) <= 1: - bins = np.linspace(series.values.min(), series.values.max(), 31) - + style_context = kwargs.pop("style_context", "python_toolkit.bhom") with plt.style.context(style_context): @@ -50,19 +50,20 @@ def histogram( show_legend = kwargs.pop("show_legend", True) - ax.hist(series.values, bins=bins, label = series.name, density=False, **kwargs) + ax.hist(series.values, bins=bins, label=series.name, density=False, **kwargs) if show_legend: ax.legend() return ax + @bhom_analytics() def monthly_proportional_histogram( series: pd.Series, bins: list[float], ax: plt.Axes = None, - labels: list[str] = None, + labels: list[str] | None = None, show_year_in_label: bool = False, show_labels: bool = False, show_legend: bool = False, @@ -94,30 +95,20 @@ def monthly_proportional_histogram( plt.Axes: The populated plt.Axes object. """ - validate_timeseries(series) - + style_context = kwargs.pop("style_context", "python_toolkit.bhom") with plt.style.context(style_context): if ax is None: ax = plt.gca() - + counts = timeseries_summary_monthly(series, bins, labels, density=True) if show_year_in_label: - counts.columns = [ - f"{year}\n{calendar.month_abbr[month]}" for year, month in counts.columns.values - ] - - counts.plot( - ax = ax, - kind = "bar", - stacked = True, - width = kwargs.pop("width", 1), - legend = False, - **kwargs - ) + counts.columns = [f"{year}\n{calendar.month_abbr[month]}" for year, month in counts.columns.values] + + counts.plot(ax=ax, kind="bar", stacked=True, width=kwargs.pop("width", 1), legend=False, **kwargs) ax.set_xlim(-0.5, len(counts) - 0.5) ax.set_ylim(0, 1) @@ -127,7 +118,7 @@ def monthly_proportional_histogram( ha="center", rotation=0, ) - + for spine in ["top", "right", "left", "bottom"]: ax.spines[spine].set_visible(False) ax.yaxis.set_major_formatter(mticker.PercentFormatter(1)) @@ -143,9 +134,7 @@ def monthly_proportional_histogram( if show_labels: for i, c in enumerate(ax.containers): label_colors = [contrasting_colour(i.get_facecolor()) for i in c.patches] - labels = [ - f"{v.get_height():0.1%}" if v.get_height() > 0.15 else "" for v in c - ] + labels = [f"{v.get_height():0.1%}" if v.get_height() > 0.15 else "" for v in c] ax.bar_label( c, labels=labels, @@ -154,4 +143,4 @@ def monthly_proportional_histogram( fontsize="x-small", ) - return ax \ No newline at end of file + return ax diff --git a/Python_Engine/Python/src/python_toolkit/plot/parallel_coordinate_plot.py b/Python_Engine/Python/src/python_toolkit/plot/parallel_coordinate_plot.py index 60c1d86f..81148589 100644 --- a/Python_Engine/Python/src/python_toolkit/plot/parallel_coordinate_plot.py +++ b/Python_Engine/Python/src/python_toolkit/plot/parallel_coordinate_plot.py @@ -1,16 +1,15 @@ -import plotly.graph_objects as go +import math + import pandas as pd +import plotly.graph_objects as go from matplotlib.colors import Colormap -import decimal as d -from typing import List, Dict -import math from ..bhom.analytics import bhom_analytics -def set_dimensions(df: pd.DataFrame, tick_mark_count: int, dp:int) -> List[Dict[str, any]]: +def set_dimensions(df: pd.DataFrame, tick_mark_count: int, dp: int) -> list[dict[str, any]]: """Set the dimensions for a parallel coordinate plot, based on column datatypes and unique values. - + Args: df (pd.DataFrame): The pandas DataFrame to plot. @@ -18,68 +17,68 @@ def set_dimensions(df: pd.DataFrame, tick_mark_count: int, dp:int) -> List[Dict[ The number of tick marks to show on the parallel coordinate plot. dp (int): The number of decimal places to show on the tick marks. - + Returns: list[dict[str, any]]: A list of dimensions to plot. """ - df_copy = df.copy() dimensions = [] for column in df_copy.columns: - dim = {} - dim['label'] = str(column) + dim["label"] = str(column) if df_copy[column].dtype == "object": - #for catagorical data types, convert to numerical, with text as tick marks + # for catagorical data types, convert to numerical, with text as tick marks df_copy[column] = df_copy[column].astype("category").cat.codes - dim['values'] = df_copy[column] - dim['tickvals'] = df_copy[column].unique() - dim['ticktext'] = df[column].unique() + dim["values"] = df_copy[column] + dim["tickvals"] = df_copy[column].unique() + dim["ticktext"] = df[column].unique() dimensions.append(dim) continue - - dim['values'] = df_copy[column] - if df_copy[column].nunique() < tick_mark_count: + dim["values"] = df_copy[column] - dim['range'] = [df_copy[column].min(), df_copy[column].max()] - dim['tickvals'] = dim['ticktext'] = df_copy[column].unique() + if df_copy[column].nunique() < tick_mark_count: + dim["range"] = [df_copy[column].min(), df_copy[column].max()] + dim["tickvals"] = dim["ticktext"] = df_copy[column].unique() dimensions.append(dim) else: # reduce the number of tick marks if the column has a large number of unique values - dim['range'] = [df_copy[column].min(), df_copy[column].max()] + dim["range"] = [df_copy[column].min(), df_copy[column].max()] - if (dim['range'][1] - dim['range'][0] +1) < tick_mark_count: - tick_mark_count = math.ceil(dim['range'][1] - dim['range'][0]) + 1 + if (dim["range"][1] - dim["range"][0] + 1) < tick_mark_count: + tick_mark_count = math.ceil(dim["range"][1] - dim["range"][0]) + 1 - dim['tickvals'] = [df_copy[column].min() + i * (df_copy[column].max() - df_copy[column].min()) / (tick_mark_count - 1) for i in range(tick_mark_count)] - dim['ticktext'] = [round(i ,dp) for i in dim['tickvals']] + dim["tickvals"] = [ + df_copy[column].min() + i * (df_copy[column].max() - df_copy[column].min()) / (tick_mark_count - 1) + for i in range(tick_mark_count) + ] + dim["ticktext"] = [round(i, dp) for i in dim["tickvals"]] dimensions.append(dim) return dimensions - + + @bhom_analytics() def parallel_coordinate_plot( - - df: pd.DataFrame = pd.DataFrame(), - variables_to_show: list = None, + df: pd.DataFrame | None = None, + variables_to_show: list | None = None, decimal_places: int = 0, tick_mark_count: int = 11, - colour_key: str = None, + colour_key: str | None = None, cmap: Colormap = "viridis", - dimensions: List[dict] = None, + dimensions: list[dict] | None = None, plot_title: str = "", - plot_bgcolour: str = 'black', - paper_bgcolour: str = 'black', - font_colour: str = 'white', + plot_bgcolour: str = "black", + paper_bgcolour: str = "black", + font_colour: str = "white", **kwargs, ) -> go.Figure: """Create a parallel coordinate plot of a pandas DataFrame. @@ -109,12 +108,13 @@ def parallel_coordinate_plot( The color of the font used in the plot. Defaults to 'white'. **kwargs: Additional keyword arguments to pass to go.Parcoords(). - + Returns: go.Figure: The populated go.Figure object. """ - + if df is None: + df = pd.DataFrame() if variables_to_show is not None: df = df[variables_to_show] @@ -123,22 +123,13 @@ def parallel_coordinate_plot( if colour_key is None and not df.empty: colour_key = df.columns[-1] - - line = dict(color=df[colour_key], colorscale=cmap) - - fig = go.Figure( - data=go.Parcoords( - line = line, - dimensions = dimensions, - **kwargs - ) - ) + + line = {"color": df[colour_key], "colorscale": cmap} + + fig = go.Figure(data=go.Parcoords(line=line, dimensions=dimensions, **kwargs)) fig.update_layout( - title = plot_title, - plot_bgcolor = plot_bgcolour, - paper_bgcolor = paper_bgcolour, - font_color = font_colour + title=plot_title, plot_bgcolor=plot_bgcolour, paper_bgcolor=paper_bgcolour, font_color=font_colour ) - return fig \ No newline at end of file + return fig diff --git a/Python_Engine/Python/src/python_toolkit/plot/spatial_heatmap.py b/Python_Engine/Python/src/python_toolkit/plot/spatial_heatmap.py index 8861ffaa..ae351134 100644 --- a/Python_Engine/Python/src/python_toolkit/plot/spatial_heatmap.py +++ b/Python_Engine/Python/src/python_toolkit/plot/spatial_heatmap.py @@ -1,4 +1,4 @@ -"""Methods for plotting spatial heatmaps.""" +"""Methods for plotting spatial heatmaps.""" import matplotlib.pyplot as plt import numpy as np @@ -14,21 +14,21 @@ def spatial_heatmap( triangulations: list[Triangulation], values: list[list[float]], - levels: list[float] | int = None, - contours: list[float] = None, - contour_colors: list[str] = None, - contour_widths: list[float] = None, + levels: list[float] | int | None = None, + contours: list[float] | None = None, + contour_colors: list[str] | None = None, + contour_widths: list[float] | None = None, cmap: Colormap = "viridis", extend: str = "neither", norm: BoundaryNorm = None, - xlims: list[float] = None, - ylims: list[float] = None, + xlims: list[float] | None = None, + ylims: list[float] | None = None, colorbar_label: str = "", title: str = "", - highlight_pts: dict[str, tuple[int]] = None, + highlight_pts: dict[str, tuple[int]] | None = None, show_legend_title: bool = True, clabels: bool = False, - style_context:str = "python_toolkit.bhom", + style_context: str = "python_toolkit.bhom", ) -> Figure: """Plot a spatial map of a variable using a triangulation and associated values. @@ -76,14 +76,10 @@ def spatial_heatmap( """ for tri, zs in list(zip(*[triangulations, values])): if len(tri.x) != len(zs): - raise ValueError( - "The shape of the triangulations and values given do not match." - ) + raise ValueError("The shape of the triangulations and values given do not match.") if levels is None: - levels = np.linspace( - min(np.amin(i) for i in values), max(np.amax(i) for i in values), 10 - ) + levels = np.linspace(min(np.amin(i) for i in values), max(np.amax(i) for i in values), 10) if xlims is None: xlims = [ @@ -96,7 +92,7 @@ def spatial_heatmap( min(i.y.min() for i in triangulations), max(i.y.max() for i in triangulations), ] - + with plt.style.context(style_context): fig, ax = plt.subplots(1, 1, figsize=(8, 8)) @@ -108,15 +104,10 @@ def spatial_heatmap( tcls = [] for tri, zs in list(zip(*[triangulations, values])): - tcf = ax.tricontourf( - tri, zs, extend=extend, cmap=cmap, levels=levels, norm=norm - ) + tcf = ax.tricontourf(tri, zs, extend=extend, cmap=cmap, levels=levels, norm=norm) # add contour lines if contours is not None: - if not ( - all(i < np.amin(zs) for i in contours) - or all(i > np.amax(zs) for i in contours) - ): + if not (all(i < np.amin(zs) for i in contours) or all(i > np.amax(zs) for i in contours)): if contour_widths is None: contour_widths = [1.5] * len(contours) if contour_colors is None: @@ -136,14 +127,10 @@ def spatial_heatmap( if highlight_pts is not None: if len(triangulations) > 1: - raise ValueError( - "Point highlighting is only possible for 1-length triangulations." - ) + raise ValueError("Point highlighting is only possible for 1-length triangulations.") pt_size = (xlims[1] - xlims[0]) / 5 for k, v in highlight_pts.items(): - ax.scatter( - triangulations[0].x[v], triangulations[0].y[v], s=pt_size, c="red" - ) + ax.scatter(triangulations[0].x[v], triangulations[0].y[v], s=pt_size, c="red") ax.text( triangulations[0].x[v] + (pt_size / 10), triangulations[0].y[v], @@ -158,7 +145,8 @@ def spatial_heatmap( cax = divider.append_axes("right", size="5%", pad=0.1, aspect=20) cbar = plt.colorbar( - tcf, cax=cax # , format=mticker.StrMethodFormatter("{x:04.1f}") + tcf, + cax=cax, # , format=mticker.StrMethodFormatter("{x:04.1f}") ) cbar.outline.set_visible(False) cbar.set_label(colorbar_label) diff --git a/Python_Engine/Python/src/python_toolkit/plot/timeseries.py b/Python_Engine/Python/src/python_toolkit/plot/timeseries.py index 35577787..93b2b689 100644 --- a/Python_Engine/Python/src/python_toolkit/plot/timeseries.py +++ b/Python_Engine/Python/src/python_toolkit/plot/timeseries.py @@ -1,6 +1,7 @@ -"""Methods for plotting time-indexed data.""" +"""Methods for plotting time-indexed data.""" from datetime import datetime + import matplotlib.pyplot as plt import pandas as pd @@ -12,8 +13,8 @@ def timeseries( series: pd.Series, ax: plt.Axes = None, - xlims: tuple[datetime] = None, - ylims: tuple[datetime] = None, + xlims: tuple[datetime] | None = None, + ylims: tuple[datetime] | None = None, **kwargs, ) -> plt.Axes: """Create a timeseries plot of a pandas Series. @@ -36,9 +37,8 @@ def timeseries( plt.Axes: The populated plt.Axes object. """ - validate_timeseries(series) - + style_context = kwargs.pop("style_context", "python_toolkit.bhom") with plt.style.context(style_context): @@ -59,4 +59,4 @@ def timeseries( else: ax.set_ylim(ylims) - return ax \ No newline at end of file + return ax diff --git a/Python_Engine/Python/src/python_toolkit/plot/utilities.py b/Python_Engine/Python/src/python_toolkit/plot/utilities.py index fd71cc9d..9b6c1638 100644 --- a/Python_Engine/Python/src/python_toolkit/plot/utilities.py +++ b/Python_Engine/Python/src/python_toolkit/plot/utilities.py @@ -1,12 +1,15 @@ -"""Text and colour utility methods for plotting""" +"""Text and colour utility methods for plotting.""" import base64 import colorsys +import copy import io from pathlib import Path from typing import Any -import copy +import matplotlib.image as mimage +import matplotlib.pyplot as plt +import matplotlib.ticker as mticker import numpy as np from matplotlib.colors import ( LinearSegmentedColormap, @@ -18,13 +21,12 @@ to_rgb, to_rgba_array, ) -import matplotlib.image as mimage -import matplotlib.pyplot as plt -import matplotlib.ticker as mticker from matplotlib.tri import Triangulation from PIL import Image + from ..bhom.analytics import bhom_analytics + @bhom_analytics() def average_color(colors: Any, keep_alpha: bool = False) -> str: """Return the average color from a list of colors. @@ -39,21 +41,19 @@ def average_color(colors: Any, keep_alpha: bool = False) -> str: color: str The average color in hex format. """ - if not isinstance(colors, (list, tuple)): raise ValueError("colors must be a list") for i in colors: if not is_color_like(i): - raise ValueError( - f"colors must be a list of valid colors - '{i}' is not valid." - ) + raise ValueError(f"colors must be a list of valid colors - '{i}' is not valid.") if len(colors) == 1: return colors[0] return rgb2hex(to_rgba_array(colors).mean(axis=0), keep_alpha=keep_alpha) + @bhom_analytics() def animation( images: list[str | Path | Image.Image], @@ -85,9 +85,7 @@ def animation( elif isinstance(i, Image.Image): _images.append(i) else: - raise ValueError( - f"images must be a list of strings, Paths or PIL Image objects - {i} is not valid." - ) + raise ValueError(f"images must be a list of strings, Paths or PIL Image objects - {i} is not valid.") # create white background background = Image.new("RGBA", _images[0].size, (255, 255, 255)) @@ -107,6 +105,7 @@ def animation( return output_gif + def create_title(text: str, plot_type: str) -> str: """Create a title for a plot. @@ -131,6 +130,7 @@ def create_title(text: str, plot_type: str) -> str: ] ) + def contrasting_colour(color: Any): """Calculate the contrasting color for a given color. @@ -145,8 +145,9 @@ def contrasting_colour(color: Any): """ return ".15" if relative_luminance(color) > 0.408 else "w" + def relative_luminance(color: Any): - """Calculate the relative luminance of a color according to W3C standards + """Calculate the relative luminance of a color according to W3C standards. Args: color (Any): @@ -165,11 +166,9 @@ def relative_luminance(color: Any): except ValueError: return lum -def colormap_sequential( - *colors: str | float | int | tuple, N: int = 256 -) -> LinearSegmentedColormap: - """ - Create a sequential colormap from a list of input colors. + +def colormap_sequential(*colors: str | float | int | tuple, N: int = 256) -> LinearSegmentedColormap: + """Create a sequential colormap from a list of input colors. Args: *colors (str | float | int | tuple): @@ -192,7 +191,6 @@ def colormap_sequential( "#732982" ) """ - if len(colors) < 2: raise KeyError("Not enough colors input to create a colormap.") @@ -206,13 +204,14 @@ def colormap_sequential( N=N, ) + def annotate_imshow( im: mimage.AxesImage, - data: list[float] = None, + data: list[float] | None = None, valfmt: str = "{x:.2f}", textcolors: tuple[str] = ("black", "white"), - threshold: float = None, - exclude_vals: list[float] = None, + threshold: float | None = None, + exclude_vals: list[float] | None = None, **text_kw, ) -> list[str]: """A function to annotate a heatmap. @@ -241,7 +240,6 @@ def annotate_imshow( list[str]: The texts added to the AxesImage. """ - if not isinstance(data, (list, np.ndarray)): data = im.get_array() @@ -273,9 +271,9 @@ def annotate_imshow( return texts + def lighten_color(color: str | tuple, amount: float = 0.5) -> tuple[float]: - """ - Lightens the given color by multiplying (1-luminosity) by the given amount. + """Lightens the given color by multiplying (1-luminosity) by the given amount. Args: color (str): @@ -314,16 +312,16 @@ def base64_to_image(base64_string: str, image_path: Path) -> Path: Path: The path to the image file. """ - # remove html pre-amble, if necessary if base64_string.startswith("data:image"): base64_string = base64_string.split(";")[-1] with open(Path(image_path), "wb") as fp: - fp.write(base64.decodebytes(base64_string.encode('utf-8'))) + fp.write(base64.decodebytes(base64_string.encode("utf-8"))) return image_path + @bhom_analytics() def image_to_base64(image_path: Path, html: bool = False) -> str: """Load an image file from disk and convert to base64 string. @@ -338,16 +336,13 @@ def image_to_base64(image_path: Path, html: bool = False) -> str: str: A base64 string encoding of the input image file. """ - # convert path string to Path object image_path = Path(image_path).absolute() # ensure format is supported supported_formats = [".png", ".jpg", ".jpeg"] if image_path.suffix not in supported_formats: - raise ValueError( - f"'{image_path.suffix}' format not supported. Use one of {supported_formats}" - ) + raise ValueError(f"'{image_path.suffix}' format not supported. Use one of {supported_formats}") # load image and convert to base64 string with open(image_path, "rb") as image_file: @@ -360,6 +355,7 @@ def image_to_base64(image_path: Path, html: bool = False) -> str: return base64_string + @bhom_analytics() def figure_to_base64(figure: plt.Figure, html: bool = False, transparent: bool = True) -> str: """Convert a matplotlib figure object into a base64 string. @@ -374,7 +370,6 @@ def figure_to_base64(figure: plt.Figure, html: bool = False, transparent: bool = str: A base64 string encoding of the input figure object. """ - buffer = io.BytesIO() figure.savefig(buffer, transparent=transparent) buffer.seek(0) @@ -387,6 +382,7 @@ def figure_to_base64(figure: plt.Figure, html: bool = False, transparent: bool = return base64_string + @bhom_analytics() def figure_to_image(fig: plt.Figure) -> Image: """Convert a matplotlib Figure object into a PIL Image. @@ -399,7 +395,6 @@ def figure_to_image(fig: plt.Figure) -> Image: Image: A PIL Image. """ - # draw the renderer fig.canvas.draw() @@ -411,10 +406,9 @@ def figure_to_image(fig: plt.Figure) -> Image: return Image.fromarray(buf) + @bhom_analytics() -def tile_images( - imgs: list[Path] | list[Image.Image], rows: int, cols: int -) -> Image.Image: +def tile_images(imgs: list[Path] | list[Image.Image], rows: int, cols: int) -> Image.Image: """Tile a set of images into a grid. Args: @@ -429,16 +423,13 @@ def tile_images( Image.Image: A PIL image of the tiled images. """ - imgs = np.array([Path(i) for i in np.array(imgs).flatten()]) # open images if paths passed imgs = [Image.open(img) if isinstance(img, Path) else img for img in imgs] if len(imgs) != rows * cols: - raise ValueError( - f"The number of images given ({len(imgs)}) does not equal ({rows}*{cols})" - ) + raise ValueError(f"The number of images given ({len(imgs)}) does not equal ({rows}*{cols})") # ensure each image has the same dimensions w, h = imgs[0].size @@ -455,6 +446,7 @@ def tile_images( return grid + @bhom_analytics() def triangulation_area(triang: Triangulation) -> float: """Calculate the area of a matplotlib Triangulation. @@ -467,7 +459,6 @@ def triangulation_area(triang: Triangulation) -> float: float: The area of the Triangulation in the units given. """ - triangles = triang.triangles x, y = triang.x, triang.y a, _ = triangles.shape @@ -476,21 +467,20 @@ def triangulation_area(triang: Triangulation) -> float: np.abs( 0.5 * ( - (x[triangles[i, 1]] - x[triangles[i, 0]]) - * (y[triangles[i, 2]] - y[triangles[i, 0]]) - - (x[triangles[i, 2]] - x[triangles[i, 0]]) - * (y[triangles[i, 1]] - y[triangles[i, 0]]) + (x[triangles[i, 1]] - x[triangles[i, 0]]) * (y[triangles[i, 2]] - y[triangles[i, 0]]) + - (x[triangles[i, 2]] - x[triangles[i, 0]]) * (y[triangles[i, 1]] - y[triangles[i, 0]]) ) ) ) return area + @bhom_analytics() def create_triangulation( x: list[float], y: list[float], - alpha: float = None, + alpha: float | None = None, max_iterations: int = 250, increment: float = 0.01, ) -> Triangulation: @@ -516,7 +506,6 @@ def create_triangulation( Triangulation: A matplotlib Triangulation object. """ - if alpha is None: # TODO - add method here to automatically determine appropriate alpha value alpha = 1.1 @@ -549,13 +538,12 @@ def create_triangulation( break if count > max_iterations: plt.close(fig) - raise ValueError( - f"Could not create a valid triangulation mask within {max_iterations}" - ) + raise ValueError(f"Could not create a valid triangulation mask within {max_iterations}") plt.close(fig) triang.set_mask(maxi > alpha) return triang + @bhom_analytics() def format_polar_plot(ax: plt.Axes, yticklabels: bool = True) -> plt.Axes: """Format a polar plot, to save on having to write this every time!""" @@ -570,9 +558,7 @@ def format_polar_plot(ax: plt.Axes, yticklabels: bool = True) -> plt.Axes: ax.set_xticks(np.radians((0, 90, 180, 270)), minor=False) ax.set_xticklabels(("N", "E", "S", "W"), minor=False, **{"fontsize": "medium"}) ax.set_xticks( - np.radians( - (22.5, 45, 67.5, 112.5, 135, 157.5, 202.5, 225, 247.5, 292.5, 315, 337.5) - ), + np.radians((22.5, 45, 67.5, 112.5, 135, 157.5, 202.5, 225, 247.5, 292.5, 315, 337.5)), minor=True, ) ax.set_xticklabels( diff --git a/Python_Engine/Python/src/python_toolkit/scaffold/__init__.py b/Python_Engine/Python/src/python_toolkit/scaffold/__init__.py new file mode 100644 index 00000000..be972a56 --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/scaffold/__init__.py @@ -0,0 +1,226 @@ +"""Create a new BHoM Python toolkit from the standard template. + +Usage (from any environment with python_toolkit installed):: + + bhom-new-toolkit Wind_Toolkit --output C:/repos/Wind_Toolkit/Wind_Toolkit_Engine/Python --python 3.11 + +or equivalently ``python -m python_toolkit.scaffold ...``, or ``BH.Engine.Python.Compute.CreateToolkit`` from C#. + +The generated toolkit is a standalone UV project that: + +* depends on the root ``python_toolkit`` (and any other toolkits given with ``--depends-on``) through UV path sources + pointing at the deployed BHoM Python extensions directory, so each toolkit can use its own Python version; +* extends the shared BHoM ruff configuration; +* contains an example module using BHoM logging and usage analytics, pytest tests, and Sphinx documentation. +""" + +from __future__ import annotations + +import argparse +import keyword +import os +import re +import sys +from collections.abc import Sequence +from dataclasses import dataclass, field +from pathlib import Path +from string import Template + +TEMPLATE_DIRECTORY = Path(__file__).parent / "template" +ROOT_TOOLKIT = "Python_Toolkit" +TOOLKIT_NAME_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9]*(_[A-Za-z0-9]+)*$") +PYTHON_VERSION_PATTERN = re.compile(r"^3\.(\d+)$") +MINIMUM_PYTHON_MINOR = 10 +EXTRAS = ("plot", "ui", "clr") + +# template file names cannot start with "." or use "__x__" folders, as the BHoM build excludes those when deploying +_RENAMES = {"dot-gitignore": ".gitignore", "dot-python-version": ".python-version"} +_PACKAGE_PLACEHOLDER = "PACKAGE_NAME" + + +def default_extensions_directory() -> Path: + """The deployed BHoM Python extensions directory (overridable with BHOM_PYTHON_EXTENSIONS_DIR).""" + override = os.environ.get("BHOM_PYTHON_EXTENSIONS_DIR") + if override: + return Path(override) + return Path(os.environ.get("PROGRAMDATA", "C:/ProgramData")) / "BHoM" / "Extensions" / "Python" + + +def package_name(toolkit_name: str) -> str: + """The Python package name for a toolkit name, e.g. ``Wind_Toolkit`` -> ``wind_toolkit``.""" + return toolkit_name.lower() + + +@dataclass +class ToolkitSpec: + """The specification of a toolkit to create.""" + + name: str + output: Path + python_version: str = "3.10" + depends_on: list[str] = field(default_factory=list) + extras: list[str] = field(default_factory=list) + description: str = "" + extensions_directory: Path = field(default_factory=default_extensions_directory) + + @property + def package(self) -> str: + """The Python package name.""" + return package_name(self.name) + + def validate(self) -> None: + """Raise ValueError if the specification is invalid.""" + if not TOOLKIT_NAME_PATTERN.match(self.name): + raise ValueError( + f"Invalid toolkit name {self.name!r}: use letters, digits and single underscores, starting with a letter " + "(e.g. 'Wind_Toolkit')." + ) + if keyword.iskeyword(self.package) or self.package == package_name(ROOT_TOOLKIT): + raise ValueError(f"{self.name!r} cannot be used as a toolkit name.") + match = PYTHON_VERSION_PATTERN.match(self.python_version) + if not match or int(match.group(1)) < MINIMUM_PYTHON_MINOR: + raise ValueError( + f"Invalid Python version {self.python_version!r}: give a major.minor version of 3.{MINIMUM_PYTHON_MINOR} " + "or later (e.g. '3.11')." + ) + for dependency in self.depends_on: + if not TOOLKIT_NAME_PATTERN.match(dependency): + raise ValueError(f"Invalid dependency toolkit name {dependency!r}.") + unknown = sorted(set(self.extras) - set(EXTRAS)) + if unknown: + raise ValueError(f"Unknown python_toolkit extras {unknown}; choose from {list(EXTRAS)}.") + if self.output.exists() and any(self.output.iterdir()): + raise ValueError(f"The output directory {self.output} already exists and is not empty.") + + def substitutions(self) -> dict[str, str]: + """The values substituted into the template files.""" + minor = int(self.python_version.split(".")[1]) + root_requirement = package_name(ROOT_TOOLKIT) + if self.extras: + root_requirement += f"[{','.join(sorted(set(self.extras)))}]" + requirements = [root_requirement] + [package_name(d) for d in self.depends_on if d != ROOT_TOOLKIT] + + sources = [] + for toolkit in [ROOT_TOOLKIT, *(d for d in self.depends_on if d != ROOT_TOOLKIT)]: + path = (self.extensions_directory / toolkit).as_posix() + sources.append(f'{package_name(toolkit)} = {{ path = "{path}", editable = true }}') + + return { + "name": self.name, + "package": self.package, + "description": self.description or f"The {self.name} BHoM Python toolkit.", + "python_version": self.python_version, + "requires_python": f">={self.python_version},<3.{minor + 1}", + "dependencies": "".join(f' "{r}",\n' for r in requirements), + "sources": "\n".join(sources), + "ruff_config": (self.extensions_directory / ROOT_TOOLKIT / "ruff.toml").as_posix(), + } + + +def create_toolkit(spec: ToolkitSpec) -> list[Path]: + """Create a toolkit from the template. + + Args: + spec: The specification of the toolkit. + + Returns: + The files created. + + Raises: + ValueError: If the specification is invalid. + """ + spec.validate() + values = spec.substitutions() + + created = [] + for template in sorted(TEMPLATE_DIRECTORY.rglob("*.tmpl")): + relative = template.relative_to(TEMPLATE_DIRECTORY).with_suffix("") + parts = [_RENAMES.get(part, part).replace(_PACKAGE_PLACEHOLDER, spec.package) for part in relative.parts] + target = spec.output.joinpath(*parts) + target.parent.mkdir(parents=True, exist_ok=True) + content = Template(template.read_text(encoding="utf-8")).substitute(values) + target.write_text(content, encoding="utf-8", newline="\n") + created.append(target) + return created + + +def next_steps(spec: ToolkitSpec) -> str: + """Instructions for wiring the created toolkit into BHoM.""" + deploy = f"$(ProgramData)\\BHoM\\Extensions\\Python\\{spec.name}" + return f"""Created {spec.name} at {spec.output} + +Next steps: + 1. Develop locally: cd "{spec.output}" && uv sync && uv run pytest + 2. Deploy with BHoM: add the following to your _Engine.csproj so that building copies this folder to + {deploy} (pass -p:BHoMSkipDeploy=true to build without deploying): + + + {deploy} + $(DefaultItemExcludes);Python\\.venv\\**;Python\\**\\__pycache__\\** + + + + + + + + + + 3. Create the environment from C#: + BH.Engine.Python.Compute.VirtualEnvironment(tomlFile: Path.Combine(Query.DirectoryEnvironments(), "{spec.name}", "pyproject.toml")) + 4. Run its tests from C#: + BH.Engine.Python.Compute.RunPytest(Path.Combine(Query.DirectoryEnvironments(), "{spec.name}"), run: true) +""" + + +def _parse_args(argv: Sequence[str] | None) -> argparse.Namespace: + parser = argparse.ArgumentParser(prog="bhom-new-toolkit", description=__doc__.split("\n\n")[0]) + parser.add_argument("name", help="The toolkit name, e.g. Wind_Toolkit. The package will be its lower-case form.") + parser.add_argument("--output", type=Path, help="The folder to create the toolkit in (default: ./).") + parser.add_argument("--python", dest="python_version", default="3.10", help="The Python version, e.g. 3.11.") + parser.add_argument( + "--depends-on", + action="append", + default=[], + metavar="TOOLKIT", + help="Another BHoM Python toolkit this toolkit depends on (repeatable). Python_Toolkit is always included.", + ) + parser.add_argument( + "--extras", action="append", default=[], choices=EXTRAS, help="python_toolkit extras to depend on (repeatable)." + ) + parser.add_argument("--description", default="", help="A one-line description of the toolkit.") + parser.add_argument( + "--extensions-dir", + type=Path, + default=default_extensions_directory(), + help="The deployed BHoM Python extensions directory containing dependency toolkits.", + ) + return parser.parse_args(argv) + + +def main(argv: Sequence[str] | None = None) -> int: + """Command line entry point. + + Args: + argv: The command line arguments (defaults to sys.argv). + + Returns: + The exit code. + """ + args = _parse_args(argv) + spec = ToolkitSpec( + name=args.name, + output=(args.output or Path.cwd() / args.name).absolute(), + python_version=args.python_version, + depends_on=args.depends_on, + extras=args.extras, + description=args.description, + extensions_directory=args.extensions_dir, + ) + try: + create_toolkit(spec) + except ValueError as error: + print(f"error: {error}", file=sys.stderr) + return 2 + print(next_steps(spec)) + return 0 diff --git a/Python_Engine/Python/src/python_toolkit/scaffold/__main__.py b/Python_Engine/Python/src/python_toolkit/scaffold/__main__.py new file mode 100644 index 00000000..8033fe03 --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/scaffold/__main__.py @@ -0,0 +1,7 @@ +"""Allow ``python -m python_toolkit.scaffold``.""" + +import sys + +from . import main + +sys.exit(main()) diff --git a/Python_Engine/Python/src/python_toolkit/scaffold/template/README.md.tmpl b/Python_Engine/Python/src/python_toolkit/scaffold/template/README.md.tmpl new file mode 100644 index 00000000..649b8732 --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/scaffold/template/README.md.tmpl @@ -0,0 +1,21 @@ +# $name + +$description + +## Development + +This toolkit is a standalone [uv](https://docs.astral.sh/uv/) project. It depends on the root BHoM +`python_toolkit` (and any other BHoM toolkits) installed in the BHoM Python extensions directory. + +```powershell +uv sync # create/update .venv +uv run pytest # run tests +uv run ruff format; uv run ruff check --fix # format and lint +uv run --group docs sphinx-build docs docs/_build/html # build documentation +``` + +## Conventions + +- Get a logger with `python_toolkit.bhom.logging.get_logger("$name")`. +- Decorate public methods with `python_toolkit.bhom.analytics.bhom_analytics()` to record usage. +- Use Google-style docstrings; they are used to generate the documentation. diff --git a/Python_Engine/Python/src/python_toolkit/scaffold/template/docs/conf.py.tmpl b/Python_Engine/Python/src/python_toolkit/scaffold/template/docs/conf.py.tmpl new file mode 100644 index 00000000..90299daa --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/scaffold/template/docs/conf.py.tmpl @@ -0,0 +1,27 @@ +"""Sphinx configuration (build with ``uv run --group docs sphinx-build docs docs/_build/html``).""" + +import importlib.metadata + +project = "$name" +author = "BHoM" +copyright = "BHoM" +try: + release = importlib.metadata.version("$package") +except importlib.metadata.PackageNotFoundError: + release = "0.0.0" + +extensions = [ + "autoapi.extension", + "myst_parser", + "sphinx.ext.napoleon", + "sphinx.ext.viewcode", +] + +autoapi_type = "python" +autoapi_dirs = ["../src"] +autoapi_options = ["members", "undoc-members", "show-inheritance", "show-module-summary"] +napoleon_google_docstring = True +napoleon_numpy_docstring = False + +html_theme = "furo" +html_title = project diff --git a/Python_Engine/Python/src/python_toolkit/scaffold/template/docs/index.md.tmpl b/Python_Engine/Python/src/python_toolkit/scaffold/template/docs/index.md.tmpl new file mode 100644 index 00000000..73fb8e23 --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/scaffold/template/docs/index.md.tmpl @@ -0,0 +1,10 @@ +# $name + +$description + +```{toctree} +:maxdepth: 2 +:caption: API reference + +autoapi/index +``` diff --git a/Python_Engine/Python/src/python_toolkit/scaffold/template/dot-gitignore.tmpl b/Python_Engine/Python/src/python_toolkit/scaffold/template/dot-gitignore.tmpl new file mode 100644 index 00000000..defc8472 --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/scaffold/template/dot-gitignore.tmpl @@ -0,0 +1,11 @@ +.venv/ +__pycache__/ +*.py[cod] +.pytest_cache/ +.pytest_results.xml +.ruff_cache/ +.coverage +htmlcov/ +docs/_build/ +docs/autoapi/ +uv.lock diff --git a/Python_Engine/Python/src/python_toolkit/scaffold/template/dot-python-version.tmpl b/Python_Engine/Python/src/python_toolkit/scaffold/template/dot-python-version.tmpl new file mode 100644 index 00000000..0b4c71ce --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/scaffold/template/dot-python-version.tmpl @@ -0,0 +1 @@ +$python_version diff --git a/Python_Engine/Python/src/python_toolkit/scaffold/template/pyproject.toml.tmpl b/Python_Engine/Python/src/python_toolkit/scaffold/template/pyproject.toml.tmpl new file mode 100644 index 00000000..99bf350a --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/scaffold/template/pyproject.toml.tmpl @@ -0,0 +1,53 @@ +[project] +name = "$package" +version = "999.999.999" # This placeholder value is replaced by the BHoM build system during packaging. +description = "$description" +readme = "README.md" +requires-python = "$requires_python" +authors = [{ name = "BHoM", email = "bhombot@burohappold.com" }] +dependencies = [ +$dependencies] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/$package"] + +# Other BHoM toolkits are installed from their deployed locations, so each toolkit keeps its own environment +# (and Python version) while sharing the root toolkit's code. +[tool.uv.sources] +$sources + +[dependency-groups] +dev = [ + "ipykernel", + "pytest", + "pytest-cov", + "ruff", +] +docs = [ + "furo", + "myst-parser", + "sphinx", + "sphinx-autoapi", +] + +[tool.uv] +default-groups = ["dev"] + +# The shared BHoM formatting and linting standard. Add toolkit-specific exceptions below it. +# (Paths in the shared file resolve relative to that file, so path-based settings must be set here.) +[tool.ruff] +extend = "$ruff_config" +src = ["src", "tests"] + +[tool.ruff.lint.extend-per-file-ignores] +"tests/**" = ["D"] +"docs/conf.py" = ["D"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "-ra --strict-markers" +markers = ["slow: long-running tests (deselect with -m \"not slow\")"] diff --git a/Python_Engine/Python/src/python_toolkit/scaffold/template/src/PACKAGE_NAME/__init__.py.tmpl b/Python_Engine/Python/src/python_toolkit/scaffold/template/src/PACKAGE_NAME/__init__.py.tmpl new file mode 100644 index 00000000..3f2e017f --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/scaffold/template/src/PACKAGE_NAME/__init__.py.tmpl @@ -0,0 +1,7 @@ +"""$description""" + +from python_toolkit.bhom.logging import get_logger + +TOOLKIT_NAME = "$name" + +LOGGER = get_logger(TOOLKIT_NAME) diff --git a/Python_Engine/Python/src/python_toolkit/scaffold/template/src/PACKAGE_NAME/example.py.tmpl b/Python_Engine/Python/src/python_toolkit/scaffold/template/src/PACKAGE_NAME/example.py.tmpl new file mode 100644 index 00000000..ddbfb379 --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/scaffold/template/src/PACKAGE_NAME/example.py.tmpl @@ -0,0 +1,20 @@ +"""An example module, showing the conventions every BHoM toolkit method should follow.""" + +from python_toolkit.bhom.analytics import bhom_analytics + +from . import LOGGER + + +@bhom_analytics() +def add(a: float, b: float) -> float: + """Add two numbers. + + Args: + a: The first number. + b: The second number. + + Returns: + The sum of a and b. + """ + LOGGER.debug("Adding %s and %s", a, b) + return a + b diff --git a/.ci/unit_tests/python/__init_.py b/Python_Engine/Python/src/python_toolkit/scaffold/template/tests/__init__.py.tmpl similarity index 100% rename from .ci/unit_tests/python/__init_.py rename to Python_Engine/Python/src/python_toolkit/scaffold/template/tests/__init__.py.tmpl diff --git a/Python_Engine/Python/src/python_toolkit/scaffold/template/tests/conftest.py.tmpl b/Python_Engine/Python/src/python_toolkit/scaffold/template/tests/conftest.py.tmpl new file mode 100644 index 00000000..40fd7b0e --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/scaffold/template/tests/conftest.py.tmpl @@ -0,0 +1,4 @@ +import os + +# Never write usage analytics to the real BHoM log folder from tests. +os.environ.setdefault("DISABLE_BHOM_ANALYTICS", "1") diff --git a/Python_Engine/Python/src/python_toolkit/scaffold/template/tests/test_example.py.tmpl b/Python_Engine/Python/src/python_toolkit/scaffold/template/tests/test_example.py.tmpl new file mode 100644 index 00000000..5fd6091d --- /dev/null +++ b/Python_Engine/Python/src/python_toolkit/scaffold/template/tests/test_example.py.tmpl @@ -0,0 +1,8 @@ +import pytest + +from $package.example import add + + +@pytest.mark.parametrize(("a", "b", "expected"), [(1, 2, 3), (-1, 1, 0), (0.5, 0.25, 0.75)]) +def test_add(a, b, expected): + assert add(a, b) == expected diff --git a/Python_Engine/Python/src/python_toolkit/units/__init__.py b/Python_Engine/Python/src/python_toolkit/units/__init__.py index 87a074dd..c9c4f401 100644 --- a/Python_Engine/Python/src/python_toolkit/units/__init__.py +++ b/Python_Engine/Python/src/python_toolkit/units/__init__.py @@ -1,15 +1,10 @@ -from .area import AreaUnit +"""Unit enumerations with conversion between units of the same quantity.""" + +from .area import AreaUnit from .energy import EnergyUnit from .length import LengthUnit from .power import PowerUnit from .speed import SpeedUnit from .temperature import TemperatureUnit -__all__ = [ - "AreaUnit", - "EnergyUnit", - "LengthUnit", - "PowerUnit", - "SpeedUnit", - "TemperatureUnit" -] \ No newline at end of file +__all__ = ["AreaUnit", "EnergyUnit", "LengthUnit", "PowerUnit", "SpeedUnit", "TemperatureUnit"] diff --git a/Python_Engine/Python/src/python_toolkit/units/area.py b/Python_Engine/Python/src/python_toolkit/units/area.py index e59b6e98..3f471939 100644 --- a/Python_Engine/Python/src/python_toolkit/units/area.py +++ b/Python_Engine/Python/src/python_toolkit/units/area.py @@ -1,13 +1,27 @@ -from enum import Enum +"""Units of area.""" + +from enum import Enum + class AreaUnit(Enum): - """Each unit value is a tuple in the format: - (display name, lambda to metres squared, lambda from metres squared) + """Units of area. + + Each unit value is a tuple in the format: (display name, lambda to metres squared, lambda from metres squared). """ + ft2 = ("Feet Squared", lambda ft2: ft2 * (3.048e-1**2), lambda m2: m2 / (3.048e-1**2)) km2 = ("Kilometres Squared", lambda km2: km2 * (1e3**2), lambda m2: m2 / (1e3**2)) m2 = ("Metres Squared", lambda m2: m2, lambda m2: m2) mi2 = ("Miles Squared", lambda mi2: mi2 * (1.609344e3**2), lambda m2: m2 / (1.609344e3**2)) - def convert(self, value: float, to_unit: "AreaUnit"): + def convert(self, value: float, to_unit: "AreaUnit") -> float: + """Convert a value in this unit to another unit. + + Args: + value: The value, in this unit. + to_unit: The unit to convert to. + + Returns: + The value in `to_unit`. + """ return to_unit.value[2](self.value[1](value)) diff --git a/Python_Engine/Python/src/python_toolkit/units/energy.py b/Python_Engine/Python/src/python_toolkit/units/energy.py index f1fad47d..8508fe1a 100644 --- a/Python_Engine/Python/src/python_toolkit/units/energy.py +++ b/Python_Engine/Python/src/python_toolkit/units/energy.py @@ -1,9 +1,14 @@ -from enum import Enum +"""Units of energy.""" + +from enum import Enum + class EnergyUnit(Enum): - """Each unit value is a tuple in the format: - (display name, lambda to joules, lambda from joules) + """Units of energy. + + Each unit value is a tuple in the format: (display name, lambda to joules, lambda from joules). """ + BTU = ("British Thermal Unit", lambda btu: btu * 1.05505585262e3, lambda j: j / 1.05505585262e3) J = ("Joule", lambda j: j, lambda j: j) kBTU = ("Kilo British Thermal Unit", lambda kbtu: kbtu * 1.05505585262e6, lambda j: j / 1.05505585262e6) @@ -14,5 +19,14 @@ class EnergyUnit(Enum): MWh = ("Megawatt Hour", lambda mwh: mwh * 3.6e9, lambda j: j / 3.6e9) Wh = ("Watt Hour", lambda wh: wh * 3.6e3, lambda j: j / 3.6e3) - def convert(self, value: float, to_unit: "EnergyUnit"): + def convert(self, value: float, to_unit: "EnergyUnit") -> float: + """Convert a value in this unit to another unit. + + Args: + value: The value, in this unit. + to_unit: The unit to convert to. + + Returns: + The value in `to_unit`. + """ return to_unit.value[2](self.value[1](value)) diff --git a/Python_Engine/Python/src/python_toolkit/units/length.py b/Python_Engine/Python/src/python_toolkit/units/length.py index f8ef8688..53889464 100644 --- a/Python_Engine/Python/src/python_toolkit/units/length.py +++ b/Python_Engine/Python/src/python_toolkit/units/length.py @@ -1,9 +1,14 @@ -from enum import Enum +"""Units of length.""" + +from enum import Enum + class LengthUnit(Enum): - """Each unit value is a tuple in the format: - (display name, lambda to metres, lambda from metres) + """Units of length. + + Each unit value is a tuple in the format: (display name, lambda to metres, lambda from metres). """ + cm = ("Centimetre", lambda cm: cm * 1e-2, lambda m: m / 1e-2) ft = ("Foot", lambda ft: ft * 3.048e-1, lambda m: m / 3.048e-1) In = ("Inch", lambda In: In * 2.54e-2, lambda m: m / 2.54e-2) @@ -13,5 +18,14 @@ class LengthUnit(Enum): mm = ("Millimetre", lambda mm: mm * 1e-3, lambda m: m / 1e-3) yd = ("Yard", lambda yd: yd * 9.144e-1, lambda m: m / 9.144e-1) - def convert(self, value: float, to_unit: "LengthUnit"): + def convert(self, value: float, to_unit: "LengthUnit") -> float: + """Convert a value in this unit to another unit. + + Args: + value: The value, in this unit. + to_unit: The unit to convert to. + + Returns: + The value in `to_unit`. + """ return to_unit.value[2](self.value[1](value)) diff --git a/Python_Engine/Python/src/python_toolkit/units/power.py b/Python_Engine/Python/src/python_toolkit/units/power.py index 386a0608..9b5fcb0d 100644 --- a/Python_Engine/Python/src/python_toolkit/units/power.py +++ b/Python_Engine/Python/src/python_toolkit/units/power.py @@ -1,15 +1,41 @@ -from enum import Enum +"""Units of power.""" + +from enum import Enum + class PowerUnit(Enum): - """Each unit value is a tuple in the format: - (display name, lambda to watts, lambda from watts) + """Units of power. + + Each unit value is a tuple in the format: (display name, lambda to watts, lambda from watts). """ - BTU_h = ("British Thermal Unit Per Hour", lambda btu_h: btu_h * (1.05505585262e3 / 3600), lambda w: w / (1.05505585262e3 / 3600)) + + BTU_h = ( + "British Thermal Unit Per Hour", + lambda btu_h: btu_h * (1.05505585262e3 / 3600), + lambda w: w / (1.05505585262e3 / 3600), + ) W = ("Watt", lambda w: w, lambda w: w) - kBTU_h = ("Kilo British Thermal Unit Per Hour", lambda kbtu_h: kbtu_h * 1.05505585262e6, lambda w: w / 1.05505585262e6) + kBTU_h = ( + "Kilo British Thermal Unit Per Hour", + lambda kbtu_h: kbtu_h * 1.05505585262e6, + lambda w: w / 1.05505585262e6, + ) kW = ("Kilowatt", lambda kw: kw * 1e3, lambda w: w / 1e3) - MBTU_h = ("Mega British Thermal Unit Per Hour", lambda mbtu_h: mbtu_h * (1.05505585262e9 / 3600), lambda w: w / (1.05505585262e9 / 3600)) + MBTU_h = ( + "Mega British Thermal Unit Per Hour", + lambda mbtu_h: mbtu_h * (1.05505585262e9 / 3600), + lambda w: w / (1.05505585262e9 / 3600), + ) MW = ("Megawatt", lambda mj: mj * 1e6, lambda j: j / 1e6) - def convert(self, value: float, to_unit: "PowerUnit"): + def convert(self, value: float, to_unit: "PowerUnit") -> float: + """Convert a value in this unit to another unit. + + Args: + value: The value, in this unit. + to_unit: The unit to convert to. + + Returns: + The value in `to_unit`. + """ return to_unit.value[2](self.value[1](value)) diff --git a/Python_Engine/Python/src/python_toolkit/units/speed.py b/Python_Engine/Python/src/python_toolkit/units/speed.py index f1ca7bdb..db68f2c8 100644 --- a/Python_Engine/Python/src/python_toolkit/units/speed.py +++ b/Python_Engine/Python/src/python_toolkit/units/speed.py @@ -1,13 +1,27 @@ -from enum import Enum +"""Units of speed.""" + +from enum import Enum + class SpeedUnit(Enum): - """Each unit value is a tuple in the format: - (display name, lambda to metres per secomd, lambda from metres per second) + """Units of speed. + + Each unit value is a tuple in the format: (display name, lambda to metres per secomd, lambda from metres per second). """ + m_s = ("Metres Per Second", lambda m_s: m_s, lambda m_s: m_s) km_h = ("Kilometres Per Hour", lambda km_h: km_h * (1e3 / 3.6e3), lambda m_s: m_s / (1e3 / 3.6e3)) mi_h = ("Miles Per Hour", lambda mi_h: mi_h * (1.609344e3 / 3.6e3), lambda m_s: m_s / (1.609344e3 / 3.6e3)) ft_s = ("Feet Per Second", lambda ft_s: ft_s * 3.048e-1, lambda m_s: m_s / 3.048e-1) - def convert(self, value: float, to_unit: "SpeedUnit"): + def convert(self, value: float, to_unit: "SpeedUnit") -> float: + """Convert a value in this unit to another unit. + + Args: + value: The value, in this unit. + to_unit: The unit to convert to. + + Returns: + The value in `to_unit`. + """ return to_unit.value[2](self.value[1](value)) diff --git a/Python_Engine/Python/src/python_toolkit/units/temperature.py b/Python_Engine/Python/src/python_toolkit/units/temperature.py index efca3378..225bc20e 100644 --- a/Python_Engine/Python/src/python_toolkit/units/temperature.py +++ b/Python_Engine/Python/src/python_toolkit/units/temperature.py @@ -1,13 +1,27 @@ -from enum import Enum +"""Units of temperature.""" + +from enum import Enum + class TemperatureUnit(Enum): - """Each unit value is a tuple in the format: - (display name, lambda to kelvin, lambda from kelvin) + """Units of temperature. + + Each unit value is a tuple in the format: (display name, lambda to kelvin, lambda from kelvin). """ + C = ("Celcius", lambda c: c + 273.15, lambda k: k - 273.15) K = ("Kelvin", lambda k: k, lambda k: k) - F = ("Fahrenheit", lambda f: (f + 459.67) * (5/9), lambda k: (k / (5/9)) - 459.67) - R = ("Rankine", lambda r: r * (5/9), lambda k: k / (5/9)) + F = ("Fahrenheit", lambda f: (f + 459.67) * (5 / 9), lambda k: (k / (5 / 9)) - 459.67) + R = ("Rankine", lambda r: r * (5 / 9), lambda k: k / (5 / 9)) + + def convert(self, value: float, to_unit: "TemperatureUnit") -> float: + """Convert a value in this unit to another unit. + + Args: + value: The value, in this unit. + to_unit: The unit to convert to. - def convert(self, value: float, to_unit: "TemperatureUnit"): - return to_unit.value[2]((self.value[1](value))) + Returns: + The value in `to_unit`. + """ + return to_unit.value[2](self.value[1](value)) diff --git a/Python_Engine/Python/tests/__init__.py b/Python_Engine/Python/tests/__init__.py index d4a8a8e4..961daabf 100644 --- a/Python_Engine/Python/tests/__init__.py +++ b/Python_Engine/Python/tests/__init__.py @@ -1,17 +1,4 @@ -from pathlib import Path -import pandas as pd -import matplotlib as mpl - +"""Tests for python_toolkit.""" # identifier for all downstream processes BASE_IDENTIFIER = "PythonBHoM_pytest" - -def get_timeseries(): - df = pd.read_csv(Path(__file__).parent / "assets" / "example_timeseries.csv", index_col="Timestamp") - df = df.set_index(pd.to_datetime(df.index)) - return pd.Series(df["Value"], index=df.index) - -TIMESERIES_COLLECTION = get_timeseries() - -#use 'agg' for testing plot methods, as tkinter occasionally throws strange errors (missing component/library when component isn't missing) when the default backend is used only when using pytest -mpl.use("agg") \ No newline at end of file diff --git a/Python_Engine/Python/tests/_data.py b/Python_Engine/Python/tests/_data.py new file mode 100644 index 00000000..89da0fea --- /dev/null +++ b/Python_Engine/Python/tests/_data.py @@ -0,0 +1,16 @@ +"""Shared test data (requires the "plot" extra).""" + +from pathlib import Path + +import pandas as pd + +ASSETS_DIRECTORY = Path(__file__).parent / "assets" + + +def get_timeseries() -> pd.Series: + df = pd.read_csv(ASSETS_DIRECTORY / "example_timeseries.csv", index_col="Timestamp") + df = df.set_index(pd.to_datetime(df.index)) + return pd.Series(df["Value"], index=df.index) + + +TIMESERIES_COLLECTION = get_timeseries() diff --git a/Python_Engine/Python/tests/conftest.py b/Python_Engine/Python/tests/conftest.py new file mode 100644 index 00000000..525b0b0c --- /dev/null +++ b/Python_Engine/Python/tests/conftest.py @@ -0,0 +1,20 @@ +"""Pytest configuration shared by all tests.""" + +import os + +import pytest + +# Use a non-interactive matplotlib backend for every test. This must happen before any test module imports +# matplotlib.pyplot, otherwise the Tk backend may be selected and fail on machines without a usable Tcl/Tk. +os.environ.setdefault("MPLBACKEND", "Agg") + +# Never write usage analytics to the real BHoM log folder from tests. +os.environ.setdefault("DISABLE_BHOM_ANALYTICS", "1") + + +@pytest.fixture +def usage_tracker(tmp_path): + """A usage tracker writing to a temporary folder, not registered to flush at exit.""" + from python_toolkit.bhom.analytics import UsageTracker + + return UsageTracker(log_folder=tmp_path, register_atexit=False) diff --git a/Python_Engine/Python/tests/test_analytics.py b/Python_Engine/Python/tests/test_analytics.py new file mode 100644 index 00000000..bb40b200 --- /dev/null +++ b/Python_Engine/Python/tests/test_analytics.py @@ -0,0 +1,242 @@ +import json +import subprocess +import sys +import textwrap +import time + +import pytest + +from python_toolkit.bhom import analytics +from python_toolkit.bhom.analytics import ( + MAX_ERRORS_PER_METHOD, + SCHEMA, + UsageLogEntry, + bhom_analytics, + load_logs_from_file, + summarise_usage_logs, +) + + +@pytest.fixture +def tracked(monkeypatch, usage_tracker): + """Route the decorator to an isolated tracker.""" + monkeypatch.setattr(analytics, "_TRACKER", usage_tracker) + return usage_tracker + + +def _read_records(folder): + return [json.loads(line) for file in folder.glob("Usage_*.jsonl") for line in file.read_text().splitlines()] + + +def test_calls_are_aggregated_into_one_record(tracked): + @bhom_analytics(disable=False) + def add(a, b): + return a + b + + for i in range(100): + assert add(i, 1) == i + 1 + + records = tracked.snapshot() + assert len(records) == 1 + record = records[0] + assert record["schema"] == SCHEMA + assert record["count"] == 100 + assert record["error_count"] == 0 + assert record["method"].endswith("add") + assert record["module"] == __name__ + assert record["toolkit"] == __name__.split(".")[0] + assert record["max_seconds"] <= record["total_seconds"] + + +def test_project_number_separates_records(tracked): + project = {"id": "A"} + + @bhom_analytics(project_id=lambda: project["id"], disable=False) + def method(): + return None + + method() + project["id"] = "B" + method() + method() + + counts = {r["project"]: r["count"] for r in tracked.snapshot()} + assert counts == {"A": 1, "B": 2} + + +def test_errors_are_recorded_deduplicated_and_capped(tracked): + @bhom_analytics(disable=False) + def fail(i): + raise ValueError(f"bad value {i % (MAX_ERRORS_PER_METHOD + 5)}") + + for i in range(1000): + with pytest.raises(ValueError): + fail(i) + + (record,) = tracked.snapshot() + assert record["count"] == 1000 + assert record["error_count"] == 1000 + assert len(record["errors"]) == MAX_ERRORS_PER_METHOD + assert all(error["type"] == "ValueError" for error in record["errors"]) + assert sum(error["count"] for error in record["errors"]) < 1000 # overflowed errors are counted but not detailed + + +def test_exceptions_propagate_unchanged(tracked): + error = KeyError("missing") + + @bhom_analytics(disable=False) + def fail(): + raise error + + with pytest.raises(KeyError) as raised: + fail() + assert raised.value is error + + +def test_flush_writes_jsonl_and_resets(tracked, tmp_path): + @bhom_analytics(disable=False) + def method(): + return 1 + + method() + method() + tracked.flush() + + records = _read_records(tmp_path) + assert len(records) == 1 + assert records[0]["count"] == 2 + assert tracked.snapshot() == [] + + tracked.flush() # nothing pending: nothing written + assert len(_read_records(tmp_path)) == 1 + + +def test_flush_respects_daily_size_cap(tracked, tmp_path, monkeypatch): + monkeypatch.setattr(analytics, "MAX_DAILY_LOG_BYTES", 1) + + @bhom_analytics(disable=False) + def method(): + return 1 + + method() + tracked.flush() # first write succeeds (file is empty) + method() + tracked.flush() # file is now over the cap: skipped + + assert len(_read_records(tmp_path)) == 1 + + +def test_flush_triggered_by_call_threshold(tracked, tmp_path, monkeypatch): + monkeypatch.setattr(analytics, "FLUSH_CALL_THRESHOLD", 10) + + @bhom_analytics(disable=False) + def method(): + return 1 + + for _ in range(25): + method() + + assert sum(r["count"] for r in _read_records(tmp_path)) == 20 + assert tracked.snapshot()[0]["count"] == 5 + + +def test_flush_never_raises(tracked, tmp_path): + @bhom_analytics(disable=False) + def method(): + return 1 + + method() + blocker = tmp_path / "not_a_folder" + blocker.write_text("") + tracked.log_folder = blocker # mkdir will fail + tracked.flush() + + +def test_disabled_returns_function_unwrapped(): + def method(): + return 1 + + assert bhom_analytics(disable=True)(method) is method + + +def test_flushes_at_process_exit(tmp_path): + script = textwrap.dedent( + f""" + from python_toolkit.bhom import analytics + analytics._TRACKER.log_folder = __import__("pathlib").Path({str(tmp_path)!r}) + + @analytics.bhom_analytics(disable=False) + def method(): + return 1 + + for _ in range(3): + method() + """ + ) + env = {k: v for k, v in __import__("os").environ.items() if k != "DISABLE_BHOM_ANALYTICS"} + subprocess.run([sys.executable, "-c", script], check=True, env=env) + + (record,) = _read_records(tmp_path) + assert record["count"] == 3 + + +def test_overhead_is_small(tracked): + """A tracked call should add only a few microseconds, even when called many times.""" + + def method(): + return None + + wrapped = bhom_analytics(disable=False)(method) + calls = 100_000 + + start = time.perf_counter() + for _ in range(calls): + method() + baseline = time.perf_counter() - start + + start = time.perf_counter() + for _ in range(calls): + wrapped() + tracked_time = time.perf_counter() - start + + per_call_overhead = (tracked_time - baseline) / calls + assert per_call_overhead < 20e-6, f"{per_call_overhead * 1e6:.1f} microseconds per call" + + # periodic flushes (every FLUSH_CALL_THRESHOLD calls) are included in the timing above; nothing is lost + tracked.flush() + records = _read_records(tracked.log_folder) + assert sum(r["count"] for r in records) == calls + assert len(records) == calls // analytics.FLUSH_CALL_THRESHOLD + + +def test_load_and_summarise_mixed_formats(tracked, tmp_path): + @bhom_analytics(disable=False) + def method(): + return 1 + + method() + method() + tracked.flush() + log_file = next(tmp_path.glob("Usage_*.jsonl")) + + legacy = UsageLogEntry(CallerName="legacy_method", Time={"$date": 1_700_000_000_000}) + legacy_json = json.dumps(legacy.__dict__, default=str) + with log_file.open("a", encoding="utf-8") as f: + f.write(legacy_json + "\n") + + entries = load_logs_from_file(log_file) + assert sum(isinstance(e, dict) for e in entries) == 1 + assert sum(isinstance(e, UsageLogEntry) for e in entries) == 1 + + summary = {s["CallerName"]: s for s in summarise_usage_logs(entries)} + assert summary["legacy_method"]["TotalNbCalls"] == 1 + (current,) = [s for name, s in summary.items() if name.endswith("method") and name != "legacy_method"] + assert current["TotalNbCalls"] == 2 + assert current["_t"] == "BH.oM.BHoMAnalytics.UsageEntry" + + +def test_usage_log_entry_defaults_are_independent(): + a, b = UsageLogEntry(), UsageLogEntry() + a.Errors.append("x") + assert b.Errors == [] + assert a.BHoM_Guid != b.BHoM_Guid diff --git a/Python_Engine/Python/tests/test_bhom_serialiser.py b/Python_Engine/Python/tests/test_bhom_serialiser.py index 0d1385f3..0f50ddb9 100644 --- a/Python_Engine/Python/tests/test_bhom_serialiser.py +++ b/Python_Engine/Python/tests/test_bhom_serialiser.py @@ -1,95 +1,133 @@ -from python_toolkit.bhom.bhom_object import convert_pascal_to_camel, convert_camel_to_pascal, BHoMObject, IObject, BHoMJSONDecoder, BHoMJSONEncoder -import uuid import json +import uuid -SERIALISED_BHOM_OBJECT = '{ "_t" : "BH.oM.Adapter.FileSettings", "FileName" : "test.txt", "Directory" : "path/to/file", "BHoM_Guid" : "f428e614-bda1-4228-882e-21d0f318a322", "Name" : "", "_bhomVersion" : "9.2" }' #TODO: use the BHoM serialiser to make a BHoMObject json string, and use that here. -DESERIALISED_BHOM_OBJECT = BHoMObject(_t = "BH.oM.Adapter.FileSettings", bhom_guid = uuid.UUID("f428e614-bda1-4228-882e-21d0f318a322"), file_name = "test.txt", directory = "path/to/file", _bhom_version = "9.2") #TODO: make equivalent BHoMObject here identical to the one above. +from python_toolkit.bhom.bhom_object import ( + BHoMJSONDecoder, + BHoMJSONEncoder, + BHoMObject, + IObject, + convert_camel_to_pascal, + convert_pascal_to_camel, +) + +SERIALISED_BHOM_OBJECT = '{ "_t" : "BH.oM.Adapter.FileSettings", "FileName" : "test.txt", "Directory" : "path/to/file", "BHoM_Guid" : "f428e614-bda1-4228-882e-21d0f318a322", "Name" : "", "_bhomVersion" : "9.2" }' # TODO: use the BHoM serialiser to make a BHoMObject json string, and use that here. +DESERIALISED_BHOM_OBJECT = BHoMObject( + _t="BH.oM.Adapter.FileSettings", + bhom_guid=uuid.UUID("f428e614-bda1-4228-882e-21d0f318a322"), + file_name="test.txt", + directory="path/to/file", + _bhom_version="9.2", +) # TODO: make equivalent BHoMObject here identical to the one above. SERIALISED_IOBJECT = '{ "_t" : "BH.oM.Geometry.Point", "X" : 0.10000000000000001, "Y" : 0.10000000000000001, "Z" : 0.10000000000000001, "_bhomVersion" : "9.2" }' -DESERIALISED_IOBJECT = IObject(_t = "BH.oM.Geometry.Point", x = 0.10000000000000001, y = 0.10000000000000001, z = 0.10000000000000001, _bhom_version = "9.2") +DESERIALISED_IOBJECT = IObject( + _t="BH.oM.Geometry.Point", x=0.10000000000000001, y=0.10000000000000001, z=0.10000000000000001, _bhom_version="9.2" +) + def test_case_convert(): - """Test that the camel and pascal converters are working correctly by using expected outputs and a round trip both ways.""" - #TODO: find edge cases within bhom to see if round trip converters work properly. - #arrange - test_pascal_str = "ThisIsAPascalCaseString" - test_camel_str = "this_is_a_camel_case_string" - expected_pascal_out = "this_is_a_pascal_case_string" - expected_camel_out = "ThisIsACamelCaseString" - - #act - pascal_out = convert_pascal_to_camel(test_pascal_str) - pascal_round_trip = convert_camel_to_pascal(pascal_out) - - camel_out = convert_camel_to_pascal(test_camel_str) - camel_round_trip = convert_pascal_to_camel(camel_out) - - #assert - assert pascal_out == expected_pascal_out, f"pascal conversion got '{pascal_out}' but expected '{expected_pascal_out}'." - assert camel_out == expected_camel_out, f"camel conversion got '{camel_out}' but expected '{expected_camel_out}'." - assert pascal_round_trip == test_pascal_str, f"pascal round trip got '{pascal_round_trip}' but expected '{test_pascal_str}'." - assert camel_round_trip == test_camel_str, f"camel round trip got '{camel_round_trip}' but expected '{test_camel_str}'." + """Test that the camel and pascal converters are working correctly by using expected outputs and a round trip both ways.""" + # TODO: find edge cases within bhom to see if round trip converters work properly. + # arrange + test_pascal_str = "ThisIsAPascalCaseString" + test_camel_str = "this_is_a_camel_case_string" + expected_pascal_out = "this_is_a_pascal_case_string" + expected_camel_out = "ThisIsACamelCaseString" + + # act + pascal_out = convert_pascal_to_camel(test_pascal_str) + pascal_round_trip = convert_camel_to_pascal(pascal_out) + + camel_out = convert_camel_to_pascal(test_camel_str) + camel_round_trip = convert_pascal_to_camel(camel_out) + + # assert + assert pascal_out == expected_pascal_out, ( + f"pascal conversion got '{pascal_out}' but expected '{expected_pascal_out}'." + ) + assert camel_out == expected_camel_out, f"camel conversion got '{camel_out}' but expected '{expected_camel_out}'." + assert pascal_round_trip == test_pascal_str, ( + f"pascal round trip got '{pascal_round_trip}' but expected '{test_pascal_str}'." + ) + assert camel_round_trip == test_camel_str, ( + f"camel round trip got '{camel_round_trip}' but expected '{test_camel_str}'." + ) + def test_serialise_bhom_object(): - """Test that bhom objects serialise correctly to a format that the c# bhom serialiser accepts as valid, and with the correct property case.""" - #act - serialised = json.dumps(DESERIALISED_BHOM_OBJECT, cls=BHoMJSONEncoder) - serialised_bhom_object_to_json = DESERIALISED_BHOM_OBJECT.to_json() - round_trip = BHoMObject.from_json(serialised) + """Test that bhom objects serialise correctly to a format that the c# bhom serialiser accepts as valid, and with the correct property case.""" + # act + serialised = json.dumps(DESERIALISED_BHOM_OBJECT, cls=BHoMJSONEncoder) + serialised_bhom_object_to_json = DESERIALISED_BHOM_OBJECT.to_json() + round_trip = BHoMObject.from_json(serialised) + + # assert + assert serialised == serialised_bhom_object_to_json, ( + "Direct serialisation to json differed to BHoMObject to_json method." + ) + assert round_trip == DESERIALISED_BHOM_OBJECT, ( + "BHoMObject round trip failed for serialisation -> deserialisation." + ) # this is the only direction the round trip can be tested without directly inspecting each dictionary entry, as it is not guaranteed that the other direction will produce identical order for json strings. - #assert - assert serialised == serialised_bhom_object_to_json, f"Direct serialisation to json differed to BHoMObject to_json method." - assert round_trip == DESERIALISED_BHOM_OBJECT, f"BHoMObject round trip failed for serialisation -> deserialisation." #this is the only direction the round trip can be tested without directly inspecting each dictionary entry, as it is not guaranteed that the other direction will produce identical order for json strings. def test_serialise_iobject(): - #act - serialised = json.dumps(DESERIALISED_IOBJECT, cls=BHoMJSONEncoder) - serialised_iobject_to_json = DESERIALISED_IOBJECT.to_json() - round_trip = IObject.from_json(serialised) + # act + serialised = json.dumps(DESERIALISED_IOBJECT, cls=BHoMJSONEncoder) + serialised_iobject_to_json = DESERIALISED_IOBJECT.to_json() + round_trip = IObject.from_json(serialised) + + # assert + assert serialised == serialised_iobject_to_json, "Direct serialisation to json differed to IObject to_json method." + assert round_trip == DESERIALISED_IOBJECT, ( + "IObject round trip failed for serialisation -> deserialisation." + ) # this is the only direction the round trip can be tested without directly inspecting each dictionary entry, as it is not guaranteed that the other direction will produce identical order for json strings. - #assert - assert serialised == serialised_iobject_to_json, f"Direct serialisation to json differed to IObject to_json method." - assert round_trip == DESERIALISED_IOBJECT, f"IObject round trip failed for serialisation -> deserialisation." #this is the only direction the round trip can be tested without directly inspecting each dictionary entry, as it is not guaranteed that the other direction will produce identical order for json strings. def test_deserialise_bhom_object(): - """Test that bhom objects deserialise correctly with no errors with expected properties with correct case.""" - #act - obj = json.loads(SERIALISED_BHOM_OBJECT, cls=BHoMJSONDecoder) - obj_bhom_object_from_json = BHoMObject.from_json(SERIALISED_BHOM_OBJECT) + """Test that bhom objects deserialise correctly with no errors with expected properties with correct case.""" + # act + obj = json.loads(SERIALISED_BHOM_OBJECT, cls=BHoMJSONDecoder) + obj_bhom_object_from_json = BHoMObject.from_json(SERIALISED_BHOM_OBJECT) + + # assert + assert isinstance(obj, BHoMObject), "JSON decoded an object of the wrong type" + assert obj == DESERIALISED_BHOM_OBJECT, ( + f"Actual deserialised object ({obj}) was not identical to expected deserialised object ({DESERIALISED_BHOM_OBJECT})." + ) + assert obj_bhom_object_from_json == obj, "Direct deserialisation from json differed to BHoMObject from_json method." - #assert - assert isinstance(obj, BHoMObject), "JSON decoded an object of the wrong type" - assert obj == DESERIALISED_BHOM_OBJECT, f"Actual deserialised object ({obj}) was not identical to expected deserialised object ({DESERIALISED_BHOM_OBJECT})." - assert obj_bhom_object_from_json == obj, f"Direct deserialisation from json differed to BHoMObject from_json method." def test_deserialise_iobject(): - """Test that bhom objects deserialise correctly with no errors with expected properties with correct case.""" - #act - obj = json.loads(SERIALISED_IOBJECT, cls=BHoMJSONDecoder) - obj_iobject_from_json = IObject.from_json(SERIALISED_IOBJECT) + """Test that bhom objects deserialise correctly with no errors with expected properties with correct case.""" + # act + obj = json.loads(SERIALISED_IOBJECT, cls=BHoMJSONDecoder) + obj_iobject_from_json = IObject.from_json(SERIALISED_IOBJECT) + + # assert + assert isinstance(obj, IObject), "JSON decoded an object of the wrong type" + assert obj == DESERIALISED_IOBJECT, ( + f"Actual deserialised object ({obj}) was not identical to expected deserialised object ({DESERIALISED_IOBJECT})." + ) + assert obj_iobject_from_json == obj, "Direct deserialisation from json differed to IObject from_json method." - #assert - assert isinstance(obj, IObject), "JSON decoded an object of the wrong type" - assert obj == DESERIALISED_IOBJECT, f"Actual deserialised object ({obj}) was not identical to expected deserialised object ({DESERIALISED_IOBJECT})." - assert obj_iobject_from_json == obj, f"Direct deserialisation from json differed to IObject from_json method." def test_subclass(): - #arrange - class TestSubClass(BHoMObject): - _t: str = "BH.oM.Base.CustomObject" - some_other_data: str - - def __init__(self, some_other_data, **kwargs): - self.some_other_data = some_other_data - _t = kwargs.pop("_t", self._t) - super().__init__(_t, **kwargs) - - #act - test_object = TestSubClass("this is some test data") - test_object_json = test_object.to_json() - test_object_round_trip = TestSubClass.from_json(test_object_json) - - #assert - assert test_object == test_object_round_trip - assert test_object.some_other_data == "this is some test data" - assert test_object._t == "BH.oM.Base.CustomObject" \ No newline at end of file + # arrange + class TestSubClass(BHoMObject): + _t: str = "BH.oM.Base.CustomObject" + some_other_data: str + + def __init__(self, some_other_data, **kwargs): + self.some_other_data = some_other_data + _t = kwargs.pop("_t", self._t) + super().__init__(_t, **kwargs) + + # act + test_object = TestSubClass("this is some test data") + test_object_json = test_object.to_json() + test_object_round_trip = TestSubClass.from_json(test_object_json) + + # assert + assert test_object == test_object_round_trip + assert test_object.some_other_data == "this is some test data" + assert test_object._t == "BH.oM.Base.CustomObject" diff --git a/Python_Engine/Python/tests/test_bhom_tkinter_ui.py b/Python_Engine/Python/tests/test_bhom_tkinter_ui.py index 9379fe3a..9e4ae981 100644 --- a/Python_Engine/Python/tests/test_bhom_tkinter_ui.py +++ b/Python_Engine/Python/tests/test_bhom_tkinter_ui.py @@ -1,463 +1,468 @@ from __future__ import annotations +import tkinter as tk from datetime import date from pathlib import Path import matplotlib.pyplot as plt -import tkinter as tk +import pytest +from python_toolkit.bhom_tkinter.bhom_base_child_window import BHoMBaseChildWindow from python_toolkit.bhom_tkinter.bhom_base_window import BHoMBaseWindow from python_toolkit.bhom_tkinter.widgets import ( - Button, - CalendarWidget, - CheckboxSelection, - CmapSelector, - ColourPicker, - DropDownSelection, - FigureContainer, - Label, - MultiBoxSelection, - PackingOptions, - PathSelector, - RadioSelection, - ScrollableListBox, - SearchableListBox, - ValidatedEntryBox, + Button, + CalendarWidget, + CheckboxSelection, + CmapSelector, + ColourPicker, + DropDownSelection, + FigureContainer, + Label, + MultiBoxSelection, + PackingOptions, + PathSelector, + RadioSelection, + ScrollableListBox, + SearchableListBox, + ValidatedEntryBox, ) from python_toolkit.bhom_tkinter.windows import ( - DirectoryFileSelector, - LandingPage, - ProcessingWindow, - WarningBox, + DirectoryFileSelector, + LandingPage, + ProcessingWindow, + WarningBox, ) -from python_toolkit.bhom_tkinter.bhom_base_child_window import BHoMBaseChildWindow from python_toolkit.bhom_tkinter.windows.modal_window import BHoMModalWindow +# Tk interpreter start-up with the uv-managed (python-build-standalone) Python intermittently fails to read init.tcl +# on Windows ("couldn't read file ... No error"). Retry only that error, so genuine UI failures still fail. +pytestmark = [pytest.mark.ui, pytest.mark.flaky(reruns=2, only_rerun=["TclError"])] + def _demo_callback(*_args, **_kwargs): - return None + return None def _show_brief(window: BHoMBaseWindow, milliseconds: int = 900) -> None: - window.after(milliseconds, window.destroy_root) - window.mainloop() + window.after(milliseconds, window.destroy_root) + window.mainloop() def run_widget_gallery(auto_close_ms: int | None = None) -> None: - root = BHoMBaseWindow( - title="BHoM Tkinter Widget Gallery", - min_width=1200, - min_height=900, - show_submit=False, - show_close=True, - close_text="Close Gallery", - ) - - parent = root.content_frame - alignments = ["left", "center", "right"] - - Label( - parent, - text="Label widget (left)", - item_title="Label", - helper_text="Basic BHoM Label wrapper", - alignment=alignments[0], - build_options=PackingOptions(fill="x", pady=6), - ).build() - - Button( - parent, - text="Button widget", - command=_demo_callback, - item_title="Button", - helper_text="Simple action button", - alignment=alignments[1], - build_options=PackingOptions(fill="x", pady=6), - ).build() - - ValidatedEntryBox( - parent, - item_title="ValidatedEntryBox", - helper_text="Integer 0..100", - value_type=int, - min_value=0, - max_value=100, - alignment=alignments[2], - build_options=PackingOptions(fill="x", pady=6), - ).build() - - DropDownSelection( - parent, - item_title="DropDownSelection", - helper_text="Pick an option", - options=["A", "B", "C"], - default="B", - alignment=alignments[0], - build_options=PackingOptions(fill="x", pady=6), - ).build() - - RadioSelection( - parent, - item_title="RadioSelection", - helper_text="Single select", - fields=["Red", "Green", "Blue"], - orient="horizontal", - max_per_line=3, - alignment=alignments[1], - build_options=PackingOptions(fill="x", pady=6), - ).build() - - CheckboxSelection( - parent, - item_title="CheckboxSelection", - helper_text="Multi select", - fields=["One", "Two", "Three", "Four"], - defaults=["Two"], - max_per_line=4, - alignment=alignments[2], - build_options=PackingOptions(fill="x", pady=6), - ).build() - - MultiBoxSelection( - parent, - item_title="MultiBoxSelection", - helper_text="Legacy alias variant", - fields=["North", "South", "East", "West"], - orient="horizontal", - max_per_line=2, - alignment=alignments[0], - build_options=PackingOptions(fill="x", pady=6), - ).build() - - ScrollableListBox( - parent, - item_title="ScrollableListBox", - helper_text="List with selection controls", - items=[f"Item {i}" for i in range(1, 13)], - height=5, - show_selection_controls=True, - alignment=alignments[1], - build_options=PackingOptions(fill="x", pady=6), - ).build() - - SearchableListBox( - parent, - item_title="SearchableListBox", - helper_text="Type to filter; selections are kept while filtering", - items=[f"{city}_TRY.epw" for city in ["London", "Birmingham", "Manchester", "Glasgow", "Belfast", "Cardiff"]], - height=4, - show_selection_controls=True, - alignment=alignments[2], - build_options=PackingOptions(fill="x", pady=6), - ).build() - - PathSelector( - parent, - item_title="PathSelector", - helper_text="Browse file path", - button_text="Browse", - mode="file", - alignment=alignments[2], - build_options=PackingOptions(fill="x", pady=6), - ).build() - - ColourPicker( - parent, - item_title="ColourPicker", - helper_text="Pick a colour", - default_colour="#4A90E2", - alignment=alignments[0], - build_options=PackingOptions(fill="x", pady=6), - ).build() - - CalendarWidget( - parent, - item_title="CalendarWidget", - helper_text="Date picker", - def_year=date.today().year, - def_month=date.today().month, - def_day=max(1, min(date.today().day, 28)), - show_year_selector=True, - alignment=alignments[1], - build_options=PackingOptions(fill="x", pady=6), - ).build() - - figure_container = FigureContainer( - parent, - item_title="FigureContainer", - helper_text="Embedded matplotlib figure", - alignment=alignments[2], - build_options=PackingOptions(fill="x", pady=6), - ) - figure_container.build() - figure, axis = plt.subplots(figsize=(3.2, 1.2)) - axis.plot([0, 1, 2, 3], [1, 3, 2, 4]) - axis.set_title("Sample") - figure_container.embed_figure(figure) - - CmapSelector( - parent, - item_title="CmapSelector", - helper_text="Colormap preview", - cmap_set="continuous", - alignment=alignments[0], - build_options=PackingOptions(fill="x", pady=6), - ).build() - - if auto_close_ms is not None: - root.after(auto_close_ms, root.destroy_root) - root.mainloop() + root = BHoMBaseWindow( + title="BHoM Tkinter Widget Gallery", + min_width=1200, + min_height=900, + show_submit=False, + show_close=True, + close_text="Close Gallery", + ) + + parent = root.content_frame + alignments = ["left", "center", "right"] + + Label( + parent, + text="Label widget (left)", + item_title="Label", + helper_text="Basic BHoM Label wrapper", + alignment=alignments[0], + build_options=PackingOptions(fill="x", pady=6), + ).build() + + Button( + parent, + text="Button widget", + command=_demo_callback, + item_title="Button", + helper_text="Simple action button", + alignment=alignments[1], + build_options=PackingOptions(fill="x", pady=6), + ).build() + + ValidatedEntryBox( + parent, + item_title="ValidatedEntryBox", + helper_text="Integer 0..100", + value_type=int, + min_value=0, + max_value=100, + alignment=alignments[2], + build_options=PackingOptions(fill="x", pady=6), + ).build() + + DropDownSelection( + parent, + item_title="DropDownSelection", + helper_text="Pick an option", + options=["A", "B", "C"], + default="B", + alignment=alignments[0], + build_options=PackingOptions(fill="x", pady=6), + ).build() + + RadioSelection( + parent, + item_title="RadioSelection", + helper_text="Single select", + fields=["Red", "Green", "Blue"], + orient="horizontal", + max_per_line=3, + alignment=alignments[1], + build_options=PackingOptions(fill="x", pady=6), + ).build() + + CheckboxSelection( + parent, + item_title="CheckboxSelection", + helper_text="Multi select", + fields=["One", "Two", "Three", "Four"], + defaults=["Two"], + max_per_line=4, + alignment=alignments[2], + build_options=PackingOptions(fill="x", pady=6), + ).build() + + MultiBoxSelection( + parent, + item_title="MultiBoxSelection", + helper_text="Legacy alias variant", + fields=["North", "South", "East", "West"], + orient="horizontal", + max_per_line=2, + alignment=alignments[0], + build_options=PackingOptions(fill="x", pady=6), + ).build() + + ScrollableListBox( + parent, + item_title="ScrollableListBox", + helper_text="List with selection controls", + items=[f"Item {i}" for i in range(1, 13)], + height=5, + show_selection_controls=True, + alignment=alignments[1], + build_options=PackingOptions(fill="x", pady=6), + ).build() + + SearchableListBox( + parent, + item_title="SearchableListBox", + helper_text="Type to filter; selections are kept while filtering", + items=[f"{city}_TRY.epw" for city in ["London", "Birmingham", "Manchester", "Glasgow", "Belfast", "Cardiff"]], + height=4, + show_selection_controls=True, + alignment=alignments[2], + build_options=PackingOptions(fill="x", pady=6), + ).build() + + PathSelector( + parent, + item_title="PathSelector", + helper_text="Browse file path", + button_text="Browse", + mode="file", + alignment=alignments[2], + build_options=PackingOptions(fill="x", pady=6), + ).build() + + ColourPicker( + parent, + item_title="ColourPicker", + helper_text="Pick a colour", + default_colour="#4A90E2", + alignment=alignments[0], + build_options=PackingOptions(fill="x", pady=6), + ).build() + + CalendarWidget( + parent, + item_title="CalendarWidget", + helper_text="Date picker", + def_year=date.today().year, + def_month=date.today().month, + def_day=max(1, min(date.today().day, 28)), + show_year_selector=True, + alignment=alignments[1], + build_options=PackingOptions(fill="x", pady=6), + ).build() + + figure_container = FigureContainer( + parent, + item_title="FigureContainer", + helper_text="Embedded matplotlib figure", + alignment=alignments[2], + build_options=PackingOptions(fill="x", pady=6), + ) + figure_container.build() + figure, axis = plt.subplots(figsize=(3.2, 1.2)) + axis.plot([0, 1, 2, 3], [1, 3, 2, 4]) + axis.set_title("Sample") + figure_container.embed_figure(figure) + + CmapSelector( + parent, + item_title="CmapSelector", + helper_text="Colormap preview", + cmap_set="continuous", + alignment=alignments[0], + build_options=PackingOptions(fill="x", pady=6), + ).build() + + if auto_close_ms is not None: + root.after(auto_close_ms, root.destroy_root) + root.mainloop() def run_predefined_windows_demo() -> None: - landing = LandingPage( - title="LandingPage demo", - header="Landing page", - message="Smoke-checking predefined windows.", - sub_title="This window auto-closes.", - show_submit=False, - ) - landing.add_custom_button("No-op Action", _demo_callback) - _show_brief(landing) - - warning = WarningBox( - title="WarningBox demo", - warnings=["Sample warning message"], - errors=["Sample error message"], - infos=["Sample informational message"], - ) - _show_brief(warning) - - processing = ProcessingWindow(title="ProcessingWindow demo", message="Working...") - processing.start() - processing.after(900, processing.stop) - processing.mainloop() - - selector = DirectoryFileSelector( - directory=Path(__file__).resolve().parent, - file_types=[".py"], - selection_label="test files", - ) - _show_brief(selector) + landing = LandingPage( + title="LandingPage demo", + header="Landing page", + message="Smoke-checking predefined windows.", + sub_title="This window auto-closes.", + show_submit=False, + ) + landing.add_custom_button("No-op Action", _demo_callback) + _show_brief(landing) + + warning = WarningBox( + title="WarningBox demo", + warnings=["Sample warning message"], + errors=["Sample error message"], + infos=["Sample informational message"], + ) + _show_brief(warning) + + processing = ProcessingWindow(title="ProcessingWindow demo", message="Working...") + processing.start() + processing.after(900, processing.stop) + processing.mainloop() + + selector = DirectoryFileSelector( + directory=Path(__file__).resolve().parent, + file_types=[".py"], + selection_label="test files", + ) + _show_brief(selector) if __name__ == "__main__": - run_widget_gallery() - run_predefined_windows_demo() + run_widget_gallery() + run_predefined_windows_demo() def test_widget_validation(): - """Ensure widget validation logic returns expected results.""" - # Integer field valid range - root = BHoMBaseWindow(title="Validation test") - parent = root.content_frame - - int_box = ValidatedEntryBox( - parent, - value_type=int, - min_value=0, - max_value=100, - required=True, - ) - int_box.build() - - int_box.set(50) - ok, msg, sev = int_box.validate() - assert ok is True and msg is None - - int_box.set(150) - ok, msg, sev = int_box.validate() - assert ok is False and sev == "error" - - # Required field empty - int_box.set("") - ok, msg, sev = int_box.validate() - assert ok is False and msg == "Required" - - # Non-required empty is valid - opt_box = ValidatedEntryBox(parent, value_type=str, required=False) - opt_box.build() - opt_box.set("") - ok, msg, sev = opt_box.validate() - assert ok is True - - # Custom validator overriding - def fail_validator(_v): - return False, "Custom failed" - - custom_box = ValidatedEntryBox(parent, value_type=str, required=True, custom_validator=fail_validator) - custom_box.build() - custom_box.set("abc") - ok, msg, sev = custom_box.validate() - assert ok is False and msg == "Custom failed" + """Ensure widget validation logic returns expected results.""" + # Integer field valid range + root = BHoMBaseWindow(title="Validation test") + parent = root.content_frame + + int_box = ValidatedEntryBox( + parent, + value_type=int, + min_value=0, + max_value=100, + required=True, + ) + int_box.build() + + int_box.set(50) + ok, msg, sev = int_box.validate() + assert ok is True and msg is None + + int_box.set(150) + ok, msg, sev = int_box.validate() + assert ok is False and sev == "error" + + # Required field empty + int_box.set("") + ok, msg, sev = int_box.validate() + assert ok is False and msg == "Required" + + # Non-required empty is valid + opt_box = ValidatedEntryBox(parent, value_type=str, required=False) + opt_box.build() + opt_box.set("") + ok, msg, sev = opt_box.validate() + assert ok is True + + # Custom validator overriding + def fail_validator(_v): + return False, "Custom failed" + + custom_box = ValidatedEntryBox(parent, value_type=str, required=True, custom_validator=fail_validator) + custom_box.build() + custom_box.set("abc") + ok, msg, sev = custom_box.validate() + assert ok is False and msg == "Custom failed" def test_rebuild(): - """Verify that rebuild() re-places widgets and reflects mutations to self.widgets.""" - root = BHoMBaseWindow(title="Rebuild test") - parent = root.content_frame + """Verify that rebuild() re-places widgets and reflects mutations to self.widgets.""" + root = BHoMBaseWindow(title="Rebuild test") + parent = root.content_frame - label_a = Label(parent, text="Widget A", build_options=PackingOptions(fill="x")) - label_b = Label(parent, text="Widget B", build_options=PackingOptions(fill="x")) + label_a = Label(parent, text="Widget A", build_options=PackingOptions(fill="x")) + label_b = Label(parent, text="Widget B", build_options=PackingOptions(fill="x")) - root.widgets.extend([label_a, label_b]) - root.build() + root.widgets.extend([label_a, label_b]) + root.build() - # Both widgets should be managed after build - managed_after_build = [ - c for c in parent.winfo_children() if c.winfo_manager() - ] - assert len(managed_after_build) == 2 + # Both widgets should be managed after build + managed_after_build = [c for c in parent.winfo_children() if c.winfo_manager()] + assert len(managed_after_build) == 2 - # Add a third widget and rebuild - label_c = Label(parent, text="Widget C", build_options=PackingOptions(fill="x")) - root.widgets.append(label_c) - root.rebuild() + # Add a third widget and rebuild + label_c = Label(parent, text="Widget C", build_options=PackingOptions(fill="x")) + root.widgets.append(label_c) + root.rebuild() - managed_after_rebuild = [ - c for c in parent.winfo_children() if c.winfo_manager() - ] - assert len(managed_after_rebuild) == 3 + managed_after_rebuild = [c for c in parent.winfo_children() if c.winfo_manager()] + assert len(managed_after_rebuild) == 3 - # Remove a widget and rebuild — it should no longer be managed - root.widgets.remove(label_a) - root.rebuild() + # Remove a widget and rebuild — it should no longer be managed + root.widgets.remove(label_a) + root.rebuild() - managed_after_remove = [ - c for c in parent.winfo_children() if c.winfo_manager() - ] - assert len(managed_after_remove) == 2 - assert label_a not in [w for w in root.widgets] + managed_after_remove = [c for c in parent.winfo_children() if c.winfo_manager()] + assert len(managed_after_remove) == 2 + assert label_a not in list(root.widgets) - root.destroy_root() + root.destroy_root() def test_modal_window_is_themed_toplevel(): - """Modal windows should be themed Toplevels, not tk.Tk roots.""" - host = BHoMBaseWindow(title="Modal host", show_submit=False, show_close=False) - host.withdraw() - - modal = BHoMModalWindow( - host, - title="Modal test", - width=420, - height=260, - show_close=True, - ) - assert isinstance(modal, tk.Toplevel) - assert isinstance(modal, BHoMBaseChildWindow) - assert hasattr(modal, "content_frame") - assert not isinstance(modal, BHoMBaseWindow) - - Label( - modal.content_frame, - text="Modal body", - build_options=PackingOptions(anchor="w"), - ).build() - modal.update_idletasks() - assert modal.winfo_exists() - - modal.close() - host.destroy_root() + """Modal windows should be themed Toplevels, not tk.Tk roots.""" + host = BHoMBaseWindow(title="Modal host", show_submit=False, show_close=False) + host.withdraw() + + modal = BHoMModalWindow( + host, + title="Modal test", + width=420, + height=260, + show_close=True, + ) + assert isinstance(modal, tk.Toplevel) + assert isinstance(modal, BHoMBaseChildWindow) + assert hasattr(modal, "content_frame") + assert not isinstance(modal, BHoMBaseWindow) + + Label( + modal.content_frame, + text="Modal body", + build_options=PackingOptions(anchor="w"), + ).build() + modal.update_idletasks() + assert modal.winfo_exists() + + modal.close() + host.destroy_root() def test_searchable_list_box(): - """Selections survive filtering; select/deselect all act on visible items; single mode keeps one item.""" - root = BHoMBaseWindow(title="SearchableListBox test") - changes = [] - items = ["London_TRY.epw", "London_DSY1.epw", "Gibraltar_TRY.epw", "Belfast_TRY.epw"] - - box = SearchableListBox(root.content_frame, items=items, show_selection_controls=True, - on_change=lambda value: changes.append(list(value))) - box.build() - - # Build a selection across two searches - box.set_filter("gib") - assert box.get_visible() == ["Gibraltar_TRY.epw"] - box.list_box.set_selections(["Gibraltar_TRY.epw"]) - box._on_list_change() - box.set_filter("belfast") - box.list_box.set_selections(["Belfast_TRY.epw"]) - box._on_list_change() - assert box.get() == ["Gibraltar_TRY.epw", "Belfast_TRY.epw"] - assert changes[-1] == ["Gibraltar_TRY.epw", "Belfast_TRY.epw"] - - # Clearing the filter shows the hidden selections as selected - box.clear_filter() - assert box.get_visible() == items - assert box.list_box.get_selection() == ["Gibraltar_TRY.epw", "Belfast_TRY.epw"] - - # Select/deselect all only affect visible items - box.set_filter("london") - box.select_all() - assert box.get() == items - box.deselect_all() - assert box.get() == ["Gibraltar_TRY.epw", "Belfast_TRY.epw"] - - # set / clear / set_options - box.set(["London_TRY.epw"]) - assert box.get() == ["London_TRY.epw"] - box.clear() - assert box.get() == [] - box.set(items) - box.set_options(["London_TRY.epw", "Cardiff_TRY.epw"]) - assert box.get() == ["London_TRY.epw"] - - # keep_hidden_selection=False drops selections the filter hides - strict = SearchableListBox(root.content_frame, items=items, keep_hidden_selection=False) - strict.build() - strict.set(["London_TRY.epw", "Belfast_TRY.epw"]) - strict.set_filter("london") - assert strict.get() == ["London_TRY.epw"] - - # Single select keeps at most one item, and a hidden choice survives filtering - single = SearchableListBox(root.content_frame, items=items, selectmode=tk.SINGLE) - single.build() - single.set(items) - assert single.get() == ["London_TRY.epw"] - single.set_filter("gib") - assert single.get() == ["London_TRY.epw"] - single.list_box.set_selections(["Gibraltar_TRY.epw"]) - single._on_list_change() - assert single.get() == ["Gibraltar_TRY.epw"] - - root.destroy_root() + """Selections survive filtering; select/deselect all act on visible items; single mode keeps one item.""" + root = BHoMBaseWindow(title="SearchableListBox test") + changes = [] + items = ["London_TRY.epw", "London_DSY1.epw", "Gibraltar_TRY.epw", "Belfast_TRY.epw"] + + box = SearchableListBox( + root.content_frame, + items=items, + show_selection_controls=True, + on_change=lambda value: changes.append(list(value)), + ) + box.build() + + # Build a selection across two searches + box.set_filter("gib") + assert box.get_visible() == ["Gibraltar_TRY.epw"] + box.list_box.set_selections(["Gibraltar_TRY.epw"]) + box._on_list_change() + box.set_filter("belfast") + box.list_box.set_selections(["Belfast_TRY.epw"]) + box._on_list_change() + assert box.get() == ["Gibraltar_TRY.epw", "Belfast_TRY.epw"] + assert changes[-1] == ["Gibraltar_TRY.epw", "Belfast_TRY.epw"] + + # Clearing the filter shows the hidden selections as selected + box.clear_filter() + assert box.get_visible() == items + assert box.list_box.get_selection() == ["Gibraltar_TRY.epw", "Belfast_TRY.epw"] + + # Select/deselect all only affect visible items + box.set_filter("london") + box.select_all() + assert box.get() == items + box.deselect_all() + assert box.get() == ["Gibraltar_TRY.epw", "Belfast_TRY.epw"] + + # set / clear / set_options + box.set(["London_TRY.epw"]) + assert box.get() == ["London_TRY.epw"] + box.clear() + assert box.get() == [] + box.set(items) + box.set_options(["London_TRY.epw", "Cardiff_TRY.epw"]) + assert box.get() == ["London_TRY.epw"] + + # keep_hidden_selection=False drops selections the filter hides + strict = SearchableListBox(root.content_frame, items=items, keep_hidden_selection=False) + strict.build() + strict.set(["London_TRY.epw", "Belfast_TRY.epw"]) + strict.set_filter("london") + assert strict.get() == ["London_TRY.epw"] + + # Single select keeps at most one item, and a hidden choice survives filtering + single = SearchableListBox(root.content_frame, items=items, selectmode=tk.SINGLE) + single.build() + single.set(items) + assert single.get() == ["London_TRY.epw"] + single.set_filter("gib") + assert single.get() == ["London_TRY.epw"] + single.list_box.set_selections(["Gibraltar_TRY.epw"]) + single._on_list_change() + assert single.get() == ["Gibraltar_TRY.epw"] + + root.destroy_root() def test_searchable_list_box_fuzzy_matching(): - """Default scorer: substrings and typos match, best first; min_score and a custom scorer can be supplied.""" - from functools import partial - from python_toolkit.bhom_tkinter.widgets.searchable_list_box import default_scorer - - assert default_scorer("lon", "London_TRY.epw") is not None - assert default_scorer("birmigham", "Birmingham_TRY.epw") is not None # typo - assert default_scorer("xyzq", "London_TRY.epw") is None - assert default_scorer("london", "LOS-ANGELES-DOWNTOWN.epw") is None - assert default_scorer("birmigham", "Birmingham_TRY.epw", min_score=95) is None # stricter threshold - - root = BHoMBaseWindow(title="SearchableListBox fuzzy test") - items = ["Country_Club.epw", "London_TRY.epw", "Birmingham_TRY.epw", "Gibraltar_TRY.epw"] - - fuzzy = SearchableListBox(root.content_frame, items=items) - fuzzy.build() - fuzzy.set_filter("birmigham") - assert fuzzy.get_visible() == ["Birmingham_TRY.epw"] - fuzzy.set_filter("try") - assert set(fuzzy.get_visible()) == set(items) # "try" is a substring of every item; ties keep original order - fuzzy.set_filter("xyzq") - assert fuzzy.get_visible() == [] - - # min_score is an argument of the scorer - strict = SearchableListBox(root.content_frame, items=items, scorer=partial(default_scorer, min_score=95)) - strict.build() - strict.set_filter("birmigham") - assert strict.get_visible() == [] - - # A custom scorer replaces the default - only_london = SearchableListBox( - root.content_frame, items=items, scorer=lambda query, item: 1.0 if item.startswith("London") else None) - only_london.build() - only_london.set_filter("anything") - assert only_london.get_visible() == ["London_TRY.epw"] - - root.destroy_root() + """Default scorer: substrings and typos match, best first; min_score and a custom scorer can be supplied.""" + from functools import partial + + from python_toolkit.bhom_tkinter.widgets.searchable_list_box import default_scorer + + assert default_scorer("lon", "London_TRY.epw") is not None + assert default_scorer("birmigham", "Birmingham_TRY.epw") is not None # typo + assert default_scorer("xyzq", "London_TRY.epw") is None + assert default_scorer("london", "LOS-ANGELES-DOWNTOWN.epw") is None + assert default_scorer("birmigham", "Birmingham_TRY.epw", min_score=95) is None # stricter threshold + + root = BHoMBaseWindow(title="SearchableListBox fuzzy test") + items = ["Country_Club.epw", "London_TRY.epw", "Birmingham_TRY.epw", "Gibraltar_TRY.epw"] + + fuzzy = SearchableListBox(root.content_frame, items=items) + fuzzy.build() + fuzzy.set_filter("birmigham") + assert fuzzy.get_visible() == ["Birmingham_TRY.epw"] + fuzzy.set_filter("try") + assert set(fuzzy.get_visible()) == set(items) # "try" is a substring of every item; ties keep original order + fuzzy.set_filter("xyzq") + assert fuzzy.get_visible() == [] + + # min_score is an argument of the scorer + strict = SearchableListBox(root.content_frame, items=items, scorer=partial(default_scorer, min_score=95)) + strict.build() + strict.set_filter("birmigham") + assert strict.get_visible() == [] + + # A custom scorer replaces the default + only_london = SearchableListBox( + root.content_frame, items=items, scorer=lambda query, item: 1.0 if item.startswith("London") else None + ) + only_london.build() + only_london.set_filter("anything") + assert only_london.get_visible() == ["London_TRY.epw"] + + root.destroy_root() diff --git a/Python_Engine/Python/tests/test_core.py b/Python_Engine/Python/tests/test_core.py new file mode 100644 index 00000000..ebad2b22 --- /dev/null +++ b/Python_Engine/Python/tests/test_core.py @@ -0,0 +1,73 @@ +import json +import subprocess +import sys + +import pytest + +from python_toolkit._optional import require_extra +from python_toolkit.bhom import BHOM_VERSION +from python_toolkit.bhom.decorators import bhom_wrapper +from python_toolkit.bhom.logging import get_logger +from python_toolkit.bhom.run_wrapped import run_wrapped +from python_toolkit.bhom.util import bson_unix_ticks, bson_unix_ticks_to_datetime + +HEAVY_MODULES = ["clr", "matplotlib", "numpy", "pandas", "plotly"] + + +def test_core_imports_only_the_standard_library(): + """The root package must stay lightweight: importing the core must not pull in optional dependencies.""" + script = ( + "import sys\n" + "import python_toolkit, python_toolkit.bhom.analytics, python_toolkit.bhom.bhom_object\n" + "import python_toolkit.bhom.run_wrapped, python_toolkit.bhom.logging, python_toolkit.units\n" + "import python_toolkit.scaffold\n" + f"print([m for m in {HEAVY_MODULES!r} if m in sys.modules])\n" + ) + result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, check=True) + assert result.stdout.strip() == "[]" + + +def test_require_extra_names_the_extra(): + with pytest.raises(ImportError, match=r"python_toolkit\[plot\]"): + require_extra("plot", "a_module_that_does_not_exist") + + require_extra("plot", "json") # present: no error + + +def test_bhom_version_is_a_version_string(): + assert isinstance(BHOM_VERSION, str) + assert BHOM_VERSION.split(".")[0].isdigit() + + +def test_get_logger_does_not_duplicate_handlers(): + first = get_logger("Some_Toolkit") + second = get_logger("Some_Toolkit") + assert first is second + assert len(first.handlers) == 1 + assert first.name == "Some_Toolkit[console]" + + +def test_bson_ticks_round_trip(): + ticks = bson_unix_ticks(short=True) + assert abs(bson_unix_ticks(bson_unix_ticks_to_datetime(ticks, short=True), short=True) - ticks) <= 1 + + +def test_bson_ticks_default_is_now(): + first = bson_unix_ticks(short=True) + assert bson_unix_ticks(short=True) >= first + + +def test_run_wrapped_round_trip(capsys): + """Methods registered with bhom_callable can be invoked with JSON, as BH.Engine.Python does.""" + payload = json.dumps({"geometry": {"_t": "BH.oM.Geometry.Point", "X": 1.0, "Y": 2.0, "Z": 3.0}}) + + run_wrapped("test", payload) + + result = json.loads(capsys.readouterr().out) + assert result["_t"] == "BH.oM.Geometry.Point" + assert result["X"] == 20 + + +def test_unregistered_method_raises(): + with pytest.raises(NotImplementedError): + bhom_wrapper.get_registered_method("does_not_exist") diff --git a/Python_Engine/Python/tests/test_plot.py b/Python_Engine/Python/tests/test_plot.py index bf94258b..dda0342e 100644 --- a/Python_Engine/Python/tests/test_plot.py +++ b/Python_Engine/Python/tests/test_plot.py @@ -1,7 +1,8 @@ -import matplotlib.pyplot as plt +import matplotlib.pyplot as plt import numpy as np import pandas as pd import pytest + from python_toolkit.plot.diurnal import diurnal, stacked_diurnals from python_toolkit.plot.heatmap import heatmap from python_toolkit.plot.spatial_heatmap import spatial_heatmap @@ -10,12 +11,11 @@ contrasting_colour, create_triangulation, lighten_color, - relative_luminance + relative_luminance, ) -from matplotlib.figure import Figure -from pathlib import Path -from . import TIMESERIES_COLLECTION +from ._data import TIMESERIES_COLLECTION + def test_create_triangulation(): """_""" @@ -35,6 +35,7 @@ def test_create_triangulation(): with pytest.raises(ValueError): create_triangulation(x, y, alpha=0.00001) + def test_relative_luminance(): """_""" assert relative_luminance("#FFFFFF") == pytest.approx(1.0, rel=1e-7) @@ -83,6 +84,7 @@ def test_colormap_sequential(): """_""" assert sum(colormap_sequential("red", "green", "blue")(0.25)) == pytest.approx(1.750003844675125, rel=0.01) + def test_spatial_heatmap(): """_""" x = np.linspace(0, 100, 101) @@ -93,7 +95,8 @@ def test_spatial_heatmap(): assert isinstance(spatial_heatmap([tri], [zz], contours=[0]), plt.Figure) plt.close("all") -#TODO: use a preset collection, or generate one from a year and random values + +# TODO: use a preset collection, or generate one from a year and random values def test_timeseries_diurnal(): """_""" assert isinstance(diurnal(TIMESERIES_COLLECTION), plt.Axes) @@ -137,6 +140,7 @@ def test_timeseries_diurnal(): plt.Figure, ) + def test_heatmap(): """_""" assert isinstance(heatmap(TIMESERIES_COLLECTION), plt.Axes) @@ -187,4 +191,4 @@ def test_heatmap_keeps_last_bins(): np.arange(24, dtype=float), index=pd.date_range("2000-01-01", periods=24, freq="h"), ) - assert _heatmap_cell_count(hourly_one_day) == 24 \ No newline at end of file + assert _heatmap_cell_count(hourly_one_day) == 24 diff --git a/Python_Engine/Python/tests/test_plot_utilities.py b/Python_Engine/Python/tests/test_plot_utilities.py index c6e56d3b..e6d97668 100644 --- a/Python_Engine/Python/tests/test_plot_utilities.py +++ b/Python_Engine/Python/tests/test_plot_utilities.py @@ -1,21 +1,17 @@ -import matplotlib.pyplot as plt -import numpy as np -import pandas as pd -import pytest -from matplotlib.figure import Figure -from pathlib import Path +import matplotlib.pyplot as plt -from python_toolkit.plot.utilities import figure_to_base64, image_to_base64, base64_to_image, figure_to_image +from python_toolkit.plot.utilities import base64_to_image, figure_to_base64, image_to_base64 -def test_figure_round_trip(): + +def test_figure_round_trip(tmp_path): """very simple test to check that base64 serialisation is working""" fig, ax = plt.subplots(1, 1) base64 = figure_to_base64(fig) assert isinstance(base64, str) - path = base64_to_image(base64, image_path = Path("tests/assets/temp.png").resolve()) + path = base64_to_image(base64, image_path=tmp_path / "temp.png") assert path.exists() - + base64_2 = image_to_base64(path) - path.unlink() #make sure to clean up after ourselves - assert base64 == base64_2 \ No newline at end of file + path.unlink() # make sure to clean up after ourselves + assert base64 == base64_2 diff --git a/Python_Engine/Python/tests/test_scaffold.py b/Python_Engine/Python/tests/test_scaffold.py new file mode 100644 index 00000000..e5f02d74 --- /dev/null +++ b/Python_Engine/Python/tests/test_scaffold.py @@ -0,0 +1,135 @@ +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +from python_toolkit.scaffold import ToolkitSpec, create_toolkit, main + +ROOT = Path(__file__).parents[1] +CURRENT_PYTHON = f"{sys.version_info.major}.{sys.version_info.minor}" + + +@pytest.fixture +def extensions(tmp_path): + """A fake BHoM Python extensions directory containing a deployed copy of this root toolkit.""" + directory = tmp_path / "extensions" + deployed = directory / "Python_Toolkit" + deployed.mkdir(parents=True) + for name in ("pyproject.toml", "README.md", "ruff.toml"): + shutil.copy(ROOT / name, deployed / name) + shutil.copytree(ROOT / "src", deployed / "src", ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.egg-info")) + return directory + + +def _spec(tmp_path, extensions, **kwargs): + return ToolkitSpec( + name=kwargs.pop("name", "Demo_Toolkit"), + output=tmp_path / "Demo_Toolkit", + python_version=kwargs.pop("python_version", CURRENT_PYTHON), + extensions_directory=extensions, + **kwargs, + ) + + +def test_creates_expected_files(tmp_path, extensions): + spec = _spec(tmp_path, extensions) + + created = {p.relative_to(spec.output).as_posix() for p in create_toolkit(spec)} + + assert created == { + ".gitignore", + ".python-version", + "README.md", + "pyproject.toml", + "docs/conf.py", + "docs/index.md", + "src/demo_toolkit/__init__.py", + "src/demo_toolkit/example.py", + "tests/__init__.py", + "tests/conftest.py", + "tests/test_example.py", + } + assert (spec.output / ".python-version").read_text().strip() == CURRENT_PYTHON + + +def test_pyproject_wires_dependencies(tmp_path, extensions): + spec = _spec(tmp_path, extensions, depends_on=["Other_Toolkit"], extras=["plot"], python_version="3.11") + create_toolkit(spec) + pyproject = (spec.output / "pyproject.toml").read_text() + + assert 'name = "demo_toolkit"' in pyproject + assert 'version = "999.999.999"' in pyproject + assert 'requires-python = ">=3.11,<3.12"' in pyproject + assert '"python_toolkit[plot]",' in pyproject + assert '"other_toolkit",' in pyproject + root = (extensions / "Python_Toolkit").as_posix() + assert f'python_toolkit = {{ path = "{root}", editable = true }}' in pyproject + assert f'other_toolkit = {{ path = "{(extensions / "Other_Toolkit").as_posix()}", editable = true }}' in pyproject + assert f'extend = "{root}/ruff.toml"' in pyproject + + try: + import tomllib + except ImportError: # Python 3.10 + return + parsed = tomllib.loads(pyproject) + assert parsed["project"]["dependencies"] == ["python_toolkit[plot]", "other_toolkit"] + assert set(parsed["tool"]["uv"]["sources"]) == {"python_toolkit", "other_toolkit"} + + +@pytest.mark.parametrize( + ("kwargs", "message"), + [ + ({"name": "bad name"}, "Invalid toolkit name"), + ({"name": "Python_Toolkit"}, "cannot be used"), + ({"python_version": "3.8"}, "Invalid Python version"), + ({"python_version": "three"}, "Invalid Python version"), + ({"extras": ["nope"]}, "Unknown python_toolkit extras"), + ({"depends_on": ["bad name"]}, "Invalid dependency"), + ], +) +def test_invalid_specs_are_rejected(tmp_path, extensions, kwargs, message): + with pytest.raises(ValueError, match=message): + create_toolkit(_spec(tmp_path, extensions, **kwargs)) + + +def test_refuses_to_overwrite(tmp_path, extensions): + spec = _spec(tmp_path, extensions) + spec.output.mkdir() + (spec.output / "existing.txt").write_text("keep me") + + with pytest.raises(ValueError, match="not empty"): + create_toolkit(spec) + + +def test_cli(tmp_path, extensions, capsys): + output = tmp_path / "Cli_Toolkit" + code = main(["Cli_Toolkit", "--output", str(output), "--python", "3.12", "--extensions-dir", str(extensions)]) + + assert code == 0 + assert (output / "src" / "cli_toolkit" / "example.py").exists() + assert "Next steps" in capsys.readouterr().out + + assert main(["bad name", "--output", str(tmp_path / "x")]) == 2 + + +@pytest.mark.slow +@pytest.mark.skipif(shutil.which("uv") is None, reason="uv is required") +def test_generated_toolkit_installs_lints_and_passes_its_tests(tmp_path, extensions): + """End to end: the generated toolkit resolves the root toolkit, passes its own tests and meets the ruff standard.""" + spec = _spec(tmp_path, extensions) + create_toolkit(spec) + env = {k: v for k, v in os.environ.items() if k not in ("VIRTUAL_ENV", "UV_PROJECT_ENVIRONMENT")} + + def run(*args): + result = subprocess.run(["uv", *args], cwd=spec.output, env=env, capture_output=True, text=True) + assert result.returncode == 0, f"uv {' '.join(args)} failed:\n{result.stdout}\n{result.stderr}" + return result.stdout + + run("sync") + run("run", "pytest", "-q") + run("run", "ruff", "check", ".") + run("run", "ruff", "format", "--check", ".") + assert "demo_toolkit" in run("run", "python", "-c", "import demo_toolkit; print(demo_toolkit.__name__)") diff --git a/Python_Engine/Python_Engine.csproj b/Python_Engine/Python_Engine.csproj index ca4230df..520c1dba 100644 --- a/Python_Engine/Python_Engine.csproj +++ b/Python_Engine/Python_Engine.csproj @@ -9,6 +9,15 @@ BH.Engine.Python 10.0.0.0 ..\Build\ + Debug;Release;Test + + + + true + + $(ProgramData)\BHoM\Extensions\Python\Python_Toolkit + + $(DefaultItemExcludes);Python\.venv\**;Python\**\__pycache__\**;Python\.pytest_cache\**;Python\.ruff_cache\**;Python\docs\_build\**;Python\docs\autoapi\** @@ -35,10 +44,16 @@ False - - + + - - + + + + + + + + diff --git a/Python_Engine/Query/Directory.cs b/Python_Engine/Query/Directory.cs index e81943e2..65e5a1f9 100644 --- a/Python_Engine/Query/Directory.cs +++ b/Python_Engine/Query/Directory.cs @@ -21,7 +21,6 @@ */ using BH.oM.Base.Attributes; -using BH.oM.Python.Enums; using System.ComponentModel; using System.IO; @@ -33,50 +32,32 @@ public static partial class Query [Output("path", "The location where BHoM extensions reside.")] public static string DirectoryExtensions() { - return Path.Combine(System.IO.Directory.GetParent(BH.Engine.Base.Query.BHoMFolder()).FullName, "Extensions"); + return Path.Combine(Directory.GetParent(Base.Query.BHoMFolder()).FullName, "Extensions"); } - [Description("The location where any BHoM-related Python kernels reside.")] - [Output("path", "The location where any BHoM-related Python kernels reside.")] - public static string DirectoryKernels() - { - - string dir = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), "jupyter", "kernels"); - if (!Directory.Exists(dir)) - Directory.CreateDirectory(dir); - return dir; - } + private const string EnvironmentsDirectoryVariable = "BHOM_PYTHON_EXTENSIONS_DIR"; - [Description("The location where any BHoM-related Python code resides.")] - [Output("path", "The location where any BHoM-related Python code resides.")] - public static string DirectoryCode() + [Description("The location where any BHoM-related Python environment (or virtualenv) resides. Defaults to the Extensions/Python folder next to the BHoM installation; set the BHOM_PYTHON_EXTENSIONS_DIR environment variable to override it (e.g. for isolated testing).")] + [Output("path", "The location where any BHoM-related Python environment (or virtualenv) resides.")] + public static string DirectoryEnvironments() { - string dir = Path.Combine(Query.DirectoryExtensions(), "PythonCode"); + string dir = System.Environment.GetEnvironmentVariable(EnvironmentsDirectoryVariable); + if (string.IsNullOrWhiteSpace(dir)) + dir = Path.Combine(DirectoryExtensions(), "Python"); + dir = Path.GetFullPath(dir); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); return dir; } - [Description("The location where any BHoM-related Python environment (or virtualenv) resides.")] - [Output("path", "The location where any BHoM-related Python environment (or virtualenv) resides.")] - public static string DirectoryEnvironments() + [Description("The location where any BHoM-related Python tools reside.")] + [Output("path", "The location where any BHoM-related Python tools reside.")] + public static string DirectoryTools() { - string dir = Path.Combine(Query.DirectoryExtensions(), "PythonEnvironments"); + string dir = Path.Combine(DirectoryEnvironments(), "tools"); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); return dir; } - - [Description("The location where the base Python environment exists.")] - [Input("version", "The python version to get the base environment for.")] - [Output("path", "The location where the base Python environment exists.")] - public static string DirectoryBaseEnvironment(this PythonVersion version) - { - return Path.Combine(Query.DirectoryEnvironments(), Query.ToolkitName(), version.ToString()); - } } } - - - - diff --git a/Python_Engine/Query/EmbeddableURL.cs b/Python_Engine/Query/EmbeddableURL.cs deleted file mode 100644 index 16cdee12..00000000 --- a/Python_Engine/Query/EmbeddableURL.cs +++ /dev/null @@ -1,97 +0,0 @@ -/* - * This file is part of the Buildings and Habitats object Model (BHoM) - * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. - * - * Each contributor holds copyright over their respective contributions. - * The project versioning (Git) records all such contribution source information. - * - * - * The BHoM is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3.0 of the License, or - * (at your option) any later version. - * - * The BHoM is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this code. If not, see . - */ - -using BH.oM.Python.Enums; -using BH.oM.Base.Attributes; -using System.Collections.Generic; -using System.ComponentModel; - -namespace BH.Engine.Python -{ - public static partial class Query - { - [Description("Get the URL for the embeddable package containing the given version of Python.")] - [Input("version", "The version of Python to retrieve the URL.")] - [Output("url", "The url for the matching Python version.")] - public static string EmbeddableURL(this PythonVersion version) - { - // See the PythonVersion enum for why most of these are commented out. - Dictionary versions = new Dictionary() - { - //{ PythonVersion.v3_7_2, "https://www.python.org/ftp/python/3.7.2/python-3.7.2rc1-amd64.exe" }, - /*{ PythonVersion.v3_7_3, "https://www.python.org/ftp/python/3.7.3/python-3.7.3rc1-amd64.exe" }, - { PythonVersion.v3_7_4, "https://www.python.org/ftp/python/3.7.4/python-3.7.4rc2-amd64.exe" }, - { PythonVersion.v3_7_5, "https://www.python.org/ftp/python/3.7.5/python-3.7.5rc1-amd64.exe" }, - { PythonVersion.v3_7_6, "https://www.python.org/ftp/python/3.7.6/python-3.7.6rc1-amd64.exe" }, - { PythonVersion.v3_7_7, "https://www.python.org/ftp/python/3.7.7/python-3.7.7rc1-amd64.exe" }, - { PythonVersion.v3_7_8, "https://www.python.org/ftp/python/3.7.8/python-3.7.8rc1-amd64.exe" },*/ - { PythonVersion.v3_7, "https://www.python.org/ftp/python/3.7.9/python-3.7.9-amd64.exe" }, - /*{ PythonVersion.v3_8_0, "https://www.python.org/ftp/python/3.8.0/python-3.8.0rc1-amd64.exe" }, - { PythonVersion.v3_8_1, "https://www.python.org/ftp/python/3.8.1/python-3.8.1rc1-amd64.exe" }, - { PythonVersion.v3_8_2, "https://www.python.org/ftp/python/3.8.2/python-3.8.2rc2-amd64.exe" }, - { PythonVersion.v3_8_3, "https://www.python.org/ftp/python/3.8.3/python-3.8.3rc1-amd64.exe" }, - { PythonVersion.v3_8_4, "https://www.python.org/ftp/python/3.8.4/python-3.8.4rc1-amd64.exe" }, - { PythonVersion.v3_8_5, "https://www.python.org/ftp/python/3.8.5/python-3.8.5-amd64.exe" }, - { PythonVersion.v3_8_6, "https://www.python.org/ftp/python/3.8.6/python-3.8.6rc1-amd64.exe" }, - { PythonVersion.v3_8_7, "https://www.python.org/ftp/python/3.8.7/python-3.8.7rc1-amd64.exe" }, - { PythonVersion.v3_8_8, "https://www.python.org/ftp/python/3.8.8/python-3.8.8rc1-amd64.exe" },*/ - { PythonVersion.v3_8, "https://www.python.org/ftp/python/3.8.9/python-3.8.9-amd64.exe" }, - /*{ PythonVersion.v3_9_0, "https://www.python.org/ftp/python/3.9.0/python-3.9.0rc2-amd64.exe" }, - { PythonVersion.v3_9_1, "https://www.python.org/ftp/python/3.9.1/python-3.9.1rc1-amd64.exe" }, - { PythonVersion.v3_9_2, "https://www.python.org/ftp/python/3.9.2/python-3.9.2rc1-amd64.exe" }, - { PythonVersion.v3_9_3, "https://www.python.org/ftp/python/3.9.3/python-3.9.3-amd64.exe" }, - { PythonVersion.v3_9_4, "https://www.python.org/ftp/python/3.9.4/python-3.9.4-amd64.exe" }, - { PythonVersion.v3_9_5, "https://www.python.org/ftp/python/3.9.5/python-3.9.5-amd64.exe" }, - { PythonVersion.v3_9_6, "https://www.python.org/ftp/python/3.9.6/python-3.9.6-amd64.exe" }, - { PythonVersion.v3_9_7, "https://www.python.org/ftp/python/3.9.7/python-3.9.7-amd64.exe" }, - { PythonVersion.v3_9_8, "https://www.python.org/ftp/python/3.9.8/python-3.9.8-amd64.exe" }, - { PythonVersion.v3_9_9, "https://www.python.org/ftp/python/3.9.9/python-3.9.9-amd64.exe" },*/ - { PythonVersion.v3_9, "https://www.python.org/ftp/python/3.9.10/python-3.9.10-amd64.exe" }, - /*{ PythonVersion.v3_10_0, "https://www.python.org/ftp/python/3.10.0/python-3.10.0rc2-amd64.exe" }, - { PythonVersion.v3_10_1, "https://www.python.org/ftp/python/3.10.1/python-3.10.1-amd64.exe" }, - { PythonVersion.v3_10_2, "https://www.python.org/ftp/python/3.10.2/python-3.10.2-amd64.exe" }, - { PythonVersion.v3_10_3, "https://www.python.org/ftp/python/3.10.3/python-3.10.3-amd64.exe" }, - { PythonVersion.v3_10_4, "https://www.python.org/ftp/python/3.10.4/python-3.10.4-amd64.exe" }, - { PythonVersion.v3_10_5, "https://www.python.org/ftp/python/3.10.5/python-3.10.5-amd64.exe" }, - { PythonVersion.v3_10_6, "https://www.python.org/ftp/python/3.10.6/python-3.10.6-amd64.exe" }, - { PythonVersion.v3_10_7, "https://www.python.org/ftp/python/3.10.7/python-3.10.7-amd64.exe" }, - { PythonVersion.v3_10_8, "https://www.python.org/ftp/python/3.10.8/python-3.10.8-amd64.exe" }, - { PythonVersion.v3_10_9, "https://www.python.org/ftp/python/3.10.9/python-3.10.9-amd64.exe" }, - { PythonVersion.v3_10_10, "https://www.python.org/ftp/python/3.10.10/python-3.10.10-amd64.exe" },*/ - { PythonVersion.v3_10, "https://www.python.org/ftp/python/3.10.11/python-3.10.11-amd64.exe" }, - /*{ PythonVersion.v3_11_0, "https://www.python.org/ftp/python/3.11.0/python-3.11.0rc2-amd64.exe" }, - { PythonVersion.v3_11_1, "https://www.python.org/ftp/python/3.11.1/python-3.11.1-amd64.exe" }, - { PythonVersion.v3_11_2, "https://www.python.org/ftp/python/3.11.2/python-3.11.2-amd64.exe" }, - { PythonVersion.v3_11_3, "https://www.python.org/ftp/python/3.11.3/python-3.11.3-amd64.exe" },*/ - { PythonVersion.v3_11, "https://www.python.org/ftp/python/3.11.4/python-3.11.4-amd64.exe" }, - { PythonVersion.v3_12, "https://www.python.org/ftp/python/3.12.3/python-3.12.3-amd64.exe" }, - { PythonVersion.v3_13, "https://www.python.org/ftp/python/3.13.12/python-3.13.12-amd64.exe" }, - }; - - return versions[version]; - } - } -} - - - - diff --git a/Python_Engine/Query/IsValidEnvironmentName.cs b/Python_Engine/Query/IsValidEnvironmentName.cs deleted file mode 100644 index 16625a65..00000000 --- a/Python_Engine/Query/IsValidEnvironmentName.cs +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This file is part of the Buildings and Habitats object Model (BHoM) - * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. - * - * Each contributor holds copyright over their respective contributions. - * The project versioning (Git) records all such contribution source information. - * - * - * The BHoM is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3.0 of the License, or - * (at your option) any later version. - * - * The BHoM is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this code. If not, see . - */ - -using BH.oM.Python.Enums; -using BH.oM.Python; -using BH.oM.Base.Attributes; - -using System.ComponentModel; -using System.IO; -using System.Linq; -using System; -using System.Collections.Generic; - -namespace BH.Engine.Python -{ - public static partial class Query - { - [Description("Check whether a string is valid as BHoM Python Environment name.")] - [Input("name", "The name given to the BHoM Python Environment.")] - [Output("valid", "True if valid, False if not.")] - public static bool IsValidEnvironmentName(string name) - { - List invalidChars = new List() { ' ' }; - invalidChars.AddRange(Path.GetInvalidPathChars().ToList()); - invalidChars.AddRange(Path.GetInvalidFileNameChars().ToList()); - if (name.Any(x => invalidChars.Contains(x))) - { - return false; - } - return true; - } - } -} - - - - diff --git a/Python_Engine/Query/ToolkitName.cs b/Python_Engine/Query/ToolkitName.cs index c0088f6b..e8e3ba38 100644 --- a/Python_Engine/Query/ToolkitName.cs +++ b/Python_Engine/Query/ToolkitName.cs @@ -32,7 +32,7 @@ public static partial class Query [Output("name", "The name of this toolkit.")] public static string ToolkitName() { - return "Python_Toolkit"; + return "python_toolkit"; } } } diff --git a/Python_Engine/Query/UVExecutable.cs b/Python_Engine/Query/UVExecutable.cs new file mode 100644 index 00000000..c0507302 --- /dev/null +++ b/Python_Engine/Query/UVExecutable.cs @@ -0,0 +1,70 @@ +/* + * This file is part of the Buildings and Habitats object Model (BHoM) + * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. + * + * Each contributor holds copyright over their respective contributions. + * The project versioning (Git) records all such contribution source information. + * + * + * The BHoM is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3.0 of the License, or + * (at your option) any later version. + * + * The BHoM is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this code. If not, see . + */ + +using BH.oM.Base.Attributes; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; + +namespace BH.Engine.Python +{ + public static partial class Query + { + [Description("The BHoM-managed UV executable. UV installations on PATH are not used.")] + [Output("executable", "The path to uv.exe in the BHoM tools directory.")] + public static string UVExecutable() + { + return Path.Combine(DirectoryTools(), "uv.exe"); + } + + [Description("The version of UV that BHoM installs and expects. Pinning this keeps environment creation reproducible across machines.")] + [Output("version", "The pinned UV version.")] + public static string UVVersion() + { + return "0.13.10"; + } + + [Description("Environment variables applied to every BHoM-managed UV call. These keep UV-managed Python interpreters, the package cache and UV tools inside the BHoM tools directory, so environments work for every user on the machine and RemoveUV removes everything. Variables already set in the current process are respected and not overridden.")] + [Output("variables", "The environment variables to apply when running UV.")] + public static Dictionary UVEnvironmentVariables() + { + string tools = DirectoryTools(); + Dictionary defaults = new Dictionary + { + { "UV_PYTHON_INSTALL_DIR", Path.Combine(tools, "python") }, + { "UV_CACHE_DIR", Path.Combine(tools, "cache") }, + { "UV_TOOL_DIR", Path.Combine(tools, "uvtools") }, + { "UV_TOOL_BIN_DIR", Path.Combine(tools, "uvtools", "bin") }, + { "UV_NO_MODIFY_PATH", "1" }, + { "UV_PYTHON_PREFERENCE", "managed" }, + }; + + Dictionary result = new Dictionary(); + foreach (KeyValuePair variable in defaults) + { + if (string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable(variable.Key))) + result[variable.Key] = variable.Value; + } + return result; + } + } +} diff --git a/Python_Engine/Query/Version.cs b/Python_Engine/Query/Version.cs index 7e2db22d..89d86359 100644 --- a/Python_Engine/Query/Version.cs +++ b/Python_Engine/Query/Version.cs @@ -21,13 +21,9 @@ */ using BH.oM.Base.Attributes; -using BH.oM.Python.Enums; -using System; -using System.Collections.Generic; +using BH.oM.Python; using System.ComponentModel; -using System.Diagnostics; using System.IO; -using System.Linq; namespace BH.Engine.Python { @@ -36,54 +32,27 @@ public static partial class Query [Description("Gets the Python version for the requested Python executable.")] [Input("pythonExecutable", "Path to python.exe.")] [Output("version", "Python version of the requested Python executable.")] - public static PythonVersion Version(string pythonExecutable) + public static string Version(string pythonExecutable) { - if (!File.Exists(pythonExecutable)) + if (!File.Exists(pythonExecutable)) { - return PythonVersion.Undefined; + Base.Compute.RecordError(new FileNotFoundException(), $"No file found at {pythonExecutable}"); + return null; } - Process process = new Process() - { - StartInfo = new ProcessStartInfo() - { - FileName = pythonExecutable, - Arguments = $"--version", - RedirectStandardError = true, - RedirectStandardOutput = true, - UseShellExecute = false, - } - }; - - try - { - string versionString; - using (Process p = Process.Start(process.StartInfo)) - { - string standardError = p.StandardError.ReadToEnd(); - versionString = p.StandardOutput.ReadToEnd().TrimEnd(); - p.WaitForExit(); - if (p.ExitCode != 0) - { - BH.Engine.Base.Compute.RecordError($"Error getting Python version.\n{standardError}"); - return PythonVersion.Undefined; - } - } + var result = Compute.RunCommandStdout(command: $"\"{pythonExecutable}\" --version"); + if (result.Item3 != 0) + return null; - List strings = versionString.Replace("Python ", "").Replace(".", "_").Split('_').ToList(); - strings.RemoveAt(strings.Count - 1); - string enumParseable = "v" + strings.Aggregate((a, b) => $"{a}_{b}"); - - return (PythonVersion)Enum.Parse(typeof(PythonVersion), enumParseable); - } - catch - { - return PythonVersion.Undefined; - } + return result.Item1.Replace("Python ", ""); + } + [Description("Get the Python version for the installed PythonEnvironment.")] + [Input("venv", "The PythonEnvironment.")] + [Output("version", "Python version of the installed PythonEnvironment.")] + public static string Version(this PythonEnvironment venv) + { + return Version(venv.Executable); } } } - - - diff --git a/Python_Engine/Query/VirtualEnvironment.cs b/Python_Engine/Query/VirtualEnvironment.cs index f20f0e19..51e7ba12 100644 --- a/Python_Engine/Query/VirtualEnvironment.cs +++ b/Python_Engine/Query/VirtualEnvironment.cs @@ -20,82 +20,74 @@ * along with this code. If not, see . */ -using BH.oM.Python.Enums; using BH.oM.Python; using BH.oM.Base.Attributes; using System.ComponentModel; using System.IO; -using System.Linq; -using System; -using System.Collections.Generic; namespace BH.Engine.Python { public static partial class Query { - [Description("Check whether a named BHoM Python virtual environment exists.")] - [Input("envName", "The name given to the BHoM Python Environment.")] - [Input("pythonVersion", "The version to check against.")] - [Output("exists", "True if exists, False if not.")] - public static bool VirtualEnvironmentExists(string envName, PythonVersion pythonVersion = PythonVersion.Undefined) + [Description("Get the path to the named Python virtual environment executable.")] + [Input("name", "The name given to the Python Environment.")] + [Output("executable", "The path to the executable.")] + public static string VirtualEnvironmentExecutable(string name) { - string executable = VirtualEnvironmentExecutable(envName); - bool directoryExists = Directory.Exists(VirtualEnvironmentDirectory(envName)); - bool executableExists = File.Exists(executable); - bool kernelExists = Directory.Exists(VirtualEnvironmentKernel(envName)); - bool versionMatches = false; - - if (executableExists) - versionMatches = Version(executable) == pythonVersion; + string exePath = Path.Combine(DirectoryEnvironments(), name, ".venv", "Scripts", "python.exe"); + if (!File.Exists(exePath)) + { + Base.Compute.RecordError($"{exePath} was not found."); + return null; + } - if (pythonVersion == PythonVersion.Undefined) - return directoryExists && executableExists && kernelExists; - - return directoryExists && executableExists && kernelExists && versionMatches; + return exePath; } - [Description("Get the path to the named BHoM Python virtual environment kernel.")] - [Input("envName", "The name given to the BHoM Python Environment.")] - [Output("kernelDirectory", "The path to the kernel directory.")] - public static string VirtualEnvironmentKernel(string envName) + [Description("Check whether a named Python virtual environment exists.")] + [Input("name", "The name given to the Python Environment.")] + [Output("exists", "True if exists, False if not.")] + public static bool VirtualEnvironmentExists(string name) { - return Path.Combine(Query.DirectoryKernels(), envName.ToLower()); - } + string expectedVenvPath = Path.Combine(DirectoryEnvironments(), name, ".venv"); - [Description("Get the path to the named BHoM Python virtual environment executable.")] - [Input("envName", "The name given to the BHoM Python Environment.")] - [Output("executable", "The path to the executable.")] - public static string VirtualEnvironmentExecutable(string envName) - { - return Path.Combine(Query.DirectoryEnvironments(), envName, "Scripts", "python.exe"); - } + if (Directory.Exists(expectedVenvPath) && File.Exists(Path.Combine(expectedVenvPath, "Scripts", "python.exe"))) + return true; - [Description("Get the path to the named BHoM Python virtual environment.")] - [Input("envName", "The name given to the BHoM Python Environment.")] - [Output("directory", "The directory where the virtual environment is located.")] - public static string VirtualEnvironmentDirectory(string envName) - { - return Path.Combine(Query.DirectoryEnvironments(), envName); + return false; } - [Description("Get the named BHoM Python virtual environment.")] - [Input("envName", "The name given to the BHoM Python Environment.")] - [Output("environment", "The BHoM Python Environment.")] - public static PythonEnvironment VirtualEnvironment(string envName) + [Description("Get the named Python virtual environment.")] + [Input("name", "The name given to the Python Environment.")] + [Output("environment", "The Python Environment.")] + public static PythonEnvironment VirtualEnvironment(string name) { - if (!VirtualEnvironmentExists(envName)) + if (!VirtualEnvironmentExists(name)) + { + Base.Compute.RecordError($"{name} was not found in {DirectoryEnvironments()}"); return null; - + } + return new PythonEnvironment() { - Name = envName, - Executable = VirtualEnvironmentExecutable(envName), + Name = name, + Executable = VirtualEnvironmentExecutable(name), }; } - } -} - - + [Description("Get a named Python virtual environment.")] + [Input("name", "The name given to the Python Environment.")] + [Output("directory", "The directory in which the venv resides.")] + public static string VirtualEnvironmentDirectory(string name) + { + if (!VirtualEnvironmentExists(name)) + { + Base.Compute.RecordError($"{name} was not found in {DirectoryEnvironments()}"); + return null; + } + return Path.Combine(DirectoryEnvironments(), name); + } + } +} diff --git a/Python_Toolkit.sln b/Python_Toolkit.sln index 31fdc786..9f41590f 100644 --- a/Python_Toolkit.sln +++ b/Python_Toolkit.sln @@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Python_oM", "Python_oM\Pyth EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Python_Engine", "Python_Engine\Python_Engine.csproj", "{D24A2970-618D-4149-B123-99F406D867D6}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Python_Engine_Test", ".ci\unit_tests\Python_Engine_Test\Python_Engine_Test.csproj", "{E654D8C0-C9A3-C0D9-F687-4A0CA64CA548}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -21,6 +23,10 @@ Global {D24A2970-618D-4149-B123-99F406D867D6}.Debug|Any CPU.Build.0 = Debug|Any CPU {D24A2970-618D-4149-B123-99F406D867D6}.Release|Any CPU.ActiveCfg = Release|Any CPU {D24A2970-618D-4149-B123-99F406D867D6}.Release|Any CPU.Build.0 = Release|Any CPU + {E654D8C0-C9A3-C0D9-F687-4A0CA64CA548}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E654D8C0-C9A3-C0D9-F687-4A0CA64CA548}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E654D8C0-C9A3-C0D9-F687-4A0CA64CA548}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E654D8C0-C9A3-C0D9-F687-4A0CA64CA548}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Python_oM/Enums/PythonVersion.cs b/Python_oM/Enums/PythonVersion.cs deleted file mode 100644 index 301febe1..00000000 --- a/Python_oM/Enums/PythonVersion.cs +++ /dev/null @@ -1,137 +0,0 @@ -/* - * This file is part of the Buildings and Habitats object Model (BHoM) - * Copyright (c) 2015 - 2026, the respective contributors. All rights reserved. - * - * Each contributor holds copyright over their respective contributions. - * The project versioning (Git) records all such contribution source information. - * - * - * The BHoM is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3.0 of the License, or - * (at your option) any later version. - * - * The BHoM is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this code. If not, see . - */ - -using System.ComponentModel; - -namespace BH.oM.Python.Enums -{ - // There are multiple specific versions here that are commented out - When installing, only one specific version (e.g 3.10.x) per minor python version (e.g 3.x) can be installed, and changes between specific versions are usually bug fixes and not breaking. however the specific versions are kept commented for posterity. - public enum PythonVersion - { - [Description("Undefined")] - Undefined, - /*[Description("3.7.0")] - v3_7_0, - [Description("3.7.1")] - v3_7_1, - [Description("3.7.2")] - v3_7_2, - [Description("3.7.3")] - v3_7_3, - [Description("3.7.4")] - v3_7_4, - [Description("3.7.5")] - v3_7_5, - [Description("3.7.6")] - v3_7_6, - [Description("3.7.7")] - v3_7_7, - [Description("3.7.8")] - v3_7_8,*/ - [Description("3.7")] //3.7.9 - v3_7, - /*[Description("3.8.0")] - v3_8_0, - [Description("3.8.1")] - v3_8_1, - [Description("3.8.2")] - v3_8_2, - [Description("3.8.3")] - v3_8_3, - [Description("3.8.4")] - v3_8_4, - [Description("3.8.5")] - v3_8_5, - [Description("3.8.6")] - v3_8_6, - [Description("3.8.7")] - v3_8_7, - [Description("3.8.8")] - v3_8_8,*/ - [Description("3.8")] //3.8.9 - v3_8, - //[Description("3.8.10")] - //v3_8_10, - /*[Description("3.9.0")] - v3_9_0, - [Description("3.9.1")] - v3_9_1, - [Description("3.9.2")] - v3_9_2, - [Description("3.9.3")] - v3_9_3, - [Description("3.9.4")] - v3_9_4, - [Description("3.9.5")] - v3_9_5, - [Description("3.9.6")] - v3_9_6, - [Description("3.9.7")] - v3_9_7, - [Description("3.9.8")] - v3_9_8, - [Description("3.9.9")] - v3_9_9,*/ - [Description("3.9")] //3.9.10 - v3_9, - /*[Description("3.10.0")] - v3_10_0, - [Description("3.10.1")] - v3_10_1, - [Description("3.10.2")] - v3_10_2, - [Description("3.10.3")] - v3_10_3, - [Description("3.10.4")] - v3_10_4, - [Description("3.10.5")] - v3_10_5, - [Description("3.10.6")] - v3_10_6, - [Description("3.10.7")] - v3_10_7, - [Description("3.10.8")] - v3_10_8, - [Description("3.10.9")] - v3_10_9, - [Description("3.10.10")] - v3_10_10,*/ - [Description("3.10")] //3.10.11 - v3_10, - /*[Description("3.11.0")] - v3_11_0, - [Description("3.11.1")] - v3_11_1, - [Description("3.11.2")] - v3_11_2, - [Description("3.11.3")] - v3_11_3,*/ - [Description("3.11")] //3.11.4 - v3_11, - [Description("3.12")] - v3_12, - [Description("3.13")] - v3_13, - } -} - - diff --git a/Python_oM/PythonEnvironment.cs b/Python_oM/PythonEnvironment.cs index 7740cb3f..7f81cb67 100644 --- a/Python_oM/PythonEnvironment.cs +++ b/Python_oM/PythonEnvironment.cs @@ -22,8 +22,6 @@ using BH.oM.Base; -using BH.oM.Python.Enums; -using System.Collections.Generic; using System.ComponentModel; namespace BH.oM.Python @@ -37,8 +35,3 @@ public class PythonEnvironment : IObject public virtual string Executable { get; set; } = string.Empty; } } - - - - - diff --git a/Python_oM/Python_oM.csproj b/Python_oM/Python_oM.csproj index c9a7e568..c036f8aa 100644 --- a/Python_oM/Python_oM.csproj +++ b/Python_oM/Python_oM.csproj @@ -10,6 +10,7 @@ BH.oM.Python 10.0.0.0 ..\Build\ + Debug;Release;Test @@ -20,8 +21,11 @@ - - + + true + + + diff --git a/README.md b/README.md index 7018811d..234fbb84 100644 --- a/README.md +++ b/README.md @@ -1,46 +1,105 @@ [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) -## Install me -To install the Python_Toolkit: -1. Compile: - 1. [BHoM](https://github.com/BHoM/BHoM) - 1. [BHoM_Engine](https://github.com/BHoM/BHoM_Engine) - 1. [BHoM_Adapter](https://github.com/BHoM/BHoM_Adapter) - 1. [BHoM_UI](https://github.com/BHoM/BHoM_UI) - 1. [Rhinoceros_Toolkit](https://github.com/BHoM/Rhinoceros_Toolkit) - 1. [Grasshopper_Toolkit](https://github.com/BHoM/Grasshopper_Toolkit) - 1. Python_Toolkit (this repo) -1. Open a UI of your choice (e.g. Grasshopper) -1. Run the `BH.Engine.Python.Compute.InstallPythonToolkit` component and wait for the installation to finish -1. The installation has succeeded if the install packages include: - - Python 3.7 - - jupyterlab - - matplotlib - - Python_Toolkit -1. Restart your UI or recompute the script - -To check whether all went well you can run the component `BH.Engine.Python.Compute.Import` with an input of a string as `Python_Engine`, -and check that it succeed without errors - -## Installation structure -There are two main events to install the toolkit: -1. Compiling the toolkit. This does two things: - - It builds the dynamic libraries required by .NET and copies them to C:\ProgramData\BHoM\Assemblies - - It packs the python files in the toolkit and copies them to C:\ProgramData\BHoM\Extensions\Python\src -2. Installing the Toolkit from the UI. This is performed by running the `InstallPythonToolkit` method. This will: - - Download Python and install python - - Download and install `pip` - - Install the necessary packages (e.g. `jupyterlab`) - - Install the python bindings of the Python_Toolkit from C:\ProgramData\BHoM\Extensions\Python\src - This contains all the code that is currently developed in the toolkit in python - - -## Building the BHoM and the Toolkits from Source ## -You will need the following to build BHoM: - -- Microsoft Visual Studio 2013 or higher -- Microsoft .NET Framework 4.0 and above (included with Visual Studio 2013) -- Note that there are no software - specific dependencies (only operating system relevant), this is specific: BHoM is a software agnostic object model. +# Python_Toolkit + +The Python_Toolkit manages the Python environments used by BHoM, and provides `python_toolkit`: the root Python +package that every BHoM Python toolkit builds on (logging, usage analytics, BHoM JSON conversion and the +C#-callable wrapper). + +Environments are managed with [uv](https://docs.astral.sh/uv/), driven from C# (`BH.Engine.Python`), so they can be +created, updated, tested and removed from any BHoM UI. + +## How it fits together + +``` +C:\ProgramData\BHoM\Extensions\Python\ +├── tools\ uv.exe (pinned version), plus the Python interpreters and package cache it manages +├── Python_Toolkit\ deployed by building this repository +│ ├── pyproject.toml root package: standard-library core + optional extras +│ ├── ruff.toml the shared formatting/linting standard +│ └── .venv\ created by InstallPythonToolkitVenv +└── _Toolkit\ deployed by building that toolkit + ├── pyproject.toml depends on python_toolkit via [tool.uv.sources] path = "...\Python_Toolkit" + └── .venv\ its own environment, with its own Python version +``` + +- **Every toolkit is a standalone uv project** with its own `.venv` and Python version. Shared code is not copied: + each toolkit lists `python_toolkit` (and any other toolkit it needs) as a dependency, installed from the deployed + folder through a [uv path source](https://docs.astral.sh/uv/concepts/projects/dependencies/#path). This is why the + root package supports every Python from 3.10 and has no required third-party dependencies. +- **Building** a toolkit's `_Engine` project copies its `Python` folder into the folder above, and its DLLs into + `C:\ProgramData\BHoM\Assemblies`. Pass `-p:BHoMSkipDeploy=true` to build without deploying. +- **Creating the environment** (`Compute.VirtualEnvironment(tomlFile)`) stamps the toolkit's version with the BHoM + version, checks that the toolkits it depends on are deployed, runs `uv sync`, and registers a Jupyter kernel. + +## Using it from C# + +| Method | Purpose | +| --- | --- | +| `Compute.InstallUV(run)` | Install the pinned uv (`Query.UVVersion()`) into the tools folder. Called automatically when needed. | +| `Compute.InstallPythonToolkitVenv(run, reload)` | Create or update the `Python_Toolkit` environment. | +| `Compute.VirtualEnvironment(tomlFile, reload)` | Create or update any deployed toolkit's environment from its `pyproject.toml`. | +| `Compute.VirtualEnvironment(version, name, reload)` | Create a bare environment with a given Python version. | +| `Compute.RunPytest(toolkitDirectory or venv, arguments, run)` | Run a toolkit's pytest suite. Returns pass/fail, exit code, output and a JUnit XML report. | +| `Compute.CreateToolkit(name, targetDirectory, pythonVersion, dependencies, extras, run)` | Scaffold a new Python toolkit (see below). | +| `Compute.BuildDocumentation(toolkitDirectory, run)` | Build a toolkit's HTML documentation from its docstrings. | +| `Compute.UpdateBHoMPackages(venv)` | Re-sync an environment with its `pyproject.toml`. | +| `Compute.RunCommandStdout(command, ...)` | Run a command, returning stdout, stderr and the exit code (-1 on timeout). | +| `Compute.RunPythonString(venv, script)` | Run a Python script in an environment and return its output. | +| `Compute.RemoveVirtualEnvironment` / `RemoveJupyterKernel` / `RemoveUV` / `RemoveEverything` | Clean up. Toolkit code is always kept. | + +Methods with side effects take `run = false` by default. When not run, they record a note describing what would +happen. + +uv is only ever run from the BHoM tools folder, never from `PATH`. Its interpreters and cache are kept in that +folder too, so environments work for every user on the machine and `RemoveUV` removes everything uv installed. + +## Creating a new Python toolkit + +From C# (`Compute.CreateToolkit`), from VS Code (the *Python: new toolkit* task), or from a terminal: + +```powershell +cd Python_Engine/Python +uv run bhom-new-toolkit Wind_Toolkit --output C:/repos/Wind_Toolkit/Wind_Toolkit_Engine/Python --python 3.11 +``` + +This generates a ready-to-use project with a `pyproject.toml`, an example module (logging and usage analytics), +pytest tests, Sphinx documentation and the shared ruff configuration. It also prints the csproj snippet that deploys +the toolkit when it is built. See [Python_Engine/Python/README.md](Python_Engine/Python/README.md) for the +conventions. + +## Developing this repository + +Prerequisites: BHoM installed in `C:\ProgramData\BHoM`, the .NET SDK, and [uv](https://docs.astral.sh/uv/). + +**In VS Code**, open the repository folder and accept the recommended extensions, then: + +- `Ctrl+Shift+B` builds the solution without deploying (*C#: build and deploy to BHoM* deploys). +- *Tasks: Run Test Task* runs the C# tests or the Python tests. The Python tests also appear in the Testing panel + once *Python: sync* has created `Python_Engine/Python/.venv`. + +**From a terminal:** + +```powershell +dotnet build Python_Toolkit.sln -p:BHoMSkipDeploy=true +dotnet test .ci/unit_tests/Python_Engine_Test/Python_Engine_Test.csproj --filter "Category!=Integration" +dotnet test .ci/unit_tests/Python_Engine_Test/Python_Engine_Test.csproj --filter "Category=Integration" # end to end, a few minutes + +cd Python_Engine/Python +uv sync --all-extras +uv run pytest +uv run ruff format; uv run ruff check --fix +``` + +The C# tests never touch `C:\ProgramData\BHoM\Extensions\Python`. They redirect it to a temporary folder through the +`BHOM_PYTHON_EXTENSIONS_DIR` environment variable. The *Integration* tests do the following, end to end, in that +temporary folder: + +1. Deploy `Python_Toolkit` and create its environment. +2. Run its pytest suite from C#. +3. Scaffold a downstream toolkit, then create and test its environment. + +To format and lint on every commit, run `uv run --project Python_Engine/Python pre-commit install` once. ## Want to contribute? ## diff --git a/Versioning_93.json b/Versioning_93.json new file mode 100644 index 00000000..1307c5e6 --- /dev/null +++ b/Versioning_93.json @@ -0,0 +1,44 @@ +{ + "Namespace": { + "ToNew": {}, + "ToOld": {} + }, + "Type": { + "ToNew": {}, + "ToOld": {} + }, + "Property": { + "ToNew": {}, + "ToOld": {} + }, + "MessageForDeleted": { + "BH.Engine.Python.Compute.BasePythonEnvironment(BH.oM.Python.Enums.PythonVersion, System.Boolean, System.Boolean)": "Python environments are now managed by UV. Use InstallPythonToolkitVenv to install the toolkit environment, or VirtualEnvironment with a Python version string to create a named environment. Reconnect inputs manually.", + "BH.Engine.Python.Compute.DownloadFile(System.String, System.String, System.String, System.Boolean)": "This download helper has been removed. Python installation is now handled by UV. For other downloads, use a separate file-download workflow.", + "BH.Engine.Python.Compute.DownloadPythonVersion(BH.oM.Python.Enums.PythonVersion)": "Python installation is now handled by UV. Use VirtualEnvironment with a Python version string, such as \"3.10\", instead.", + "BH.Engine.Python.Compute.InstallPackages(System.String, System.Collections.Generic.List)": "Installation using an executable path has been removed. Use InstallPackages with a PythonEnvironment created using the UV workflow and set run to true.", + "BH.Engine.Python.Compute.InstallRequirements(BH.oM.Python.PythonEnvironment, System.String)": "Requirements-file installation has been removed. Declare dependencies in pyproject.toml and create the environment from that file, or supply package requirements to InstallPackages with run set to true.", + "BH.Engine.Python.Compute.InstallRequirements(System.String, System.String)": "Requirements-file installation using an executable path has been removed. Declare dependencies in pyproject.toml and create the environment from that file, or use InstallPackages with a PythonEnvironment and run set to true.", + "BH.Engine.Python.Compute.InstallPackageLocal(System.String, System.String)": "Local package installation using an executable path has been removed. Use InstallPackageLocal with a PythonEnvironment created using the UV workflow and set run to true.", + "BH.Engine.Python.Compute.RemoveKernel(System.String)": "Use RemoveJupyterKernel with the name of a UV-managed BHoM environment and set run to true. Legacy kernels may require manual removal using Jupyter.", + "BH.Engine.Python.Compute.RemoveAllKernels()": "Bulk kernel removal has been removed. Use RemoveJupyterKernel for individual UV-managed BHoM environments with run set to true. Legacy kernels may require manual removal using Jupyter.", + "BH.Engine.Python.Compute.RemoveVirtualEnvironment(System.String)": "Replace this component with RemoveVirtualEnvironment(String, Boolean) and set run to true. It removes environments in the new BHoM Python directory; legacy environments require separate cleanup.", + "BH.Engine.Python.Compute.RemoveAllVirtualEnvironments()": "Bulk environment removal has been removed. Use RemoveVirtualEnvironment for each named environment and set run to true. RemoveEverything also removes BHoM-managed UV tools, so use it only when that broader cleanup is intended.", + "BH.Engine.Python.Compute.RemoveBaseVersion(BH.oM.Python.Enums.PythonVersion)": "The former base Python installation workflow has been removed. Use RemoveVirtualEnvironment for named BHoM environments. Removing UV does not uninstall UV-managed Python runtimes or legacy Python installations.", + "BH.Engine.Python.Compute.RequirementsTxt(System.String, System.String)": "Requirements-file generation has been removed. Manage project dependencies using pyproject.toml and UV. Use UV export separately if a requirements.txt file is needed.", + "BH.Engine.Python.Compute.UnzipFile(System.String, System.String, System.String, System.Boolean)": "This archive-extraction helper has been removed. Use a separate archive-extraction workflow if needed.", + "BH.Engine.Python.Compute.UpdateBHoMPackages(System.String, BH.oM.Python.Enums.PythonVersion)": "Use UpdateBHoMPackages(PythonEnvironment) with an environment created using the UV workflow. The PythonVersion enum input is no longer supported.", + "BH.Engine.Python.Compute.VirtualEnvironment(BH.oM.Python.Enums.PythonVersion, System.String, System.Boolean)": "Replace this component with VirtualEnvironment(String, String, Boolean). Replace the PythonVersion enum with a version string, such as \"3.10\", and recreate the environment using UV.", + "BH.Engine.Python.Query.DirectoryKernels()": "The fixed kernel-directory query has been removed. Use Jupyter kernelspec discovery to locate registered kernels.", + "BH.Engine.Python.Query.DirectoryCode()": "The separate PythonCode directory is no longer used. Toolkit project files now reside under DirectoryEnvironments(), within the toolkit's named directory.", + "BH.Engine.Python.Query.DirectoryBaseEnvironment(BH.oM.Python.Enums.PythonVersion)": "Base Python environments are no longer organised by PythonVersion. Use a named UV-managed environment and query its directory or executable instead.", + "BH.Engine.Python.Query.EmbeddableURL(BH.oM.Python.Enums.PythonVersion)": "Python downloads are now managed by UV. Use VirtualEnvironment with a Python version string instead of retrieving an installer URL.", + "BH.Engine.Python.Query.IsValidEnvironmentName(System.String)": "This legacy environment-name validation method has been removed. Review names against the requirements of the UV environment and Jupyter kernel workflows.", + "BH.Engine.Python.Query.VirtualEnvironmentExists(System.String, BH.oM.Python.Enums.PythonVersion)": "Replace this component with VirtualEnvironmentExists(String). It checks the new UV-managed BHoM environment layout and no longer accepts a PythonVersion input.", + "BH.Engine.Python.Query.VirtualEnvironmentKernel(System.String)": "This kernel-path query has been removed. Use Jupyter kernelspec discovery to locate a registered kernel.", + "BH.oM.Python.Enums.PythonVersion": "Python versions are now specified as strings, such as \"3.10\" or \"3.11\". Replace enum inputs with the appropriate version string and recreate environments using the UV workflow." + }, + "MessageForNoUpgrade": { + "BH.Engine.Python.Compute.RunCommandStdout(System.String, System.Boolean, System.String, System.Double)": "The output has changed from a single string to stdout, stderr and exit code. Review and reconnect downstream components manually. Exit code zero indicates success; -1 indicates timeout.", + "BH.Engine.Python.Query.Version(System.String)": "The output is now a Python version string instead of PythonVersion. Replace downstream enum-based comparisons and inputs with string-based equivalents." + } +} \ No newline at end of file