chemql-python 1.8.0__tar.gz → 1.8.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. {chemql_python-1.8.0/src/chemql_python.egg-info → chemql_python-1.8.1}/PKG-INFO +2 -2
  2. {chemql_python-1.8.0 → chemql_python-1.8.1}/README.md +1 -1
  3. {chemql_python-1.8.0 → chemql_python-1.8.1}/pyproject.toml +1 -1
  4. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/__init__.py +129 -4
  5. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/algebra/engine.py +356 -0
  6. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/codecql.py +76 -7
  7. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/codecql_gui_core.py +15 -4
  8. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/colors.json +5 -0
  9. chemql_python-1.8.1/src/chemql/data_analysis/visualization/plot3d.py +522 -0
  10. chemql_python-1.8.1/src/chemql/highlighting.json +1040 -0
  11. chemql_python-1.8.1/src/chemql/stdlib/diff.cql +104 -0
  12. chemql_python-1.8.1/src/chemql/stdlib/ml.cql +382 -0
  13. chemql_python-1.8.1/src/chemql/stdlib/optimize.cql +376 -0
  14. chemql_python-1.8.1/src/chemql/stdlib/quantities.cql +214 -0
  15. chemql_python-1.8.1/src/chemql/stdlib/spectra.cql +316 -0
  16. chemql_python-1.8.1/src/chemql/stdlib/templates.cql +85 -0
  17. chemql_python-1.8.1/src/chemql/stdlib/toml.cql +106 -0
  18. chemql_python-1.8.1/src/chemql/stdlib/xmldoc.cql +181 -0
  19. {chemql_python-1.8.0 → chemql_python-1.8.1/src/chemql_python.egg-info}/PKG-INFO +2 -2
  20. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql_python.egg-info/SOURCES.txt +10 -0
  21. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_codecql.py +122 -1
  22. chemql_python-1.8.1/tests/test_new_stdlib_packages.py +193 -0
  23. chemql_python-1.8.0/src/chemql/highlighting.json +0 -954
  24. {chemql_python-1.8.0 → chemql_python-1.8.1}/LICENSE +0 -0
  25. {chemql_python-1.8.0 → chemql_python-1.8.1}/setup.cfg +0 -0
  26. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/__main__.py +0 -0
  27. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/algebra/__init__.py +0 -0
  28. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/algebra/helper.py +0 -0
  29. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/build.py +0 -0
  30. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/codecqlx.py +0 -0
  31. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data/BondEnergies.json +0 -0
  32. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data/MoleculeBonds.json +0 -0
  33. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data/Molecules.json +0 -0
  34. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data/PeriodicTableJSON.json +0 -0
  35. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data/Reactions.json +0 -0
  36. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data/THIRD_PARTY_LICENSES/PeriodicTableJSON.txt +0 -0
  37. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data/THIRD_PARTY_LICENSES/RHEA.txt +0 -0
  38. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/__init__.py +0 -0
  39. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/spreadsheet.py +0 -0
  40. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/__init__.py +0 -0
  41. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/area.py +0 -0
  42. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/bar.py +0 -0
  43. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/boxplot.py +0 -0
  44. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/candlestick.py +0 -0
  45. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/common.py +0 -0
  46. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/heatmap.py +0 -0
  47. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/histogram.py +0 -0
  48. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/line.py +0 -0
  49. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/main.py +0 -0
  50. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/pie.py +0 -0
  51. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/scatter.py +0 -0
  52. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/svg.py +0 -0
  53. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/data_analysis/visualization/web.py +0 -0
  54. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/formatter.py +0 -0
  55. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/highlighting.py +0 -0
  56. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/html/periodic_table.html +0 -0
  57. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/logo64-macos.png +0 -0
  58. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/logo64.png +0 -0
  59. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/quantity.py +0 -0
  60. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/safety.py +0 -0
  61. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/README.md +0 -0
  62. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/async.cql +0 -0
  63. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/bits.cql +0 -0
  64. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/chem/formula.cql +0 -0
  65. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/chem.cql +0 -0
  66. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/ciphers.cql +0 -0
  67. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/collections.cql +0 -0
  68. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/colors.cql +0 -0
  69. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/constants.cql +0 -0
  70. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/dates.cql +0 -0
  71. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/datetime.cql +0 -0
  72. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/decimal.cql +0 -0
  73. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/encoding.cql +0 -0
  74. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/events.cql +0 -0
  75. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/finance.cql +0 -0
  76. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/fmt.cql +0 -0
  77. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/fp.cql +0 -0
  78. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/fractions.cql +0 -0
  79. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/geometry.cql +0 -0
  80. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/graphs.cql +0 -0
  81. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/hashing.cql +0 -0
  82. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/iter.cql +0 -0
  83. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/json.cql +0 -0
  84. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/maps.cql +0 -0
  85. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/math/calculus.cql +0 -0
  86. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/math/data.cql +0 -0
  87. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/math/inference.cql +0 -0
  88. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/math/linalg.cql +0 -0
  89. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/math/numbers.cql +0 -0
  90. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/math/probability.cql +0 -0
  91. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/math/statistics.cql +0 -0
  92. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/math.cql +0 -0
  93. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/pathlib.cql +0 -0
  94. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/physics.cql +0 -0
  95. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/pipeline.cql +0 -0
  96. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/predicates.cql +0 -0
  97. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/random.cql +0 -0
  98. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/regex.cql +0 -0
  99. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/sampling.cql +0 -0
  100. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/sequences.cql +0 -0
  101. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/sets.cql +0 -0
  102. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/sql.cql +0 -0
  103. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/state.cql +0 -0
  104. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/sysinfo.cql +0 -0
  105. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/tables.cql +0 -0
  106. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/text/utils.cql +0 -0
  107. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/text.cql +0 -0
  108. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/timing.cql +0 -0
  109. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/units.cql +0 -0
  110. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql/stdlib/validate.cql +0 -0
  111. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql_python.egg-info/dependency_links.txt +0 -0
  112. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql_python.egg-info/entry_points.txt +0 -0
  113. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql_python.egg-info/requires.txt +0 -0
  114. {chemql_python-1.8.0 → chemql_python-1.8.1}/src/chemql_python.egg-info/top_level.txt +0 -0
  115. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_codecqlx_console.py +0 -0
  116. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_codecqlx_fonts.py +0 -0
  117. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_codecqlx_icon.py +0 -0
  118. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_codecqlx_theme.py +0 -0
  119. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_data_analysis.py +0 -0
  120. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_external_molecule_lookup.py +0 -0
  121. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_function_parameters.py +0 -0
  122. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_images_and_binary.py +0 -0
  123. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_lambda_calls_and_algebra.py +0 -0
  124. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_public_api.py +0 -0
  125. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_reactions.py +0 -0
  126. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_repl_history.py +0 -0
  127. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_stdlib.py +0 -0
  128. {chemql_python-1.8.0 → chemql_python-1.8.1}/tests/test_structured_types.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: chemql-python
