DGCV 0.4.2__tar.gz → 0.4.4__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 (82) hide show
  1. {dgcv-0.4.2/src/dgcv.egg-info → dgcv-0.4.4}/PKG-INFO +1 -1
  2. {dgcv-0.4.2 → dgcv-0.4.4}/pyproject.toml +1 -1
  3. {dgcv-0.4.2 → dgcv-0.4.4}/setup.cfg +1 -1
  4. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/__init__.py +2 -1
  5. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/_dgcv_display.py +8 -0
  6. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/_safeguards.py +33 -68
  7. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/_settings.py +51 -7
  8. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/arrays.py +227 -20
  9. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_types_and_constants.py +128 -0
  10. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_updates.py +2 -0
  11. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/dgcv_core.py +10 -24
  12. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/dgcv_formatter.py +5 -4
  13. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/eds/eds.py +46 -37
  14. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/solvers.py +3 -3
  15. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/vector_fields_and_differential_forms.py +144 -0
  16. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/vmf.py +3 -2
  17. {dgcv-0.4.2 → dgcv-0.4.4/src/dgcv.egg-info}/PKG-INFO +1 -1
  18. {dgcv-0.4.2 → dgcv-0.4.4}/LICENSE.txt +0 -0
  19. {dgcv-0.4.2 → dgcv-0.4.4}/MANIFEST.in +0 -0
  20. {dgcv-0.4.2 → dgcv-0.4.4}/README.md +0 -0
  21. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/CR_geometry.py +0 -0
  22. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/Riemannian_geometry.py +0 -0
  23. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/_config.py +0 -0
  24. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/_tables.py +0 -0
  25. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/algebras/__init__.py +0 -0
  26. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/algebras/algebras_aux.py +0 -0
  27. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/algebras/algebras_core.py +0 -0
  28. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/algebras/algebras_secondary.py +0 -0
  29. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/__init__.py +0 -0
  30. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/Orbitron-Black.ttf +0 -0
  31. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/Orbitron-Black.woff2 +0 -0
  32. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/Orbitron-Bold.ttf +0 -0
  33. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/Orbitron-Bold.woff2 +0 -0
  34. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/Orbitron-ExtraBold.ttf +0 -0
  35. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/Orbitron-ExtraBold.woff2 +0 -0
  36. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/Orbitron-Medium.ttf +0 -0
  37. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/Orbitron-Medium.woff2 +0 -0
  38. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/Orbitron-Regular.ttf +0 -0
  39. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/Orbitron-Regular.woff2 +0 -0
  40. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/Orbitron-SemiBold.ttf +0 -0
  41. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/Orbitron-SemiBold.woff2 +0 -0
  42. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/PatrickHand-Regular.ttf +0 -0
  43. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/assets/fonts/fonts.css +0 -0
  44. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/__init__.py +0 -0
  45. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_caches.py +0 -0
  46. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_calculus.py +0 -0
  47. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_cls_coercion.py +0 -0
  48. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_display.py +0 -0
  49. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_display_engine.py +0 -0
  50. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_engine.py +0 -0
  51. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_exact_arith.py +0 -0
  52. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_notebooks.py +0 -0
  53. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_numeric_engine.py +0 -0
  54. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_numeric_router.py +0 -0
  55. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_polynomials.py +0 -0
  56. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/backends/_symbolic_router.py +0 -0
  57. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/base.py +0 -0
  58. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/combinatorics.py +0 -0
  59. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/complex_structures.py +0 -0
  60. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/conversions.py +0 -0
  61. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/coordinate_maps.py +0 -0
  62. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/eds/__init__.py +0 -0
  63. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/eds/abst_vector_fields.py +0 -0
  64. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/eds/ast.py +0 -0
  65. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/eds/eds_operations.py +0 -0
  66. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/eds/eds_representations.py +0 -0
  67. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/filtered_structures.py +0 -0
  68. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/light_wrappers.py +0 -0
  69. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/matrix_ring/__init__.py +0 -0
  70. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/matrix_ring/matrix_ring.py +0 -0
  71. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/morphisms.py +0 -0
  72. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/polynomials.py +0 -0
  73. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/printing/__init__.py +0 -0
  74. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/printing/_class_printers.py +0 -0
  75. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/printing/_data_structures.py +0 -0
  76. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/printing/_string_processing.py +0 -0
  77. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/styles.py +0 -0
  78. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv/tensors.py +0 -0
  79. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv.egg-info/SOURCES.txt +0 -0
  80. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv.egg-info/dependency_links.txt +0 -0
  81. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv.egg-info/requires.txt +0 -0
  82. {dgcv-0.4.2 → dgcv-0.4.4}/src/dgcv.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dgcv