3
- Version: 1.8.0
3
+ Version: 1.8.1
4
4
  Summary: A chemistry-focused query language and REPL
5
5
  Author-email: Mohammad Rakibul Islam <rakibulofficial1017@gmail.com>
6
6
  Requires-Python: >=3.12
@@ -23,7 +23,7 @@ ChemQL is a small language for querying, computing with, and simulating chemistr
23
23
 
24
24
  - **Distribution name:** `chemql-python`
25
25
  - **Import / CLI name:** `chemql`
26
- - **Language version:** `1.8.0` (per `chemql.__version__`)
26
+ - **Language version:** `1.8.1` (per `chemql.__version__`)
27
27
  - **Editor version:** `codecql 0.1.2`
28
28
  - **GUI Editor version:** `CodecQLX 1.1.1`
29
29
  - **Author:** Mohammad Rakibul Islam
@@ -6,7 +6,7 @@ ChemQL is a small language for querying, computing with, and simulating chemistr
6
6
 
7
7
  - **Distribution name:** `chemql-python`
8
8
  - **Import / CLI name:** `chemql`
9
- - **Language version:** `1.8.0` (per `chemql.__version__`)
9
+ - **Language version:** `1.8.1` (per `chemql.__version__`)
10
10
  - **Editor version:** `codecql 0.1.2`
11
11
  - **GUI Editor version:** `CodecQLX 1.1.1`
12
12
  - **Author:** Mohammad Rakibul Islam
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "chemql-python"
7
- version = "1.8.0"
7
+ version = "1.8.1"
8
8
  authors = [
9
9
  { name = "Mohammad Rakibul Islam", email = "rakibulofficial1017@gmail.com" }
10
10
  ]
@@ -104,7 +104,7 @@ __all__ = [
104
104
  "__version__"
105
105
  ]
106
106
 
107
- __version__ = "1.8.0"
107
+ __version__ = "1.8.1"
108
108
 
109
109
  # Persistent preprocessor/function state for the current ChemQL session.
110
110
  DEFINITIONS = {}
@@ -526,6 +526,40 @@ def run_spreadsheet_gui(source=None, theme="light"):
526
526
  return open_dashboard(source, theme)
527
527
 
528
528
 
529
+ # ── 3-D visualizations ──────────────────────────────────────────────────────
530
+
531
+ def scatter3d(points, title="3D Scatter"):
532
+ """Open an interactive 3-D scatter plot in the browser.
533
+ ``points`` is a list of [x, y, z] triples."""
534
+ _sandbox_require("scatter3d")
535
+ from .data_analysis.visualization.plot3d import scatter3d as _s3d
536
+ _s3d(points, title=str(title))
537
+
538
+
539
+ def line3d(points_or_series, title="3D Line"):
540
+ """Open an interactive 3-D line chart in the browser.
541
+ Pass a list of [x, y, z] triples, or a dict of {name: [[x,y,z], ...]}."""
542
+ _sandbox_require("line3d")
543
+ from .data_analysis.visualization.plot3d import line3d as _l3d
544
+ _l3d(points_or_series, title=str(title))
545
+
546
+
547
+ def surface3d(z_matrix, title="3D Surface"):
548
+ """Open an interactive 3-D surface plot in the browser.
549
+ ``z_matrix[row][col]`` is the height at that grid cell."""
550
+ _sandbox_require("surface3d")
551
+ from .data_analysis.visualization.plot3d import surface3d as _sf3d
552
+ _sf3d(z_matrix, title=str(title))
553
+
554
+
555
+ def bar3d(z_matrix, title="3D Bar Chart", bar_width=0.7):
556
+ """Open an interactive 3-D bar chart in the browser.
557
+ ``z_matrix[row][col]`` is the bar height at that grid position."""
558
+ _sandbox_require("bar3d")
559
+ from .data_analysis.visualization.plot3d import bar3d as _b3d
560
+ _b3d(z_matrix, title=str(title), bar_width=float(bar_width))
561
+
562
+
529
563
  # name: (callable, minimum positional arguments, maximum positional arguments)
530
564
  # Built-ins are native Python-backed operations; user-defined ChemQL functions
531
565
  # retain precedence when a name is defined in FUNCTIONS.
@@ -589,6 +623,10 @@ BUILTIN_FUNCTIONS = {
589
623
  "show_heat_map": (show_heat_map, 1, 4),
590
624
  "show_candlestick_chart": (show_candlestick_chart, 1, 3),
591
625
  "run_spreadsheet_gui": (run_spreadsheet_gui, 0, 2),
626
+ "scatter3d": (scatter3d, 1, 2),
627
+ "line3d": (line3d, 1, 2),
628
+ "surface3d": (surface3d, 1, 2),
629
+ "bar3d": (bar3d, 1, 3),
592
630
  "sym_eval": (_algebra.sym_eval, 1, 2),
593
631
  "sym_diff": (_algebra.sym_diff, 1, 3),
594
632
  "sym_integrate": (_algebra.sym_integrate, 1, 4),
@@ -657,6 +695,10 @@ _BUILTIN_HELP = {
657
695
  "show_heat_map": ("Data Analysis", "show_heat_map{matrix, row_labels?, column_labels?, theme?}", "Open an interactive heat map window.", ['show_heat_map{[[1, 2], [3, 4]], ["N", "S"], ["Q1", "Q2"]}']),
658
696
  "show_candlestick_chart": ("Data Analysis", "show_candlestick_chart{ohlc, labels?, theme?}", "Open an interactive OHLC candlestick window.", ['show_candlestick_chart{[(10, 13, 9, 12)], ["Mon"]}']),
659
697
  "run_spreadsheet_gui": ("Data Analysis", "run_spreadsheet_gui{spreadsheet?, theme?}", "Open the spreadsheet visualization dashboard for a Spreadsheet or DataFrame.", ['run_spreadsheet_gui{sheet}']),
698
+ "scatter3d": ("3D Visualization", "scatter3d{points, title?}", "Open an interactive 3-D scatter plot in the browser. points is a list of [x,y,z] triples. Drag to rotate, scroll to zoom, right-drag to pan. Points are coloured by height using a blue-to-red scale.", ['scatter3d{[[0,0,0],[1,2,1],[2,1,3]], title="My 3D Scatter"}']),
699
+ "line3d": ("3D Visualization", "line3d{points_or_series, title?}", "Open an interactive 3-D line chart. Pass a list of [x,y,z] triples for one curve, or a dict {name: [[x,y,z],...]} for multiple named series.", ['line3d{[[0,0,0],[1,1,1],[2,0,2]]}']),
700
+ "surface3d": ("3D Visualization", "surface3d{z_matrix, title?}", "Open an interactive 3-D surface plot. z_matrix[row][col] is the height. The surface is shaded using a colour scale; a semi-transparent wireframe overlay shows the grid.", ['surface3d{[[0,1,0],[1,2,1],[0,1,0]]}']),
701
+ "bar3d": ("3D Visualization", "bar3d{z_matrix, title?, bar_width?}", "Open an interactive 3-D bar chart. z_matrix[row][col] is the bar height at that grid position. Bars are coloured by height.", ['bar3d{[[1,2,3],[4,5,6],[7,8,9]]}']),
660
702
  "quantity": ("Units", "quantity{value, unit?}", "Make a quantity from a number and a unit, or from text such as \"5 mol/L\". You can also write quantities directly: 5 mol, 25 °C, 1.5 atm.", ['quantity{5, "mol"}', 'quantity{"9.81 m/s^2"}']),
661
703
  "to": ("Units", "to{quantity, unit}", "Convert a quantity to another unit of the same kind. Incompatible units raise an error.", ['to{1 atm, "kPa"} # 101.325 kPa', 'to{25 °C, "K"} # 298.15 K']),
662
704
  "magnitude": ("Units", "magnitude{quantity, unit?}", "The plain number of a quantity, optionally after converting to a unit. Use it to pass a quantity to functions that expect numbers.", ['magnitude{2 mol/L, "mmol/L"} # 2000']),
@@ -710,6 +752,36 @@ _HELP_TOPICS = {
710
752
  "See help{fp} for details on every function.",
711
753
  "Related packages: iter (iteration), predicates (filter builders), pipeline (named steps).",
712
754
  ]),
755
+ "set_theory": ("Set Theory in the Algebra Engine", [
756
+ "Use inside `algebra` / `sym` commands. See help{algebra_sets} for the full reference.",
757
+ "algebra 3 \\in \\mathbb{Z} # True",
758
+ "algebra 0.5 \\in \\mathbb{Z} # False",
759
+ "algebra \\pi \\in \\mathbb{R} # True",
760
+ "algebra 7 \\in \\mathbb{P} # True (prime numbers)",
761
+ "algebra 2 \\in \\{1,2,3\\} # True (explicit set)",
762
+ "algebra \\{1,2,3\\} \\cup \\{3,4,5\\} # {1, 2, 3, 4, 5}",
763
+ "algebra \\{1,2,3\\} \\cap \\{2,3,4\\} # {2, 3}",
764
+ "algebra \\{1,2,3\\} \\setminus \\{2\\} # {1, 3}",
765
+ "algebra \\{1,2\\} \\subset \\{1,2,3\\} # True",
766
+ "algebra \\forall x \\in \\{1,2,3\\}: x > 0 # True",
767
+ "algebra \\exists x \\in \\{1,4,9\\}: x > 5 # True",
768
+ "Supported sets: \\mathbb{N} \\mathbb{Z} \\mathbb{Z+} \\mathbb{Z-} \\mathbb{Q} \\mathbb{R} \\mathbb{C} \\mathbb{P}",
769
+ "Supported ops: \\in \\notin \\cup \\cap \\setminus \\triangle \\subset \\subseteq \\supset \\supseteq",
770
+ ]),
771
+ "sets": ("Set Theory in the Algebra Engine", [
772
+ "Alias for set_theory. See help{set_theory} or help{algebra_sets}.",
773
+ ]),
774
+ "3d": ("3-D Visualization", [
775
+ "scatter3d{points, title?} — interactive 3-D scatter (points = [[x,y,z], ...])",
776
+ "line3d{points_or_series, title?} — 3-D polyline or multiple named series",
777
+ "surface3d{z_matrix, title?} — 3-D surface from a 2-D grid of heights",
778
+ "bar3d{z_matrix, title?, bar_width?} — 3-D bar chart from a 2-D grid of heights",
779
+ "All charts open in your browser. Drag to rotate, scroll to zoom, right-drag to pan.",
780
+ "Colour scale: blue (low) → cyan → green → yellow → red (high).",
781
+ "Example: scatter3d{[[0,0,0],[1,1,1],[2,0,2]]}",
782
+ "Example: surface3d{[[i*j for j in range(5)] for i in range(5)]}",
783
+ "See help{3d_visualization} for more.",
784
+ ]),
713
785
  "syntax": ("ChemQL Syntax", ["Function calls use braces: `name{arg1, arg2}`.", "Quote text containing spaces: `upper{\"hello world\"}`.", "Separate arguments with commas, not spaces.", "Python statements/expressions can be embedded in `[ ... ]`.", "Multiline Python uses `[[[ ... ]]]`; embedded queries use `{{ ... }}`.", "Enums use `enum Name [from Base]`, member declarations, and `endenum`; omitted values are generated automatically.", "Structs and records may use `from Base`; structs inherit from structs, records, or Python classes, while records inherit only from records.", "Definitions are defined like `define MAX 9` and used like `@MAX * 2`, which returns 18", "Macros are defined like define Macro{} with the body text under it and ended by `enddefine` and called like @Macro{}"]),
714
786
  "errors": ("ChemQL Error Signals", ["SyntaxError — the input could not be parsed as valid syntax.", "TooFewArguments — a function received fewer arguments than required.", "TooManyArguments — a function received more arguments than allowed.", "InvalidArgumentType — an argument has an unsupported type.", "InvalidArgumentValue — an argument's value is invalid.", "FileReadError — reading a file failed.", "FileWriteError — writing a file failed.", "NameError — a name or function is unknown.", "PermissionError — a private namespace function was called externally."]),
715
787
  "files": ("File Functions", ["read_text{path, encoding?}", "read_lines{path, encoding?}", "read_csv{path, delimiter?, encoding?, header?}", "read_json{path, encoding?}", "write_text{path, content, encoding?}", "write_csv{path, rows, delimiter?, encoding?}", "write_json{path, value, encoding?, indent?}", "file_exists{path}", "list_files{directory?, pattern?}"]),
@@ -728,6 +800,7 @@ _HELP_TOPICS = {
728
800
  ]),