3
- Version: 0.4.2
3
+ Version: 0.4.4
4
4
  Summary: Differential Geometry with Complex Variables
5
5
  Author: David Sykes
6
6
  Author-email: David Sykes <david@realandimaginary.com>
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
5
5
  [project]
6
6
  requires-python = ">=3.9"
7
7
  name = "dgcv"
8
- version = "0.4.2"
8
+ version = "0.4.4"
9
9
  description = "Differential Geometry with Complex Variables"
10
10
  authors = [{ name = "David Sykes", email = "david@realandimaginary.com" }]
11
11
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = dgcv
3
- version = 0.4.2
3
+ version = 0.4.4
4
4
  description = A package for Differential Geometry with Complex Variables
5
5
  author = David Sykes
6
6
  author_email = david@realandimaginary.com
@@ -95,7 +95,7 @@ from .algebras.algebras_secondary import (
95
95
  subalgebra_class,
96
96
  subalgebra_element,
97
97
  )
98
- from .arrays import array_dgcv, matrix_dgcv
98
+ from .arrays import array_dgcv, assemble_block_matrix, matrix_dgcv
99
99
  from .backends import (
100
100
  expand_dgcv,
101
101
  factor_dgcv,
@@ -262,6 +262,7 @@ __all__ = [
262
262
  # From arrays
263
263
  "array_dgcv", # light-weight array representation
264
264
  "matrix_dgcv", # light-weight matrix representation
265
+ "assemble_block_matrix",
265
266
  # From backends
266
267
  "expand_dgcv",
267
268
  "factor_dgcv",
@@ -15,6 +15,7 @@ from __future__ import annotations
15
15
 
16
16
  import numbers
17
17
  import warnings
18
+ from collections.abc import Mapping
18
19
  from typing import Any
19
20
 
20
21
  from ._safeguards import check_dgcv_category, get_dgcv_category
@@ -87,6 +88,13 @@ def LaTeX(obj: Any, removeBARs: bool = False) -> str:
87
88
  if isinstance(x, set):
88
89
  elems = [_strip_display_dollars(_latex_of(e)) for e in x]
89
90
  return r"\left\{ " + ", ".join(elems) + r" \right\}"
91
+ if isinstance(x, Mapping):
92
+ elems = [
93
+ f"{_strip_display_dollars(_latex_of(k))} : "
94
+ f"{_strip_display_dollars(_latex_of(v))}"
95
+ for k, v in x.items()
96
+ ]
97
+ return r"\left\{ " + ", ".join(elems) + r" \right\}"
90
98
 
91
99
  if _is_tensorish_dgcv(x):
92
100
  if removeBARs:
@@ -20,7 +20,7 @@ from ._config import (
20
20
  get_dgcv_settings_registry,
21
21
  get_variable_registry,
22
22
  )
23
- from .vmf import clearVar
23
+ from .vmf import clearVar, vmf_lookup
24
24
 
25
25
  _passkey = "".join(random.choices(string.ascii_letters + string.digits, k=16))
26
26
  public_key = "".join(random.choices(string.ascii_letters + string.digits, k=8))
@@ -274,20 +274,12 @@ def validate_label_list(basis_labels):
274
274
 
275
275
 
276
276
  def protect_variable_relatives():
277
- variable_registry = get_variable_registry()
278
- return sum(
279
- [
280
- variable_registry["complex_variable_systems"][k]["family_names"][j]
281
- for k in variable_registry["complex_variable_systems"]
282
- for j in [2, 3]
283
- ],
284
- (),
285
- )
277
+ return get_variable_registry().get("protected_variables", {})
286
278
 
287
279
 
288
280
  def validate_label(label, remove_guardrails=False):
289
281
  """
290
- Checks if the provided variable label starts with 'BAR', and reformats it to 'anti_' if necessary.
282
+ Checks if the provided variable label starts with dgcv's designated prefix for complex variables, and reformats it to a safe fallback if necessary.
291
283
  Also checks if the label is a protected global or in 'protected_variables', unless remove_guardrails is True.
292
284
 
293
285
  Parameters
@@ -301,71 +293,44 @@ def validate_label(label, remove_guardrails=False):
301
293
  -------
302
294
  str
303
295
  The reformatted label.
304
-
305
- Raises
306
- ------
307
- ValueError
308
- If the label is a protected global name or is in 'protected_variables', unless remove_guardrails is True.
309
296
  """
310
- variable_registry = get_variable_registry()
311
-
312
- # Check if the label is a protected global, unless guardrails are removed
313
297
  if not remove_guardrails:
314
298
  if label in protected_caller_globals():
315
299
  raise ValueError(
316
300
  f"dgcv recognizes label '{label}' as a protected global name and recommends not using it as a variable name. Set remove_guardrails=True to force it."
317
301
  )
318
-
319
- # Check if the label is a child of a parent in 'protected_variables' in the variable_registry
320
302
  if label in protect_variable_relatives():
321
- # If protected, search through complex_variable_systems for the parent label
322
- if "complex_variable_systems" in variable_registry:
323
- for parent_label, parent_data in variable_registry[
324
- "complex_variable_systems"
325
- ].items():
326
- if (
327
- "variable_relatives" in parent_data
328
- and label in parent_data["variable_relatives"]
329
- ):
330
- # Found the parent label associated with the protected variable
331
- raise ValueError(
332
- f"Label '{label}' is protected within the current dgcv Variable Management Framework, "
333
- f"as it is associated with the complex variable system '{parent_label}'.\n"
334
- f"It is recommended to use the dgcv function `clearVar('{parent_label}')` to clear the protected variable "
335
- f"from the dgcv Variable Management Framework (VMF) before reassigning this label.\n"
336
- f"Or set remove_guardrails=True in the relevant dgcv object creator to force the use of this label, "
337
- f"but note this can limit available features from the VMF."
338
- )
339
-
340
- # Check if the label is in 'protected_variables' in the variable_registry
341
- if (
342
- "protected_variables" in variable_registry
343
- and label in variable_registry["protected_variables"]
344
- ):
345
- # If protected, search through complex_variable_systems for the parent label
346
- if "complex_variable_systems" in variable_registry:
347
- for parent_label, parent_data in variable_registry[
348
- "complex_variable_systems"
349
- ].items():
350
- if (
351
- "family_houses" in parent_data
352
- and label in parent_data["family_houses"]
353
- ):
354
- # Found the parent label associated with the protected variable
355
- raise ValueError(
356
- f"Label '{label}' is protected within the current dgcv Variable Management Framework, "
357
- f"as it is associated with the complex variable system '{parent_label}'.\n"
358
- f"It is recommended to use the dgcv function `clearVar('{parent_label}')` to clear the protected variable "
359
- f"from the dgcv Variable Management Framework (VMF) before reassigning this label.\n"
360
- f"Or set remove_guardrails=True in the relevant dgcv object creator to force the use of this label, "
361
- f"but note this can limit available features from the VMF."
362
- )
363
-
364
- # Check if the label starts with "BAR" and reformat if necessary
365
- if label.startswith("BAR"):
366
- reformatted_label = "anti_" + label[3:]
303
+ info = vmf_lookup(label, path=True)
304
+ system_type = info.get("type", "unregistered")
305
+ path = info.get("path", ["", "unknown"])
306
+ system_label = (
307
+ path[1]
308
+ if isinstance(path, (list, tuple)) and len(path) > 1
309
+ else "unknown"
310
+ )
311
+ if system_type == "unregistered":
312
+ raise ValueError(
313
+ f"The label {label} is currently protected from reassignment in the VMF"
314
+ "but it is not associated with any system of objects in the VMF. This is"
315
+ "likely a bug in `dgcv`. Please report it to dgcv maintainers."
316
+ )
317
+ raise ValueError(
318
+ f"The label {label} is currently protected from reassignment in the VMF"
319
+ f"It's associated system is: {system_label}"
320
+ f"It's associated system type is: {system_type}"
321
+ )
322
+
323
+ dgcvSR = get_dgcv_settings_registry()
324
+ pref, fallback = (
325
+ dgcvSR.get("conjugate_prefix", "_c_"),
326
+ dgcvSR.get("fallback_conjugate_prefix", "anti_"),
327
+ )
328
+ if label.startswith(pref):
329
+ reformatted_label = fallback + label[len(pref) :]
367
330
  warnings.warn(
368
- f"Label '{label}' starts with 'BAR', which has special meaning in dgcv. It has been automatically reformatted to '{reformatted_label}'."
331
+ f"Label '{label}' starts with {pref}, which is reserved by the `conjugate_prefix`"
332
+ "value currently set in dgcv settings. It has been automatically reformatted to "
333
+ f"'{reformatted_label}'."
369
334
  )
370
335
  else:
371
336
  reformatted_label = label
@@ -14,11 +14,11 @@ License:
14
14
  from __future__ import annotations
15
15
 
16
16
  import warnings
17
- from typing import Literal, Optional
17
+ from typing import Literal
18
18
 
19
19
  from dgcv import __version__
20
20
 
21
- from ._config import get_dgcv_settings_registry, vlp
21
+ from ._config import get_dgcv_settings_registry, get_variable_registry, vlp
22
22
  from .backends._cls_coercion import attach_sympy_hook, detach_sympy_hook
23
23
  from .backends._engine import (
24
24
  invalidate_engine_cache,
@@ -64,21 +64,23 @@ def _infer_vscode_jupyter():
64
64
 
65
65
 
66
66
  def set_dgcv_settings(
67
- theme: Optional[str] = None,
67
+ theme: str | None = None,
68
68
  format_displays: bool | None = None,
69
69
  use_latex: bool | None = None,
70
- print_style: Optional[Literal["readable", "literal"]] = None,
71
- version_specific_defaults: Optional[str] = None,
70
+ print_style: Literal["readable", "literal"] | None = None,
71
+ version_specific_defaults: str | None = None,
72
72
  ask_before_overwriting_objects_in_vmf: bool | None = None,
73
73
  forgo_warnings: bool | None = None,
74
- default_engine: Optional[Literal["sage", "sympy", "dgcv_custom"]] = None,
74
+ default_engine: Literal["sage", "sympy", "dgcv_custom"] | None = None,
75
75
  verbose_label_printing: bool | None = None,
76
76
  pass_solve_requests_to_symbolic_engine: bool | None = None,
77
77
  DEBUG: bool | None = None,
78
78
  extra_support_for_math_in_tables: bool | None = None,
79
- preferred_variable_format: Optional[Literal["complex", "real"]] = None,
79
+ preferred_variable_format: Literal["complex", "real"] | None = None,
80
80
  use_numeric_methods: bool | None = None,
81
81
  force_rich_display: bool | None = None,
82
+ conjugation_prefix: str | None = None,
83
+ fallback_conjugate_prefix: str | None = None,
82
84
  **kwargs,
83
85
  ):
84
86
  dgcvSR = get_dgcv_settings_registry()
@@ -164,6 +166,41 @@ def set_dgcv_settings(
164
166
  dgcv_init_printing()
165
167
  return
166
168
 
169
+ if k == "conjugation_prefix":
170
+ if len(get_variable_registry().get("complex_variable_systems", {})) > 0:
171
+ warnings.warn(
172
+ "The default `conjugation_prefix` cannot be changed while complex"
173
+ "coordinate systems exist in the VMF. Clear such systems from the"
174
+ "VMF first. Recommend usage: set `conjugation_prefix` only once at"
175
+ "the start of a session with dgcv."
176
+ )
177
+ return
178
+ if v == get_dgcv_settings_registry().get("fallback_conjugate_prefix"):
179
+ newfallback = "anti_" if v != "anti_" else "BAR"
180
+ warnings.warn(
181
+ "The requested `conjugation_prefix` is already assigned to `fallback_conjugate_prefix`."
182
+ f"To free the assignement, `fallback_conjugate_prefix` has been changed to {newfallback}."
183
+ )
184
+ dgcvSR["fallback_conjugate_prefix"] = newfallback
185
+ dgcvSR[k] = v
186
+ if k == "fallback_conjugate_prefix":
187
+ if len(get_variable_registry().get("complex_variable_systems", {})) > 0:
188
+ warnings.warn(
189
+ "The default `fallback_conjugate_prefix` cannot be changed while complex"
190
+ "coordinate systems exist in the VMF. Clear such systems from the"
191
+ "VMF first. Recommend usage: set `fallback_conjugate_prefix` only once"
192
+ "at the start of a session with dgcv."
193
+ )
194
+ return
195
+ if v == get_dgcv_settings_registry.get("conjugate_prefix"):
196
+ newfallback = "BAR" if v != "BAR" else "Banti_R"
197
+ warnings.warn(
198
+ "The requested `fallback_conjugate_prefix` is already assigned to `conjugate_prefix`."
199
+ f"To free the assignement, `conjugate_prefix` has been changed to {newfallback}."
200
+ )
201
+ dgcvSR["conjugate_prefix"] = newfallback
202
+ dgcvSR[k] = v
203
+
167
204
  if k == "extra_support_for_math_in_tables":
168
205
  dgcvSR[k] = _resolve_vscode_patch_value(v)
169
206
  return
@@ -296,6 +333,7 @@ def view_dgcv_settings():
296
333
  "numeric_error_thresholds",
297
334
  "default_numeric_engine",
298
335
  "DEBUG",
336
+ "fallback_conjugate_prefix",
299
337
  }
300
338
  items = [(k, settings[k]) for k in settings.keys() if k not in hidden]
301
339
  if settings.get("use_numeric_methods", False):
@@ -318,6 +356,11 @@ def view_dgcv_settings():
318
356
  settings.get("numeric_error_thresholds", {}).get("policy"),
319
357
  )
320
358
  )
359
+ if settings.get("fallback_conjugate_prefix", False):
360
+ if settings.get("fallback_conjugate_prefix") != "anti_":
361
+ items.append(
362
+ ("fallback_conjugate_prefix", settings.get("fallback_conjugate_prefix"))
363
+ )
321
364
  if not items:
322
365
  print("dgcv settings registry is empty.")
323
366
  return
@@ -354,6 +397,7 @@ def reset_dgcv_settings():
354
397
  "verbose_label_printing": False,
355
398
  "VLP": vlp,
356
399
  "conjugation_prefix": "BAR",
400
+ "fallback_conjugate_prefix": "anti_",
357
401
  "preferred_variable_format": "complex",
358
402
  "pass_solve_requests_to_symbolic_engine": True,
359
403
  "extra_support_for_math_in_tables": _vscodepatch,
@@ -13,7 +13,12 @@ License:
13
13
  # -----------------------------------------------------------------------------
14
14
  from numbers import Integral
15
15
 
16
- from ._safeguards import check_dgcv_category, create_key, retrieve_passkey
16
+ from ._safeguards import (
17
+ check_dgcv_category,
18
+ create_key,
19
+ query_dgcv_categories,
20
+ retrieve_passkey,
21
+ )
17
22
  from .backends._engine import engine_kind, engine_module
18
23
  from .backends._exact_arith import exact_reciprocal
19
24
  from .backends._symbolic_router import (
@@ -22,11 +27,11 @@ from .backends._symbolic_router import (
22
27
  get_free_symbols,
23
28
  simplify,
24
29
  )
25
- from .backends._types_and_constants import fast_scalar_types, symbol
30
+ from .backends._types_and_constants import expr_numeric_types, fast_scalar_types, symbol
26
31
  from .base import dgcv_class
27
32
  from .printing import array_latex_helper, array_VS_printer
28
33
 
29
- __all__ = ["array_dgcv", "matrix_dgcv"]
34
+ __all__ = ["array_dgcv", "matrix_dgcv", "assemble_block_matrix"]
30
35
 
31
36
 
32
37
  # -----------------------------------------------------------------------------
@@ -54,32 +59,95 @@ class array_dgcv(dgcv_class):
54
59
 
55
60
  def __init__(self, array_data, *, shape=None):
56
61
  if shape is not None:
57
- if not isinstance(shape, tuple) or not all(
58
- isinstance(s, Integral) and s >= 0 for s in shape
59
- ):
60
- raise TypeError("shape must be a tuple of non-negative ints")
62
+ if isinstance(shape, (list, tuple)):
63
+ shape = tuple(shape)
64
+ else:
65
+ raise TypeError(
66
+ "shape must be tuple-like (list/tuple) of non-negative ints"
67
+ )
68
+
69
+ if not all(isinstance(s, Integral) and s >= 0 for s in shape):
70
+ raise TypeError(
71
+ "shape must be tuple-like (list/tuple) of non-negative ints"
72
+ )
73
+
61
74
  self.shape = shape
62
75
 
63
76
  self._data, self.shape = self._normalize(array_data)
64
77
  self.ndim = len(self.shape)
65
78
  self._dgcv_class_check = retrieve_passkey()
66
79
 
67
- def __str__(self):
68
- return array_VS_printer(self)
69
-
70
- def _latex(self, printer=None, raw=True, **kwargs):
71
- s = array_latex_helper(self, **kwargs)
72
- return s if raw else f"$\\displaystyle {s}$"
73
-
74
- def _repr_latex_(self, raw=False, **kwargs):
75
- return self._latex(**kwargs)
76
-
77
80
  def _normalize(self, array_data):
78
81
  if isinstance(array_data, dict):
79
82
  shp = getattr(self, "shape", None)
80
83
  if not isinstance(shp, tuple):
81
84
  raise TypeError("dict input requires shape=... in array_dgcv(...)")
82
- return dict(array_data), tuple(shp)
85
+
86
+ flat = {}
87
+ for k, v in array_data.items():
88
+ if isinstance(k, tuple):
89
+ idx = _spool(k, shp)
90
+ else:
91
+ idx = k
92
+
93
+ if v is None:
94
+ flat[idx] = None
95
+ continue
96
+ try:
97
+ if _scalar_is_zero(v):
98
+ continue
99
+ except Exception:
100
+ pass
101
+
102
+ flat[idx] = v
103
+
104
+ return flat, tuple(shp)
105
+ if callable(array_data):
106
+ shp = getattr(self, "shape", None)
107
+ if not isinstance(shp, tuple):
108
+ raise TypeError(
109
+ "callable entry rule requires shape=... in array_dgcv(...)"
110
+ )
111
+ flat = {}
112
+ if not shp:
113
+ v = array_data()
114
+ if v is None:
115
+ flat[0] = None
116
+ else:
117
+ try:
118
+ if not _scalar_is_zero(v):
119
+ flat[0] = v
120
+ except Exception:
121
+ flat[0] = v
122
+ return flat, tuple(shp)
123
+
124
+ def _walk(prefix, rest):
125
+ if not rest:
126
+ try:
127
+ v = array_data(*prefix)
128
+ except TypeError:
129
+ v = array_data(prefix)
130
+
131
+ idx = _spool(prefix, shp)
132
+
133
+ if v is None:
134
+ flat[idx] = None
135
+ return
136
+
137
+ try:
138
+ if _scalar_is_zero(v):
139
+ return
140
+ except Exception:
141
+ pass
142
+
143
+ flat[idx] = v
144
+ return
145
+
146
+ for i in range(rest[0]):
147
+ _walk(prefix + (i,), rest[1:])
148
+
149
+ _walk((), shp)
150
+ return flat, tuple(shp)
83
151
 
84
152
  if isinstance(array_data, (list, tuple)):
85
153
  shape = self._infer_shape(array_data)
@@ -100,6 +168,7 @@ class array_dgcv(dgcv_class):
100
168
  for j in range(cols):
101
169
  flat[base + j] = array_data[i, j]
102
170
  return flat, shape
171
+
103
172
  nrows = getattr(array_data, "nrows", None)
104
173
  ncols = getattr(array_data, "ncols", None)
105
174
  if callable(nrows) and callable(ncols):
@@ -115,6 +184,16 @@ class array_dgcv(dgcv_class):
115
184
 
116
185
  raise TypeError("Unsupported array_data type")
117
186
 
187
+ def __str__(self):
188
+ return array_VS_printer(self)
189
+
190
+ def _latex(self, printer=None, raw=True, **kwargs):
191
+ s = array_latex_helper(self, **kwargs)
192
+ return s if raw else f"$\\displaystyle {s}$"
193
+
194
+ def _repr_latex_(self, raw=False, **kwargs):
195
+ return self._latex(**kwargs)
196
+
118
197
  def _infer_shape(self, data):
119
198
  shape = []
120
199
  cur = data
@@ -269,8 +348,9 @@ class matrix_dgcv(array_dgcv):
269
348
 
270
349
  _dgcv_categories = {"matrix"}
271
350
 
272
- def __init__(self, array_data):
273
- super().__init__(array_data)
351
+ def __init__(self, array_data, *, shape=None):
352
+ super().__init__(array_data, shape=shape)
353
+
274
354
  if self.ndim == 1:
275
355
  n = self.shape[0]
276
356
  new_data = {}
@@ -282,8 +362,10 @@ class matrix_dgcv(array_dgcv):
282
362
  self._data = new_data
283
363
  self.shape = (n, 1)
284
364
  self.ndim = 2
365
+
285
366
  if self.ndim != 2:
286
367
  raise ValueError("matrix_dgcv requires 2-dimensional data")
368
+
287
369
  self._dgcv_categories = {"matrix"}
288
370
  self._engine_representation = dict()
289
371
 
@@ -341,6 +423,26 @@ class matrix_dgcv(array_dgcv):
341
423
  out._data[_spool((i, i), out.shape)] = one
342
424
  return out
343
425
 
426
+ @classmethod
427
+ def padded_identity(cls, nrows, ncols, one=1, zero=0):
428
+ _validate_pos_int(nrows, "nrows")
429
+ _validate_pos_int(ncols, "ncols")
430
+
431
+ out = cls.__new__(cls)
432
+ out._dgcv_class_check = retrieve_passkey()
433
+ out._dgcv_categories = {"matrix"}
434
+ out.shape = (int(nrows), int(ncols))
435
+ out.ndim = 2
436
+ out._data = {}
437
+
438
+ d = min(out.shape[0], out.shape[1])
439
+ if one != zero:
440
+ for i in range(d):
441
+ out._data[_spool((i, i), out.shape)] = one
442
+
443
+ out._engine_representation = dict()
444
+ return out
445
+
344
446
  def transpose(self):
345
447
  def _entry_transpose(x):
346
448
  if x is None:
@@ -1181,6 +1283,111 @@ class matrix_dgcv(array_dgcv):
1181
1283
  return out
1182
1284
 
1183
1285
 
1286
+ def assemble_block_matrix(blocks):
1287
+ B = _as_seq(blocks, "blocks")
1288
+ if B is None:
1289
+ B = []
1290
+
1291
+ rows = []
1292
+ max_cols = 0
1293
+ for r in B:
1294
+ rr = _as_seq(r, "block row")
1295
+ if rr is None:
1296
+ rr = []
1297
+ rr = list(rr)
1298
+ rows.append(rr)
1299
+ if len(rr) > max_cols:
1300
+ max_cols = len(rr)
1301
+
1302
+ for rr in rows:
1303
+ if len(rr) < max_cols:
1304
+ rr.extend([0] * (max_cols - len(rr)))
1305
+
1306
+ n_block_rows = len(rows)
1307
+ n_block_cols = max_cols
1308
+
1309
+ def _is_matrix(x):
1310
+ try:
1311
+ return bool(query_dgcv_categories(x, {"matrix"}))
1312
+ except Exception:
1313
+ return False
1314
+
1315
+ def _is_scalar(x):
1316
+ try:
1317
+ return isinstance(x, expr_numeric_types())
1318
+ except Exception:
1319
+ return False
1320
+
1321
+ row_heights = [None] * n_block_rows
1322
+ col_widths = [None] * n_block_cols
1323
+
1324
+ for i in range(n_block_rows):
1325
+ for j in range(n_block_cols):
1326
+ x = rows[i][j]
1327
+
1328
+ if _is_matrix(x):
1329
+ m = int(getattr(x, "nrows"))
1330
+ n = int(getattr(x, "ncols"))
1331
+
1332
+ rh = row_heights[i]
1333
+ if rh is None:
1334
+ row_heights[i] = m
1335
+ elif rh != m:
1336
+ raise ValueError(
1337
+ f"Incompatible block-row heights in row {i}: got {rh} and {m}."
1338
+ )
1339
+
1340
+ cw = col_widths[j]
1341
+ if cw is None:
1342
+ col_widths[j] = n
1343
+ elif cw != n:
1344
+ raise ValueError(
1345
+ f"Incompatible block-column widths in col {j}: got {cw} and {n}."
1346
+ )
1347
+
1348
+ elif _is_scalar(x):
1349
+ continue
1350
+ else:
1351
+ raise TypeError(
1352
+ "Block entries must satisfy "
1353
+ "isinstance(x, expr_numeric_types()) or query_dgcv_categories(x, {'matrix'})."
1354
+ )
1355
+
1356
+ for i in range(n_block_rows):
1357
+ if row_heights[i] is None:
1358
+ row_heights[i] = 1
1359
+ for j in range(n_block_cols):
1360
+ if col_widths[j] is None:
1361
+ col_widths[j] = 1
1362
+
1363
+ for i in range(n_block_rows):
1364
+ for j in range(n_block_cols):
1365
+ x = rows[i][j]
1366
+ if _is_matrix(x):
1367
+ continue
1368
+ m = row_heights[i]
1369
+ n = col_widths[j]
1370
+ rows[i][j] = x * matrix_dgcv.padded_identity(m, n)
1371
+
1372
+ total_m = sum(row_heights)
1373
+ total_n = sum(col_widths)
1374
+
1375
+ out_data = {}
1376
+ row_off = 0
1377
+ for i in range(n_block_rows):
1378
+ col_off = 0
1379
+ for j in range(n_block_cols):
1380
+ blk = rows[i][j]
1381
+ for (ii, jj), v in blk.iter_nonzero_items(
1382
+ include_zeros=False, include_none=False
1383
+ ):
1384
+ out_data[(row_off + ii, col_off + jj)] = v
1385
+ col_off += col_widths[j]
1386
+ row_off += row_heights[i]
1387
+
1388
+ return matrix_dgcv(out_data, shape=(total_m, total_n))
1389
+
1390
+
1184
1391
  def _validate_pos_int(n, name="n"):
1185
1392
  if not isinstance(n, Integral) or n < 0:
1186
1393
  raise TypeError(f"{name} must be a nonnegative integer, got {n!r}")