729
801
  "chemistry": ("Chemistry Functions", ["molar_mass{formula}", "count_atoms{formula, element_symbol}", "empirical_formula{formula}", "element{symbol, field?}"]),
730
802
  "data_analysis": ("Data Analysis Tools", [
803
+ "── Terminal charts (draw_* return a text string) ──────────────────────",
731
804
  "draw_bar_chart{values, labels?}",
732
805
  "draw_line_chart{values, labels?}",
733
806
  "draw_area_chart{values, labels?}",
@@ -737,6 +810,7 @@ _HELP_TOPICS = {
737
810
  "draw_box_plot{values}",
738
811
  "draw_heat_map{matrix, row_labels?, column_labels?}",
739
812
  "draw_candlestick_chart{ohlc, labels?}",
813
+ "── Interactive browser charts (show_* open in a window) ───────────────",
740
814
  "show_bar_chart{values, labels?, theme?}",
741
815
  "show_line_chart{values, labels?, theme?}",
742
816
  "show_area_chart{values, labels?, theme?}",
@@ -747,6 +821,13 @@ _HELP_TOPICS = {
747
821
  "show_heat_map{matrix, row_labels?, column_labels?, theme?}",
748
822
  "show_candlestick_chart{ohlc, labels?, theme?}",
749
823
  "run_spreadsheet_gui{spreadsheet?, theme?}",
824
+ "── 3-D interactive charts (open in the browser with three.js) ─────────",
825
+ "scatter3d{points, title?} — 3-D scatter plot (points = [[x,y,z], ...])",
826
+ "line3d{points_or_series, title?}— 3-D polyline or multi-series lines",
827
+ "surface3d{z_matrix, title?} — 3-D surface from a grid of heights",
828
+ "bar3d{z_matrix, title?, bar_width?} — 3-D bar chart from a grid of heights",
829
+ "Controls: drag to rotate · scroll to zoom · right-drag to pan",
830
+ "── Spreadsheets ───────────────────────────────────────────────────────",
750
831
  "Spreadsheet, Vector, and every chart class are available inside Python code blocks.",
751
832
  "Example: let sheet = Spreadsheet{3, 2}",
752
833
  ]),
@@ -877,6 +958,44 @@ _STDLIB_HELP = {
877
958
  "Example: quantities::ideal_gas_pressure{1 mol, 273.15 K, 22.414 L} # about 101.3 kPa",
878
959
  ],
879
960
  ),
961
+ "3d_visualization": (
962
+ "Interactive 3-D charts rendered with three.js in your browser. No extra dependencies — only the standard library is used server-side.",
963
+ [
964
+ "scatter3d{points, title?} — 3-D scatter plot. points = [[x,y,z], ...]",
965
+ "line3d{points_or_series, title?} — 3-D polyline or multiple named series ({name: [[x,y,z],...]}).",
966
+ "surface3d{z_matrix, title?} — 3-D surface. z_matrix[row][col] = height.",
967
+ "bar3d{z_matrix, title?, bar_width?} — 3-D bar chart. z_matrix[row][col] = bar height.",
968
+ "Controls: left-drag to rotate · scroll to zoom · right-drag to pan.",
969
+ "Colour scale runs blue (low) → cyan → green → yellow → red (high).",
970
+ "An AxesHelper and grid are always shown; each axis is 1 unit long.",
971
+ "Example: scatter3d{[[0,0,0],[1,2,1],[2,1,3]]}",
972
+ "Example: surface3d{[[i*j for j in range(5)] for i in range(5)]}",
973
+ "Example: line3d{{'sin': [[x/10, math.sin(x/10), 0] for x in range(63)]}}",
974
+ ],
975
+ ),
976
+ "algebra_sets": (
977
+ "Set theory and membership testing inside `algebra` / `sym` commands.",
978
+ [
979
+ "\\\\in / \\\\notin — membership test: `algebra 3 \\\\in \\\\mathbb{Z}` → True",
980
+ "\\\\mathbb{N} — natural numbers (non-negative integers)",
981
+ "\\\\mathbb{Z} — integers (including negatives)",
982
+ "\\\\mathbb{Z+} / \\\\mathbb{Z-} — positive / negative integers",
983
+ "\\\\mathbb{Q} — rational numbers (heuristic: exact fractions and recognisable decimals)",
984
+ "\\\\mathbb{R} — real numbers (any finite float)",
985
+ "\\\\mathbb{C} — complex numbers (always True for a real input)",
986
+ "\\\\mathbb{P} — prime numbers",
987
+ "Explicit sets: `algebra 2 \\\\in \\\\{1,2,3\\\\}` → True",
988
+ "\\\\cup — union: `algebra \\\\{1,2,3\\\\} \\\\cup \\\\{3,4,5\\\\}` → {1, 2, 3, 4, 5}",
989
+ "\\\\cap — intersection: `algebra \\\\{1,2,3\\\\} \\\\cap \\\\{2,3,4\\\\}` → {2, 3}",
990
+ "\\\\setminus — difference: `algebra \\\\{1,2,3\\\\} \\\\setminus \\\\{2\\\\}` → {1, 3}",
991
+ "\\\\triangle / \\\\symdiff — symmetric difference",
992
+ "\\\\subset / \\\\subseteq / \\\\supset / \\\\supseteq — subset / superset tests",
993
+ "\\\\forall x \\\\in S: cond — universal quantifier over an explicit set",
994
+ "\\\\exists x \\\\in S: cond — existential quantifier over an explicit set",
995
+ "Example: algebra \\\\forall x \\\\in \\\\{1,2,3\\\\}: x > 0",
996
+ "Example: algebra \\\\exists x \\\\in \\\\{1,4,9,16\\\\}: x > 10",
997
+ ],
998
+ ),
880
999
  "units": (
881
1000
  "Unit conversion between common scientific units.",
882
1001
  [
@@ -5573,6 +5692,10 @@ python_globals = {
5573
5692
  "show_box_plot": show_box_plot,
5574
5693
  "show_heat_map": show_heat_map,
5575
5694
  "show_candlestick_chart": show_candlestick_chart,
5695
+ "scatter3d": scatter3d,
5696
+ "line3d": line3d,
5697
+ "surface3d": surface3d,
5698
+ "bar3d": bar3d,
5576
5699
  "run_spreadsheet_gui": run_spreadsheet_gui,
5577
5700
  }
5578
5701
  STRUCTS = {}
@@ -6534,12 +6657,14 @@ def evaluate_python(code):
6534
6657
  # A plain name works the same way: "Hello "name -> "Hello " + str(name).
6535
6658
  # Keywords (`in`, `if`, `and` ...) and names that start a call are left alone.
6536
6659
  code = re.sub(
6537
- r'("(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\')'
6660
+ r'(#[^\n]*)'
6661
+ r'|("(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\')'
6538
6662
  r'((?:this|[A-Za-z_]\w*)(?:\.[A-Za-z_]\w*)+'
6539
6663
  r'|(?!(?:%s)\b)[A-Za-z_]\w*(?![\w{(\[.:]))?' % "|".join(sorted(keyword.kwlist)),
6540
6664
  lambda match: (
6541
- match.group(1) + " + str(" + match.group(2) + ")"
6542
- if match.group(2) else match.group(0)
6665
+ match.group(1) if match.group(1) is not None else
6666
+ match.group(2) + " + str(" + match.group(3) + ")"
6667
+ if match.group(3) else match.group(2)
6543
6668
  ),
6544
6669
  code,
6545
6670
  )
@@ -1155,6 +1155,7 @@ _HELP = {
1155
1155
  variables let, unset, vars, reset, ans, f(x) = ...
1156
1156
  lists let x = [1, 2, ... 10]; f(x) maps f over every element
1157
1157
  latex \\sin^2 x, \\binom{n}{k}, \\lfloor x \\rfloor, \\begin{cases}...\\end{cases}, multi-line input
1158
+ sets 3 \\in \\mathbb{Z}, \\{1,2\\} \\cup \\{3,4\\}, \\forall x \\in \\{1,2,3\\}: x > 0
1158
1159
  settings set precision N, set mode standard|decimal|default""",
1159
1160
  "latex": """ Functions \\sin \\cos \\tan \\sec \\csc \\cot \\arcsin \\arccos \\arctan \\arcsec \\arccsc \\arccot
1160
1161
  \\sinh \\cosh \\tanh \\sech \\csch \\coth \\arsinh \\arcosh \\artanh (or \\arcsinh ...)
@@ -1200,6 +1201,37 @@ _HELP = {
1200
1201
  let a = 2; let b = 3; a*b several statements at once
1201
1202
  vars list everything defined
1202
1203
  unset a / reset forget one name / everything""",
1204
+ "sets": """ Membership
1205
+ 3 \\in \\mathbb{Z} True (integer)
1206
+ 0.5 \\in \\mathbb{Z} False
1207
+ \\pi \\in \\mathbb{R} True (real)
1208
+ 1/2 \\in \\mathbb{Q} True (rational)
1209
+ 7 \\in \\mathbb{P} True (prime)
1210
+ 2 \\in \\{1,2,3\\} True (explicit set)
1211
+ 5 \\notin \\{1,2,3\\} True
1212
+
1213
+ Standard sets
1214
+ \\mathbb{N} natural numbers (non-negative integers)
1215
+ \\mathbb{Z} integers \\mathbb{Z+} positive integers \\mathbb{Z-} negative
1216
+ \\mathbb{Q} rationals \\mathbb{R} reals \\mathbb{C} complex
1217
+ \\mathbb{P} prime numbers
1218
+
1219
+ Set operations (on explicit sets {a, b, c})
1220
+ \\{1,2,3\\} \\cup \\{3,4,5\\} {1, 2, 3, 4, 5}
1221
+ \\{1,2,3\\} \\cap \\{2,3,4\\} {2, 3}
1222
+ \\{1,2,3\\} \\setminus \\{2\\} {1, 3}
1223
+ \\{1,2,3\\} \\triangle \\{2,3,4\\} {1, 4} (symmetric difference)
1224
+
1225
+ Subset / superset tests
1226
+ \\{1,2\\} \\subset \\{1,2,3\\} True \\{1,2\\} \\subseteq \\{1,2\\} True
1227
+ \\{1,2,3\\} \\supset \\{1,2\\} True \\{1,2,3\\} \\supseteq \\{1,2,3\\} True
1228
+
1229
+ Quantifiers (over explicit sets)
1230
+ \\forall x \\in \\{1,2,3\\}: x > 0 True (all elements satisfy)
1231
+ \\exists x \\in \\{1,4,9,16\\}: x > 10 True (some element satisfies)
1232
+ \\forall x \\in \\{-1,0,1\\}: x^2 >= 0 True""",
1233
+ "set theory": """See `algebra help sets`""",
1234
+ "membership": """See `algebra help sets`""",
1203
1235
  }
1204
1236
 
1205
1237
 
@@ -1707,6 +1739,310 @@ _LATEX_REWRITES = [
1707
1739
  (re.compile(r"\\det(?![A-Za-z])"), "det"),
1708
1740
  (re.compile(r"\^\s*(?:\{\s*)?\\(?:top|intercal)(?![A-Za-z])(?:\s*\})?"), "^T"),
1709
1741
  ]
1742
+ # ---------------------------------------------------------------------------
1743
+ # Set theory — LaTeX set notation, membership tests, and quantifiers
1744
+ # ---------------------------------------------------------------------------
1745
+
1746
+ # Standard number sets (mathbb). Evaluated numerically when tested against.
1747
+ _MATHBB = {
1748
+ "N": "mathbb_N", "Z": "mathbb_Z", "Q": "mathbb_Q",
1749
+ "R": "mathbb_R", "C": "mathbb_C", "P": "mathbb_P",
1750
+ "Z+": "mathbb_Zpos", "Z-": "mathbb_Zneg",
1751
+ }
1752
+ # Keep the recognised set tokens so we can detect them later.
1753
+ _MATHBB_TOKENS = frozenset(_MATHBB.values())
1754
+
1755
+ # Pre-compiled patterns for the set-theory pre-pass.
1756
+ _SET_MEMBERSHIP = re.compile(
1757
+ r"^(.+?)\s*\\(?:in|notin|not\\s*\\in)\s+(.+)$", re.DOTALL
1758
+ )
1759
+ _SET_IN_NOTIN = re.compile(r"\\(notin|in)(?![A-Za-z])")
1760
+ _SET_SUBSET = re.compile(r"\\(subseteq?|supseteq?|subset|supset)(?![A-Za-z])")
1761
+ _SET_BINOP = re.compile(r"\\(cup|cap|setminus|triangle|symdiff)(?![A-Za-z])")
1762
+ _MATHBB_PATTERN = re.compile(r"\\mathbb\s*\{\s*([A-Za-z][^{}]*?)\s*\}")
1763
+ _SET_LITERAL = re.compile(r"^\{(.*)\}$", re.DOTALL)
1764
+ _QUANTIFIER = re.compile(
1765
+ r"^\\(forall|exists)\s+([^\W\d]\w*)\s+\\in\s+(.+?)\s*:\s*(.+)$", re.DOTALL
1766
+ )
1767
+
1768
+ # Rewrite \mathbb{X} to a placeholder token early so the LaTeX parser does not
1769
+ # choke. We do this in the LaTeX-layout normaliser.
1770
+ def _expand_mathbb(source: str) -> str:
1771
+ def _repl(m: re.Match) -> str:
1772
+ key = re.sub(r"\s+", "", m.group(1))
1773
+ return _MATHBB.get(key, f"mathbb_{key}")
1774
+ return _MATHBB_PATTERN.sub(_repl, source)
1775
+
1776
+
1777
+ def _parse_set_literal(text: str) -> list | None:
1778
+ """Return the elements of a {a,b,c} literal, or None."""
1779
+ text = text.strip()
1780
+ m = _SET_LITERAL.fullmatch(text)
1781
+ if not m:
1782
+ return None
1783
+ items = _split_top_level(m.group(1))
1784
+ result = []
1785
+ for item in items:
1786
+ try:
1787
+ result.append(_constant_float(item.strip()))
1788
+ except Exception:
1789
+ return None # symbolic elements not supported in set ops
1790
+ return result
1791
+
1792
+
1793
+ def _membership_test(value_text: str, set_text: str, negated: bool) -> bool | None:
1794
+ """Test value ∈ / ∉ set. Returns bool or None if the set is not recognised."""
1795
+ set_text = set_text.strip()
1796
+
1797
+ # --- Standard number sets ---
1798
+ if set_text in _MATHBB_TOKENS or set_text in _MATHBB.values():
1799
+ try:
1800
+ value = _constant_float(value_text)
1801
+ except Exception:
1802
+ return None # symbolic — cannot decide
1803
+ name = set_text
1804
+ if name in ("mathbb_N",):
1805
+ result = float(value).is_integer() and value >= 0
1806
+ elif name in ("mathbb_Zpos",):
1807
+ result = float(value).is_integer() and value > 0
1808
+ elif name in ("mathbb_Zneg",):
1809
+ result = float(value).is_integer() and value < 0
1810
+ elif name in ("mathbb_Z",):
1811
+ result = float(value).is_integer()
1812
+ elif name in ("mathbb_Q",):
1813
+ # Heuristic: if the decimal expansion within our precision looks rational
1814
+ from fractions import Fraction
1815
+ try:
1816
+ f = Fraction(value).limit_denominator(10 ** 9)
1817
+ result = abs(float(f) - float(value)) < 1e-9
1818
+ except Exception:
1819
+ result = True # treat as rational when uncertain
1820
+ elif name in ("mathbb_R",):
1821
+ result = math.isfinite(float(value))
1822
+ elif name in ("mathbb_C",):
1823
+ result = True # every real number is complex
1824
+ elif name in ("mathbb_P",): # primes
1825
+ n = int(value)
1826
+ if not float(value).is_integer() or n < 2:
1827
+ result = False
1828
+ else:
1829
+ result = all(n % i for i in range(2, int(n ** 0.5) + 1))
1830
+ else:
1831
+ return None
1832
+ return (not result) if negated else result
1833
+
1834
+ # --- Explicit set literal: {1, 2, 3} ---
1835
+ elements = _parse_set_literal(set_text)
1836
+ if elements is not None:
1837
+ try:
1838
+ value = _constant_float(value_text)
1839
+ except Exception:
1840
+ return None
1841
+ result = any(math.isclose(value, e, rel_tol=1e-9, abs_tol=1e-12) for e in elements)
1842
+ return (not result) if negated else result
1843
+
1844
+ return None
1845
+
1846
+
1847
+ def _set_binop(left_text: str, op: str, right_text: str):
1848
+ """Evaluate set ∪ / ∩ / \\ on literal sets."""
1849
+ left = _parse_set_literal(left_text)
1850
+ right = _parse_set_literal(right_text)
1851
+ if left is None or right is None:
1852
+ raise helper.ExpressionSyntaxError(
1853
+ f"set {op} requires explicit sets like {{1, 2, 3}}"
1854
+ )
1855
+ if op in ("cup", "union"):
1856
+ seen = set()
1857
+ result = []
1858
+ for x in left + right:
1859
+ key = round(x, 12)
1860
+ if key not in seen:
1861
+ seen.add(key)
1862
+ result.append(x)
1863
+ return result
1864
+ if op in ("cap", "intersection"):
1865
+ return [x for x in left if any(math.isclose(x, y, rel_tol=1e-9) for y in right)]
1866
+ if op in ("setminus", "minus"):
1867
+ return [x for x in left if not any(math.isclose(x, y, rel_tol=1e-9) for y in right)]
1868
+ if op in ("triangle", "symdiff"):
1869
+ only_left = [x for x in left if not any(math.isclose(x, y, rel_tol=1e-9) for y in right)]
1870
+ only_right = [x for x in right if not any(math.isclose(x, y, rel_tol=1e-9) for y in left)]
1871
+ return only_left + only_right
1872
+ raise helper.ExpressionSyntaxError(f"unknown set operation: {op}")
1873
+
1874
+
1875
+ def _subset_test(left_text: str, op: str, right_text: str) -> bool:
1876
+ left = _parse_set_literal(left_text)
1877
+ right = _parse_set_literal(right_text)
1878
+ if left is None or right is None:
1879
+ raise helper.ExpressionSyntaxError(
1880
+ "subset tests require explicit sets like {1, 2, 3}"
1881
+ )
1882
+ def contained(a, b):
1883
+ return all(any(math.isclose(x, y, rel_tol=1e-9) for y in b) for x in a)
1884
+ if op in ("subset", "subsetneq"):
1885
+ return contained(left, right) and (op == "subseteq" or left != right)
1886
+ if op in ("subseteq", "subseteqq"):
1887
+ return contained(left, right)
1888
+ if op in ("supset", "supsetneq"):
1889
+ return contained(right, left) and (op == "supseteq" or left != right)
1890
+ if op in ("supseteq", "supseteqq"):
1891
+ return contained(right, left)
1892
+ raise helper.ExpressionSyntaxError(f"unknown subset operator: {op}")
1893
+
1894
+
1895
+ def _quantifier_test(quantifier: str, var: str, set_text: str, condition: str) -> bool:
1896
+ """Evaluate ∀x∈S: cond(x) or ∃x∈S: cond(x) for explicit sets."""
1897
+ elements = _parse_set_literal(set_text)
1898
+ if elements is None:
1899
+ raise helper.ExpressionSyntaxError(
1900
+ "quantifiers require an explicit set like {1, 2, 3}"
1901
+ )
1902
+ results = []
1903
+ for elem in elements:
1904
+ saved = ENVIRONMENT.get(var)
1905
+ try:
1906
+ ENVIRONMENT[var] = _scalar_constant(elem)
1907
+ # Try a comparison condition first (x > 0, x <= 5, etc.)
1908
+ cond_stripped = condition.strip()
1909
+ cmp_parts = _COMPARISON_SPLIT.split(cond_stripped)
1910
+ if len(cmp_parts) >= 3:
1911
+ # It's a comparison — evaluate operands then compare
1912
+ try:
1913
+ result = _condition_holds(cond_stripped,
1914
+ lambda text: _constant_float(text))
1915
+ results.append(result)
1916
+ continue
1917
+ except Exception:
1918
+ pass
1919
+ # Fall back: try to evaluate as a numeric expression (truthy)
1920
+ val = _constant_float(cond_stripped)
1921
+ results.append(bool(val))
1922
+ except Exception:
1923
+ raise helper.ExpressionSyntaxError(
1924
+ f"quantifier condition {condition!r} could not be evaluated at {var}={elem}"
1925
+ )
1926
+ finally:
1927
+ if saved is None:
1928
+ ENVIRONMENT.pop(var, None)
1929
+ else:
1930
+ ENVIRONMENT[var] = saved
1931
+ if quantifier == "forall":
1932
+ return all(results)
1933
+ if quantifier == "exists":
1934
+ return any(results)
1935
+ raise helper.ExpressionSyntaxError(f"unknown quantifier: {quantifier}")
1936
+
1937
+
1938
+ def _try_set_theory(source: str):
1939
+ """Return a set-theory result if `source` is a set-theory expression, else None."""
1940
+ # Normalise \mathbb{X} -> token before anything else
1941
+ source = _expand_mathbb(source)
1942
+
1943
+ # ∀ / ∃ quantifiers
1944
+ q = _QUANTIFIER.fullmatch(source)
1945
+ if q:
1946
+ quantifier, var, set_text, condition = q.groups()
1947
+ set_text = _expand_mathbb(set_text).strip()
1948
+ return _quantifier_test(quantifier, var, set_text, condition)
1949
+
1950
+ # Set binary operations: left \cup/\cap/\setminus right
1951
+ # Scan for a binary op at the top level (outside braces)
1952
+ binop_match = _find_set_binop(source)
1953
+ if binop_match:
1954
+ left, op, right = binop_match
1955
+ return _set_binop(left, op, right)
1956
+
1957
+ # Subset / superset test
1958
+ subset_match = _find_set_subset(source)
1959
+ if subset_match:
1960
+ left, op, right = subset_match
1961
+ return _subset_test(left, op, right)
1962
+
1963
+ # Membership: value \in set or value \notin set
1964
+ mem = _find_membership(source)
1965
+ if mem:
1966
+ value_text, op, set_text = mem
1967
+ negated = "notin" in op
1968
+ result = _membership_test(value_text, set_text, negated)
1969
+ if result is not None:
1970
+ return result
1971
+
1972
+ return None # not a set-theory expression
1973
+
1974
+
1975
+ def _find_membership(source: str):
1976
+ """Find `value \\in set` or `value \\notin set` at the top level."""
1977
+ # Scan for \in or \notin not inside braces
1978
+ depth = 0
1979
+ i = 0
1980
+ while i < len(source):
1981
+ c = source[i]
1982
+ if c in "({[":
1983
+ depth += 1; i += 1; continue
1984
+ if c in ")}]":
1985
+ depth -= 1; i += 1; continue
1986
+ if depth == 0 and c == "\\":
1987
+ tail = source[i:]
1988
+ m = re.match(r"\\(notin|not\s*\\in|in)(?![A-Za-z])", tail)
1989
+ if m:
1990
+ op = m.group(1)
1991
+ left = source[:i].strip()
1992
+ right = source[i + m.end():].strip()
1993
+ if left and right:
1994
+ return left, op, right
1995
+ i += 1
1996
+ return None
1997
+
1998
+
1999
+ def _find_set_binop(source: str):
2000
+ """Find \\cup / \\cap / \\setminus at the top level."""
2001
+ depth = 0
2002
+ i = 0
2003
+ while i < len(source):
2004
+ c = source[i]
2005
+ if c in "({[":
2006
+ depth += 1; i += 1; continue
2007
+ if c in ")}]":
2008
+ depth -= 1; i += 1; continue
2009
+ if depth == 0 and c == "\\":
2010
+ tail = source[i:]
2011
+ m = re.match(r"\\(cup|cap|setminus|triangle|symdiff)(?![A-Za-z])", tail)
2012
+ if m:
2013
+ op = m.group(1)
2014
+ left = source[:i].strip()
2015
+ right = source[i + m.end():].strip()
2016
+ if left and right:
2017
+ return left, op, right
2018
+ i += 1
2019
+ return None
2020
+
2021
+
2022
+ def _find_set_subset(source: str):
2023
+ """Find \\subset / \\subseteq / \\supset / \\supseteq at the top level."""
2024
+ depth = 0
2025
+ i = 0
2026
+ while i < len(source):
2027
+ c = source[i]
2028
+ if c in "({[":
2029
+ depth += 1; i += 1; continue
2030
+ if c in ")}]":
2031
+ depth -= 1; i += 1; continue
2032
+ if depth == 0 and c == "\\":
2033
+ tail = source[i:]
2034
+ m = re.match(r"\\(subseteqq?|supseteqq?|subsetneq|supsetneq|subset|supset)(?![A-Za-z])", tail)
2035
+ if m:
2036
+ op = m.group(1)
2037
+ left = source[:i].strip()
2038
+ right = source[i + m.end():].strip()
2039
+ if left and right:
2040
+ return left, op, right
2041
+ i += 1
2042
+ return None
2043
+
2044
+ # ---------------------------------------------------------------------------
2045
+
1710
2046
  _MATRIX_POWER = re.compile(r"([^\W\d]\w*)\s*\^\s*\{\s*(T|-1)\s*\}")
1711
2047
  _CASES_ENVIRONMENTS = {"cases", "dcases", "rcases"}
1712
2048
  _PASSTHROUGH_ENVIRONMENTS = {"equation", "displaymath", "math", "subequations"}
@@ -1801,6 +2137,8 @@ def _normalize_latex_layout(source: str) -> str:
1801
2137
  )
1802
2138
  if "\\" not in source:
1803
2139
  return source
2140
+ # Expand \mathbb{X} tokens before the main LaTeX rewrites.
2141
+ source = _expand_mathbb(source)
1804
2142
  for pattern, replacement in _LATEX_REWRITES:
1805
2143
  source = pattern.sub(replacement, source)
1806
2144
  return _normalize_environments(source)
@@ -1823,6 +2161,14 @@ def _open_environments(text: str) -> list[str]:
1823
2161
 
1824
2162
 
1825
2163
  def _parse_single(source: str):
2164
+ # Set-theory expressions (membership, subsets, unions, quantifiers).
2165
+ # These are tried before the symbolic algebra parser so that \in, \cup, etc.
2166
+ # do not cause "Unsupported LaTeX command" errors.
2167
+ if "\\" in source:
2168
+ set_result = _try_set_theory(source)
2169
+ if set_result is not None:
2170
+ return set_result
2171
+
1826
2172
  # Standalone piecewise expressions use the current variable environment.
1827
2173
  if source.startswith("{") and source.endswith("}") and not helper._LATEX_INFIX.search(source):
1828
2174
  return _eval_piecewise_expression(source)
@@ -1928,7 +2274,17 @@ def _parse_single(source: str):
1928
2274
 
1929
2275
 
1930
2276
  def _format_result(result) -> str:
2277
+ if isinstance(result, bool):
2278
+ return "True" if result else "False"
1931
2279
  if isinstance(result, list):
2280
+ # A list returned by a set operation is displayed as {a, b, c}
2281
+ # only when every element is numeric; otherwise use the normal display.
2282
+ if all(isinstance(x, (int, float)) for x in result):
2283
+ def _fmt(x):
2284
+ if isinstance(x, float) and x.is_integer():
2285
+ return str(int(x))
2286
+ return str(x)
2287
+ return "{" + ", ".join(_fmt(x) for x in result) + "}"
1932
2288
  return _display_list(result)
1933
2289
  if not isinstance(result, dict):
1934
2290
  return str(result)