mapFolding 0.12.1__py3-none-any.whl → 0.12.3__py3-none-any.whl

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 (37) hide show
  1. mapFolding/__init__.py +46 -20
  2. mapFolding/_theSSOT.py +81 -0
  3. mapFolding/_theTypes.py +148 -0
  4. mapFolding/basecamp.py +62 -47
  5. mapFolding/beDRY.py +100 -73
  6. mapFolding/dataBaskets.py +226 -31
  7. mapFolding/filesystemToolkit.py +161 -107
  8. mapFolding/oeis.py +388 -174
  9. mapFolding/reference/flattened.py +1 -1
  10. mapFolding/someAssemblyRequired/RecipeJob.py +146 -20
  11. mapFolding/someAssemblyRequired/__init__.py +60 -38
  12. mapFolding/someAssemblyRequired/_toolIfThis.py +125 -35
  13. mapFolding/someAssemblyRequired/_toolkitContainers.py +125 -44
  14. mapFolding/someAssemblyRequired/getLLVMforNoReason.py +35 -26
  15. mapFolding/someAssemblyRequired/infoBooth.py +37 -2
  16. mapFolding/someAssemblyRequired/makeAllModules.py +785 -0
  17. mapFolding/someAssemblyRequired/makeJobTheorem2Numba.py +161 -74
  18. mapFolding/someAssemblyRequired/toolkitNumba.py +218 -36
  19. mapFolding/someAssemblyRequired/transformationTools.py +125 -58
  20. mapfolding-0.12.3.dist-info/METADATA +163 -0
  21. mapfolding-0.12.3.dist-info/RECORD +53 -0
  22. {mapfolding-0.12.1.dist-info → mapfolding-0.12.3.dist-info}/WHEEL +1 -1
  23. tests/__init__.py +28 -44
  24. tests/conftest.py +66 -61
  25. tests/test_computations.py +64 -89
  26. tests/test_filesystem.py +25 -1
  27. tests/test_oeis.py +37 -7
  28. tests/test_other.py +29 -2
  29. tests/test_tasks.py +30 -2
  30. mapFolding/datatypes.py +0 -18
  31. mapFolding/someAssemblyRequired/Z0Z_makeAllModules.py +0 -433
  32. mapFolding/theSSOT.py +0 -34
  33. mapfolding-0.12.1.dist-info/METADATA +0 -184
  34. mapfolding-0.12.1.dist-info/RECORD +0 -53
  35. {mapfolding-0.12.1.dist-info → mapfolding-0.12.3.dist-info}/entry_points.txt +0 -0
  36. {mapfolding-0.12.1.dist-info → mapfolding-0.12.3.dist-info}/licenses/LICENSE +0 -0
  37. {mapfolding-0.12.1.dist-info → mapfolding-0.12.3.dist-info}/top_level.txt +0 -0
mapFolding/oeis.py CHANGED
@@ -1,42 +1,59 @@
1
1
  """
2
- Interface to The Online Encyclopedia of Integer Sequences (OEIS) for map folding sequences.
3
-
4
- This module provides a comprehensive interface for accessing and utilizing integer sequences from the OEIS that relate
5
- to map folding problems. It serves as the bridge between mathematical sequence definitions and the computational
6
- algorithm, implementing:
7
-
8
- 1. Retrieval of sequence data from OEIS with local caching for performance optimization.
9
- 2. Mapping of sequence indices to corresponding map shapes based on sequence definitions.
10
- 3. Command-line and programmatic interfaces for sequence lookups and validation.
11
- 4. Computation of sequence terms not available in the OEIS database.
12
-
13
- The module maintains a registry of implemented OEIS sequences (A001415-A001418, A195646) with their metadata, known
14
- values, and conversion functions between sequence indices and map dimensions. This allows the package to validate
15
- results against established mathematical literature while also extending sequences beyond their currently known terms.
16
-
17
- Each sequence is carefully mapped to its corresponding map folding problem, enabling seamless integration between the
18
- mathematical definition in OEIS and the computational implementation in the package.
2
+ Mathematical validation and discovery through OEIS integration.
3
+
4
+ (AI generated docstring)
5
+
6
+ Complementing the unified computational interface, this module extends the map
7
+ folding ecosystem into the broader mathematical community through comprehensive
8
+ integration with the Online Encyclopedia of Integer Sequences (OEIS). This bridge
9
+ enables validation of computational results against established mathematical
10
+ knowledge while supporting the discovery of new sequence values through the
11
+ sophisticated computational pipeline.
12
+
13
+ The integration provides multiple pathways for mathematical verification: direct
14
+ computation of OEIS sequences using the complete algorithmic implementation,
15
+ cached access to published sequence data for rapid validation, and research
16
+ support for extending known sequences through new computational discoveries.
17
+ The module handles sequence families ranging from simple strip folding to
18
+ complex multi-dimensional hypercube problems.
19
+
20
+ Through intelligent caching and optimized lookup mechanisms, this module ensures
21
+ that the computational power developed through the foundational layers can contribute
22
+ meaningfully to mathematical research. Whether validating results, avoiding
23
+ redundant computation, or extending mathematical knowledge, this integration
24
+ completes the journey from configuration foundation to mathematical discovery.
19
25
  """
26
+
20
27
  from collections.abc import Callable
21
- from datetime import datetime, timedelta
28
+ from datetime import datetime, timedelta, UTC
22
29
  from functools import cache
23
- from mapFolding import countFolds, packageSettings, TypedDict
30
+ from hunterMakesPy import writeStringToHere
31
+ from mapFolding import countFolds, packageSettings
24
32
  from pathlib import Path
25
- from typing import Any, Final
26
- from urllib.parse import urlparse
27
- from Z0Z_tools import writeStringToHere
33
+ from typing import Any, Final, TypedDict
34
+ from urllib.request import urlopen
28
35
  import argparse
29
36
  import random
30
37
  import sys
31
38
  import time
32
- import urllib.request
33
39
  import warnings
34
40
 
35
41
  cacheDays = 30
42
+ """Number of days to retain cached OEIS data before refreshing from the online source."""
36
43
 
37
44
  pathCache: Path = packageSettings.pathPackage / ".cache"
45
+ """Local directory path for storing cached OEIS sequence data and metadata."""
38
46
 
39
47
  class SettingsOEIS(TypedDict):
48
+ """Complete configuration settings for a single OEIS sequence implementation.
49
+
50
+ (AI generated docstring)
51
+
52
+ This `TypedDict` defines the structure for storing all metadata, known values, and operational parameters
53
+ needed to work with an OEIS sequence within the map folding context.
54
+
55
+ """
56
+
40
57
  description: str
41
58
  getMapShape: Callable[[int], tuple[int, ...]]
42
59
  offset: int
@@ -47,6 +64,15 @@ class SettingsOEIS(TypedDict):
47
64
  valueUnknown: int
48
65
 
49
66
  class SettingsOEIShardcodedValues(TypedDict):
67
+ """Hardcoded configuration values for OEIS sequences defined within the module.
68
+
69
+ (AI generated docstring)
70
+
71
+ This `TypedDict` contains the static configuration data that is embedded in the source code
72
+ rather than retrieved from external sources.
73
+
74
+ """
75
+
50
76
  getMapShape: Callable[[int], tuple[int, ...]]
51
77
  valuesBenchmark: list[int]
52
78
  valuesTestParallelization: list[int]
@@ -57,25 +83,25 @@ settingsOEIShardcodedValues: dict[str, SettingsOEIShardcodedValues] = {
57
83
  'getMapShape': lambda n: tuple(sorted([1, n])),
58
84
  'valuesBenchmark': [14],
59
85
  'valuesTestParallelization': [*range(3, 7)],
60
- 'valuesTestValidation': [random.randint(2, 9)],
86
+ 'valuesTestValidation': [random.randint(2, 9)], # noqa: S311
61
87
  },
62
88
  'A001415': {
63
89
  'getMapShape': lambda n: tuple(sorted([2, n])),
64
90
  'valuesBenchmark': [14],
65
91
  'valuesTestParallelization': [*range(3, 7)],
66
- 'valuesTestValidation': [random.randint(2, 9)],
92
+ 'valuesTestValidation': [random.randint(2, 9)], # noqa: S311
67
93
  },
68
94
  'A001416': {
69
95
  'getMapShape': lambda n: tuple(sorted([3, n])),
70
96
  'valuesBenchmark': [9],
71
97
  'valuesTestParallelization': [*range(3, 5)],
72
- 'valuesTestValidation': [random.randint(2, 6)],
98
+ 'valuesTestValidation': [random.randint(2, 6)], # noqa: S311
73
99
  },
74
100
  'A001417': {
75
101
  'getMapShape': lambda n: tuple(2 for _dimension in range(n)),
76
102
  'valuesBenchmark': [6],
77
103
  'valuesTestParallelization': [*range(2, 4)],
78
- 'valuesTestValidation': [random.randint(2, 4)],
104
+ 'valuesTestValidation': [random.randint(2, 4)], # noqa: S311
79
105
  },
80
106
  'A195646': {
81
107
  'getMapShape': lambda n: tuple(3 for _dimension in range(n)),
@@ -87,28 +113,43 @@ settingsOEIShardcodedValues: dict[str, SettingsOEIShardcodedValues] = {
87
113
  'getMapShape': lambda n: (n, n),
88
114
  'valuesBenchmark': [5],
89
115
  'valuesTestParallelization': [*range(2, 4)],
90
- 'valuesTestValidation': [random.randint(2, 4)],
116
+ 'valuesTestValidation': [random.randint(2, 4)], # noqa: S311
91
117
  },
92
118
  }
119
+ """
120
+ Registry of hardcoded OEIS sequence configurations implemented in this module.
93
121
 
94
- oeisIDsImplemented: Final[list[str]] = sorted([oeisID.upper().strip() for oeisID in settingsOEIShardcodedValues.keys()])
122
+ Each key is a standardized OEIS sequence identifier (e.g., 'A001415'), and each value contains
123
+ the static configuration needed to work with that sequence, including the mapping function from
124
+ sequence index to map shape and various test parameter sets.
125
+ """
126
+
127
+ oeisIDsImplemented: Final[list[str]] = sorted([oeisID.upper().strip() for oeisID in settingsOEIShardcodedValues])
95
128
  """Directly implemented OEIS IDs; standardized, e.g., 'A001415'."""
96
129
 
97
130
  def validateOEISid(oeisIDcandidate: str) -> str:
98
- """
99
- Validates an OEIS sequence ID against implemented sequences.
131
+ """Validate an OEIS sequence ID against implemented sequences.
132
+
133
+ (AI generated docstring)
100
134
 
101
135
  If the provided ID is recognized within the application's implemented OEIS sequences, the function returns the
102
136
  verified ID in uppercase. Otherwise, a KeyError is raised indicating that the sequence is not directly supported.
103
137
 
104
- Parameters:
105
- oeisIDcandidate: The OEIS sequence identifier to validate.
138
+ Parameters
139
+ ----------
140
+ oeisIDcandidate : str
141
+ The OEIS sequence identifier to validate.
106
142
 
107
- Returns:
108
- oeisID: The validated and possibly modified OEIS sequence ID, if recognized.
143
+ Returns
144
+ -------
145
+ str
146
+ The validated and possibly modified OEIS sequence ID, if recognized.
147
+
148
+ Raises
149
+ ------
150
+ KeyError
151
+ If the provided sequence ID is not directly implemented.
109
152
 
110
- Raises:
111
- KeyError: If the provided sequence ID is not directly implemented.
112
153
  """
113
154
  if oeisIDcandidate in oeisIDsImplemented:
114
155
  return oeisIDcandidate
@@ -117,31 +158,59 @@ def validateOEISid(oeisIDcandidate: str) -> str:
117
158
  if oeisIDcleaned in oeisIDsImplemented:
118
159
  return oeisIDcleaned
119
160
  else:
120
- raise KeyError(
161
+ message = (
121
162
  f"OEIS ID {oeisIDcandidate} is not directly implemented.\n"
122
163
  f"Available sequences:\n{_formatOEISsequenceInfo()}"
123
164
  )
165
+ raise KeyError(
166
+ message
167
+ )
124
168
 
125
169
  def getFilenameOEISbFile(oeisID: str) -> str:
170
+ """Generate the filename for an OEIS b-file given a sequence ID.
171
+
172
+ (AI generated docstring)
173
+
174
+ OEIS b-files contain sequence values in a standardized format and follow the naming convention
175
+ 'b{sequence_number}.txt', where the sequence number excludes the 'A' prefix.
176
+
177
+ Parameters
178
+ ----------
179
+ oeisID : str
180
+ The OEIS sequence identifier to convert to a b-file filename.
181
+
182
+ Returns
183
+ -------
184
+ str
185
+ The corresponding b-file filename for the given sequence ID.
186
+
187
+ """
126
188
  oeisID = validateOEISid(oeisID)
127
189
  return f"b{oeisID[1:]}.txt"
128
190
 
129
- def _parseBFileOEIS(OEISbFile: str, oeisID: str) -> dict[int, int]:
130
- """
131
- Parses the content of an OEIS b-file for a given sequence ID.
132
-
133
- This function processes a multiline string representing an OEIS b-file and creates a dictionary mapping integer
134
- indices to their corresponding sequence values. The first line of the b-file is expected to contain a comment that
135
- matches the given sequence ID. If it does not match, a ValueError is raised.
136
-
137
- Parameters:
138
- OEISbFile: A multiline string representing an OEIS b-file. oeisID: The expected OEIS sequence identifier.
139
- Returns:
140
- OEISsequence: A dictionary where each key is an integer index `n` and each value is the sequence value `a(n)`
141
- corresponding to that index.
142
- Raises:
143
- ValueError: If the first line of the file does not indicate the expected sequence ID or if the content format is
144
- invalid.
191
+ def _parseBFileOEIS(OEISbFile: str) -> dict[int, int]:
192
+ """Parse the content of an OEIS b-file into a sequence dictionary.
193
+
194
+ (AI generated docstring)
195
+
196
+ OEIS b-files contain sequence data in a standardized two-column format where each line represents
197
+ an index-value pair. Comment lines beginning with '#' are ignored during parsing.
198
+
199
+ Parameters
200
+ ----------
201
+ OEISbFile : str
202
+ A multiline string representing the content of an OEIS b-file.
203
+
204
+ Returns
205
+ -------
206
+ OEISsequence : dict[int, int]
207
+ A dictionary mapping sequence indices to their corresponding values.
208
+
209
+ Raises
210
+ ------
211
+ ValueError
212
+ If the file content format is invalid or cannot be parsed.
213
+
145
214
  """
146
215
  bFileLines: list[str] = OEISbFile.strip().splitlines()
147
216
 
@@ -154,96 +223,120 @@ def _parseBFileOEIS(OEISbFile: str, oeisID: str) -> dict[int, int]:
154
223
  return OEISsequence
155
224
 
156
225
  def getOEISofficial(pathFilenameCache: Path, url: str) -> None | str:
157
- """
158
- Retrieve OEIS sequence data from cache or online source.
226
+ """Retrieve OEIS sequence data from cache or online source with intelligent caching.
227
+
228
+ (AI generated docstring)
159
229
 
160
- This function implements a caching strategy for OEIS sequence data, first checking if a local cached copy exists and
161
- is not expired. If a valid cache exists, it returns the cached content; otherwise, it fetches the data from the OEIS
162
- website and writes it to the cache for future use.
230
+ This function implements a caching strategy that prioritizes local cached data when it exists and
231
+ has not expired. Fresh data is retrieved from the OEIS website when the cache is stale or missing,
232
+ and the cache is updated for future use.
163
233
 
164
- Parameters:
165
- pathFilenameCache: Path to the local cache file. url: URL to retrieve the OEIS sequence data from if cache is
166
- invalid or missing.
234
+ Parameters
235
+ ----------
236
+ pathFilenameCache : Path
237
+ Path to the local cache file for storing retrieved data.
238
+ url : str
239
+ URL to retrieve the OEIS sequence data from if cache is invalid or missing.
167
240
 
168
- Returns:
169
- oeisInformation: The retrieved OEIS sequence information as a string, or None if the information could not be
170
- retrieved.
241
+ Returns
242
+ -------
243
+ oeisInformation : str | None
244
+ The retrieved OEIS sequence information as a string, or `None` if retrieval failed.
245
+
246
+ Notes
247
+ -----
248
+ Cache expiration is controlled by the module-level `cacheDays` variable. The function validates
249
+ URL schemes and issues warnings for failed retrievals.
171
250
 
172
- Notes:
173
- The cache expiration period is controlled by the global `cacheDays` variable. If the function fails to retrieve
174
- data from both cache and online source, it will return None and issue a warning.
175
251
  """
176
252
  tryCache: bool = False
177
253
  if pathFilenameCache.exists():
178
- fileAge: timedelta = datetime.now() - datetime.fromtimestamp(pathFilenameCache.stat().st_mtime)
254
+ fileAge: timedelta = datetime.now(tz=UTC) - datetime.fromtimestamp(pathFilenameCache.stat().st_mtime, tz=UTC)
179
255
  tryCache = fileAge < timedelta(days=cacheDays)
180
256
 
181
257
  oeisInformation: str | None = None
182
258
  if tryCache:
183
259
  try:
184
- oeisInformation = pathFilenameCache.read_text()
260
+ oeisInformation = pathFilenameCache.read_text(encoding="utf-8")
185
261
  except OSError:
186
262
  tryCache = False
187
263
 
188
264
  if not tryCache:
189
- parsedUrl = urlparse(url)
190
- if parsedUrl.scheme not in ("http", "https"):
191
- warnings.warn(f"I received the URL '{url}', but only 'http' and 'https' schemes are permitted.")
192
- else:
193
- httpResponse = urllib.request.urlopen(url)
194
- oeisInformationRaw = httpResponse.read().decode('utf-8')
195
- oeisInformation = str(oeisInformationRaw)
196
- writeStringToHere(oeisInformation, pathFilenameCache)
265
+ if not url.startswith(("http:", "https:")):
266
+ raise ValueError("URL must start with 'http:' or 'https:'")
267
+ with urlopen(url) as response:
268
+ oeisInformationRaw = response.read().decode('utf-8')
269
+ oeisInformation = str(oeisInformationRaw)
270
+ writeStringToHere(oeisInformation, pathFilenameCache)
197
271
 
198
272
  if not oeisInformation:
199
- warnings.warn(f"Failed to retrieve OEIS sequence information for {pathFilenameCache.stem}.")
273
+ warnings.warn(f"Failed to retrieve OEIS sequence information for {pathFilenameCache.stem}.", stacklevel=2)
200
274
 
201
275
  return oeisInformation
202
276
 
203
277
  def getOEISidValues(oeisID: str) -> dict[int, int]:
204
- """
205
- Retrieves the specified OEIS sequence as a dictionary mapping integer indices to their corresponding values.
206
-
207
- This function checks for a cached local copy of the sequence data, using it if it has not expired. Otherwise, it
208
- fetches the sequence data from the OEIS website and writes it to the cache. The parsed data is returned as a
209
- dictionary mapping each index to its sequence value.
210
-
211
- Parameters:
212
- oeisID: The identifier of the OEIS sequence to retrieve.
213
- Returns:
214
- OEISsequence: A dictionary where each key is an integer index, `n`, and each value is the corresponding `a(n)`
215
- from the OEIS entry.
216
- Raises:
217
- ValueError: If the cached or downloaded file format is invalid. IOError: If there is an error reading from or
218
- writing to the local cache.
219
- """
278
+ """Retrieve known sequence values for a specified OEIS sequence.
279
+
280
+ (AI generated docstring)
281
+
282
+ This function fetches the complete set of known values for an OEIS sequence by accessing cached
283
+ data when available or retrieving fresh data from the OEIS website. The data is parsed from the
284
+ standard OEIS b-file format.
220
285
 
286
+ Parameters
287
+ ----------
288
+ oeisID : str
289
+ The identifier of the OEIS sequence to retrieve.
290
+
291
+ Returns
292
+ -------
293
+ OEISsequence : dict[int, int]
294
+ A dictionary mapping sequence indices to their corresponding values, or a fallback
295
+ dictionary containing {-1: -1} if retrieval fails.
296
+
297
+ Raises
298
+ ------
299
+ ValueError
300
+ If the cached or downloaded file format is invalid.
301
+ IOError
302
+ If there is an error reading from or writing to the local cache.
303
+
304
+ """
221
305
  pathFilenameCache: Path = pathCache / getFilenameOEISbFile(oeisID)
222
306
  url: str = f"https://oeis.org/{oeisID}/{getFilenameOEISbFile(oeisID)}"
223
307
 
224
308
  oeisInformation: None | str = getOEISofficial(pathFilenameCache, url)
225
309
 
226
310
  if oeisInformation:
227
- return _parseBFileOEIS(oeisInformation, oeisID)
311
+ return _parseBFileOEIS(oeisInformation)
228
312
  return {-1: -1}
229
313
 
230
314
  def getOEISidInformation(oeisID: str) -> tuple[str, int]:
231
- """
232
- Retrieve the description and offset for an OEIS sequence.
315
+ """Retrieve the description and offset metadata for an OEIS sequence.
316
+
317
+ (AI generated docstring)
233
318
 
234
- This function fetches the metadata for a given OEIS sequence ID, including its textual description and index offset
235
- value. It uses a caching mechanism to avoid redundant network requests while ensuring data freshness.
319
+ This function extracts the mathematical description and starting index offset from OEIS sequence
320
+ metadata using the machine-readable text format. It employs the same caching mechanism as other
321
+ retrieval functions to minimize network requests.
236
322
 
237
- Parameters:
238
- oeisID: The OEIS sequence identifier to retrieve information for.
323
+ Parameters
324
+ ----------
325
+ oeisID : str
326
+ The OEIS sequence identifier to retrieve metadata for.
239
327
 
240
- Returns:
241
- A tuple containing: - description: A string describing the sequence's mathematical meaning. - offset: An integer
242
- representing the starting index of the sequence. Usually 0 or 1, depending on the mathematical context.
328
+ Returns
329
+ -------
330
+ description : str
331
+ A human-readable string describing the sequence's mathematical meaning.
332
+ offset : int
333
+ The starting index of the sequence, typically 0 or 1 depending on mathematical context.
334
+
335
+ Notes
336
+ -----
337
+ Descriptions are parsed from OEIS %N entries and offsets from %O entries. If metadata cannot
338
+ be retrieved, warning messages are issued and fallback values are returned.
243
339
 
244
- Notes:
245
- Sequence descriptions are parsed from the machine-readable format of OEIS. If information cannot be retrieved,
246
- warning messages are issued and fallback values are returned.
247
340
  """
248
341
  oeisID = validateOEISid(oeisID)
249
342
  pathFilenameCache: Path = pathCache / f"{oeisID}.txt"
@@ -253,46 +346,49 @@ def getOEISidInformation(oeisID: str) -> tuple[str, int]:
253
346
 
254
347
  if not oeisInformation:
255
348
  return "Not found", -1
256
-
257
349
  listDescriptionDeconstructed: list[str] = []
258
350
  offset = None
259
- for ImaStr in oeisInformation.splitlines():
260
- ImaStr = ImaStr.strip() + "I am writing code to string parse machine readable data because in 2025, people can't even spell enteroperableity."
261
- secretCode, title, secretData =ImaStr.split(maxsplit=2)
262
- if secretCode == '%N' and title == oeisID:
263
- listDescriptionDeconstructed.append(secretData)
264
- if secretCode == '%O' and title == oeisID:
265
- offsetAsStr: str = secretData.split(',')[0]
351
+ for lineOEIS in oeisInformation.splitlines():
352
+ lineOEIS = lineOEIS.strip() # noqa: PLW2901
353
+ if not lineOEIS or len(lineOEIS.split()) < 3: # noqa: PLR2004
354
+ continue
355
+ fieldCode, sequenceID, fieldData = lineOEIS.split(maxsplit=2)
356
+ if fieldCode == '%N' and sequenceID == oeisID:
357
+ listDescriptionDeconstructed.append(fieldData)
358
+ if fieldCode == '%O' and sequenceID == oeisID:
359
+ offsetAsStr: str = fieldData.split(',')[0]
266
360
  offset = int(offsetAsStr)
267
361
  if not listDescriptionDeconstructed:
268
- warnings.warn(f"No description found for {oeisID}")
362
+ warnings.warn(f"No description found for {oeisID}", stacklevel=2)
269
363
  listDescriptionDeconstructed.append("No description found")
270
364
  if offset is None:
271
- warnings.warn(f"No offset found for {oeisID}")
365
+ warnings.warn(f"No offset found for {oeisID}", stacklevel=2)
272
366
  offset = -1
273
367
  description: str = ' '.join(listDescriptionDeconstructed)
274
368
  return description, offset
275
369
 
276
370
  def makeSettingsOEIS() -> dict[str, SettingsOEIS]:
277
- """
278
- Construct the comprehensive settings dictionary for all implemented OEIS sequences.
371
+ """Construct the comprehensive settings dictionary for all implemented OEIS sequences.
372
+
373
+ (AI generated docstring)
374
+
375
+ This function builds the complete configuration dictionary by merging hardcoded settings with
376
+ dynamically retrieved data from OEIS. For each implemented sequence, it combines:
279
377
 
280
- This function builds a complete configuration dictionary for all supported OEIS sequences by retrieving and
281
- combining:
282
378
  1. Sequence values from OEIS b-files
283
- 2. Sequence metadata (descriptions and offsets)
284
- 3. Hardcoded mapping functions and test values
285
-
286
- The resulting dictionary provides a single authoritative source for all OEIS-related configurations used throughout
287
- the package, including:
288
- - Mathematical descriptions of each sequence
289
- - Functions to convert between sequence indices and map dimensions
290
- - Known sequence values retrieved from OEIS
291
- - Testing and benchmarking reference values
292
-
293
- Returns:
294
- A dictionary mapping OEIS sequence IDs to their complete settings objects, containing all metadata and known
295
- values needed for computation and validation.
379
+ 2. Sequence metadata including descriptions and offsets
380
+ 3. Hardcoded mapping functions and test parameter sets
381
+
382
+ The resulting dictionary serves as the authoritative configuration source for all OEIS-related
383
+ operations throughout the package, enabling consistent access to sequence definitions, known values,
384
+ and operational parameters.
385
+
386
+ Returns
387
+ -------
388
+ settingsTarget : dict[str, SettingsOEIS]
389
+ A comprehensive dictionary mapping OEIS sequence IDs to their complete settings
390
+ objects, containing all metadata and known values needed for computation and validation.
391
+
296
392
  """
297
393
  settingsTarget: dict[str, SettingsOEIS] = {}
298
394
  for oeisID in oeisIDsImplemented:
@@ -311,11 +407,33 @@ def makeSettingsOEIS() -> dict[str, SettingsOEIS]:
311
407
  return settingsTarget
312
408
 
313
409
  settingsOEIS: dict[str, SettingsOEIS] = makeSettingsOEIS()
314
- """All values and settings for `oeisIDsImplemented`."""
410
+ """
411
+ Complete settings and metadata for all implemented OEIS sequences.
412
+
413
+ This dictionary contains the comprehensive configuration for each OEIS sequence supported by the module,
414
+ including known values retrieved from OEIS, mathematical descriptions, offset information, and all
415
+ operational parameters needed for computation and testing. The dictionary is populated by combining
416
+ hardcoded configurations with dynamically retrieved OEIS data during module initialization.
417
+ """
315
418
 
316
419
  @cache
317
420
  def makeDictionaryFoldsTotalKnown() -> dict[tuple[int, ...], int]:
318
- """Returns a dictionary mapping dimension tuples to their known folding totals."""
421
+ """Create a cached lookup dictionary mapping map shapes to their known folding totals.
422
+
423
+ (AI generated docstring)
424
+
425
+ This function processes all known sequence values from implemented OEIS sequences and creates
426
+ a unified dictionary that maps map dimension tuples to their corresponding folding totals. The
427
+ resulting dictionary enables rapid lookup of known values without requiring knowledge of which
428
+ specific OEIS sequence contains the data.
429
+
430
+ Returns
431
+ -------
432
+ dictionaryMapDimensionsToFoldsTotalKnown : dict[tuple[int, ...], int]
433
+ A dictionary where keys are tuples representing map shapes and values are the total number
434
+ of distinct folding patterns for those shapes.
435
+
436
+ """
319
437
  dictionaryMapDimensionsToFoldsTotalKnown: dict[tuple[int, ...], int] = {}
320
438
 
321
439
  for settings in settingsOEIS.values():
@@ -328,29 +446,48 @@ def makeDictionaryFoldsTotalKnown() -> dict[tuple[int, ...], int]:
328
446
  return dictionaryMapDimensionsToFoldsTotalKnown
329
447
 
330
448
  def getFoldsTotalKnown(mapShape: tuple[int, ...]) -> int:
331
- """
332
- Retrieve the known total number of foldings for a given map shape.
449
+ """Retrieve the known total number of distinct folding patterns for a given map shape.
450
+
451
+ (AI generated docstring)
333
452
 
334
- This function looks up precalculated folding totals for specific map dimensions from OEIS sequences. It serves as a
335
- rapid reference for known values without requiring computation, and can be used to validate algorithm results.
453
+ This function provides rapid access to precalculated folding totals from OEIS sequences without
454
+ requiring computation. It serves as a validation reference for algorithm results and enables
455
+ quick lookup of known values across all implemented sequences.
336
456
 
337
- Parameters:
338
- mapShape: A tuple of integers representing the dimensions of the map.
457
+ Parameters
458
+ ----------
459
+ mapShape : tuple[int, ...]
460
+ A tuple of integers representing the dimensions of the map.
339
461
 
340
- Returns:
341
- foldingsTotal: The known total number of foldings for the given map shape, or -1 if the map shape doesn't match
342
- any known values in the OEIS sequences.
462
+ Returns
463
+ -------
464
+ foldingsTotal : int
465
+ The known total number of distinct folding patterns for the given map shape,
466
+ or -1 if the map shape does not match any known values in the OEIS sequences.
467
+
468
+ Notes
469
+ -----
470
+ The function uses a cached dictionary for efficient retrieval without repeatedly processing
471
+ OEIS data. Map shapes are matched exactly as provided without internal sorting or normalization.
343
472
 
344
- Notes:
345
- The function uses a cached dictionary (via makeDictionaryFoldsTotalKnown) to efficiently retrieve values without
346
- repeatedly parsing OEIS data. Map shape tuples are sorted internally to ensure consistent lookup regardless of
347
- dimension order.
348
473
  """
349
474
  lookupFoldsTotal = makeDictionaryFoldsTotalKnown()
350
475
  return lookupFoldsTotal.get(tuple(mapShape), -1)
351
476
 
352
477
  def _formatHelpText() -> str:
353
- """Format standardized help text for both CLI and interactive use."""
478
+ """Format comprehensive help text for both command-line and interactive use.
479
+
480
+ (AI generated docstring)
481
+
482
+ This function generates standardized help documentation that includes all available OEIS sequences
483
+ with their descriptions and provides usage examples for both command-line and programmatic interfaces.
484
+
485
+ Returns
486
+ -------
487
+ helpText : str
488
+ A formatted string containing complete usage information and examples.
489
+
490
+ """
354
491
  exampleOEISid: str = oeisIDsImplemented[0]
355
492
  exampleN: int = settingsOEIS[exampleOEISid]['valuesTestValidation'][-1]
356
493
 
@@ -366,42 +503,96 @@ def _formatHelpText() -> str:
366
503
  )
367
504
 
368
505
  def _formatOEISsequenceInfo() -> str:
369
- """Format information about available OEIS sequences for display or error messages."""
506
+ """Format information about available OEIS sequences for display in help messages and error output.
507
+
508
+ (AI generated docstring)
509
+
510
+ This function creates a standardized listing of all implemented OEIS sequences with their mathematical
511
+ descriptions, suitable for inclusion in help text and error messages.
512
+
513
+ Returns
514
+ -------
515
+ sequenceInfo : str
516
+ A formatted string listing each OEIS sequence ID with its description.
517
+
518
+ """
370
519
  return "\n".join(
371
520
  f" {oeisID}: {settingsOEIS[oeisID]['description']}"
372
521
  for oeisID in oeisIDsImplemented
373
522
  )
374
523
 
375
524
  def oeisIDfor_n(oeisID: str, n: int | Any) -> int:
376
- """
377
- Calculate `a(n)` of a sequence from "The On-Line Encyclopedia of Integer Sequences" (OEIS).
378
-
379
- Parameters:
380
- oeisID: The ID of the OEIS sequence. n: A non-negative integer for which to calculate the sequence value.
525
+ """Calculate the value a(n) for a specified OEIS sequence and index.
526
+
527
+ (AI generated docstring)
528
+
529
+ This function serves as the primary interface for computing OEIS sequence values within the map folding
530
+ context. For small values or values within the known range, it returns cached OEIS data. For larger
531
+ values, it computes the result using the map folding algorithm with the appropriate map shape derived
532
+ from the sequence definition.
533
+
534
+ Parameters
535
+ ----------
536
+ oeisID : str
537
+ The identifier of the OEIS sequence to evaluate.
538
+ n : int | Any
539
+ A non-negative integer index for which to calculate the sequence value.
540
+
541
+ Returns
542
+ -------
543
+ int
544
+ The value a(n) of the specified OEIS sequence.
545
+
546
+ Raises
547
+ ------
548
+ ValueError
549
+ If n is not a non-negative integer.
550
+ KeyError
551
+ If the OEIS sequence ID is not directly implemented.
552
+ ArithmeticError
553
+ If n is below the sequence's defined offset.
381
554
 
382
- Returns:
383
- sequenceValue: `a(n)` of the OEIS sequence.
384
-
385
- Raises:
386
- ValueError: If `n` is negative. KeyError: If the OEIS sequence ID is not directly implemented.
387
555
  """
388
556
  oeisID = validateOEISid(oeisID)
389
557
 
390
558
  if not isinstance(n, int) or n < 0:
391
- raise ValueError(f"I received `{n = }` in the form of `{type(n) = }`, but it must be non-negative integer in the form of `{int}`.")
559
+ message = f"I received `{n = }` in the form of `{type(n) = }`, but it must be non-negative integer in the form of `{int}`."
560
+ raise ValueError(message)
392
561
 
393
562
  mapShape: tuple[int, ...] = settingsOEIS[oeisID]['getMapShape'](n)
394
563
 
395
- if n <= 1 or len(mapShape) < 2:
564
+ if n <= 1 or len(mapShape) < 2: # noqa: PLR2004
396
565
  offset: int = settingsOEIS[oeisID]['offset']
397
566
  if n < offset:
398
- raise ArithmeticError(f"OEIS sequence {oeisID} is not defined at {n = }.")
567
+ message = f"OEIS sequence {oeisID} is not defined at {n = }."
568
+ raise ArithmeticError(message)
399
569
  foldsTotal: int = settingsOEIS[oeisID]['valuesKnown'][n]
400
570
  return foldsTotal
401
571
  return countFolds(mapShape)
402
572
 
403
573
  def OEIS_for_n() -> None:
404
- """Command-line interface for oeisIDfor_n."""
574
+ """Command-line interface for calculating OEIS sequence values.
575
+
576
+ (AI generated docstring)
577
+
578
+ This function provides a command-line interface to the `oeisIDfor_n` function, enabling users to
579
+ calculate specific values of implemented OEIS sequences from the terminal. It includes argument
580
+ parsing, error handling, and performance timing to provide a complete user experience.
581
+
582
+ The function accepts two command-line arguments: an OEIS sequence identifier and an integer index,
583
+ then outputs the calculated sequence value along with execution time. Error messages are directed
584
+ to stderr with appropriate exit codes for shell scripting integration.
585
+
586
+ Usage
587
+ -----
588
+ python -m mapFolding.oeis OEIS_for_n A001415 10
589
+
590
+ Raises
591
+ ------
592
+ SystemExit
593
+ With code 1 if invalid arguments are provided or computation fails.
594
+
595
+ """
405
596
  parserCLI = argparse.ArgumentParser(
406
597
  description="Calculate a(n) for an OEIS sequence.",
407
598
  epilog=_formatHelpText(),
@@ -415,27 +606,50 @@ def OEIS_for_n() -> None:
415
606
  timeStart: float = time.perf_counter()
416
607
 
417
608
  try:
418
- print(oeisIDfor_n(argumentsCLI.oeisID, argumentsCLI.n), "distinct folding patterns.")
609
+ print(oeisIDfor_n(argumentsCLI.oeisID, argumentsCLI.n), "distinct folding patterns.") # noqa: T201
419
610
  except (KeyError, ValueError, ArithmeticError) as ERRORmessage:
420
- print(f"Error: {ERRORmessage}", file=sys.stderr)
611
+ print(f"Error: {ERRORmessage}", file=sys.stderr) # noqa: T201
421
612
  sys.exit(1)
422
613
 
423
614
  timeElapsed: float = time.perf_counter() - timeStart
424
- print(f"Time elapsed: {timeElapsed:.3f} seconds")
615
+ print(f"Time elapsed: {timeElapsed:.3f} seconds") # noqa: T201
425
616
 
426
617
  def clearOEIScache() -> None:
427
- """Delete all cached OEIS sequence files."""
618
+ """Delete all cached OEIS sequence files from the local cache directory.
619
+
620
+ (AI generated docstring)
621
+
622
+ This function removes all cached OEIS data files, including both sequence value files (b-files)
623
+ and metadata files, forcing fresh retrieval from the OEIS website on the next access. This is
624
+ useful for clearing stale cache data or troubleshooting network-related issues.
625
+
626
+ The function safely handles missing files and provides user feedback about the cache clearing
627
+ operation. If the cache directory does not exist, an informative message is displayed.
628
+
629
+ """
428
630
  if not pathCache.exists():
429
- print(f"Cache directory, {pathCache}, not found - nothing to clear.")
631
+ print(f"Cache directory, {pathCache}, not found - nothing to clear.") # noqa: T201
430
632
  return
431
633
  for oeisID in settingsOEIS:
432
634
  ( pathCache / f"{oeisID}.txt" ).unlink(missing_ok=True)
433
635
  ( pathCache / getFilenameOEISbFile(oeisID) ).unlink(missing_ok=True)
434
- print(f"Cache cleared from {pathCache}")
636
+ print(f"Cache cleared from {pathCache}") # noqa: T201
435
637
 
436
638
  def getOEISids() -> None:
437
- """Print all available OEIS sequence IDs that are directly implemented."""
438
- print(_formatHelpText())
639
+ """Display comprehensive information about all implemented OEIS sequences.
640
+
641
+ (AI generated docstring)
642
+
643
+ This function serves as the primary help interface for the module, displaying detailed information
644
+ about all directly implemented OEIS sequences along with usage examples for both command-line and
645
+ programmatic interfaces. It provides users with a complete overview of available sequences and
646
+ their mathematical meanings.
647
+
648
+ The output includes sequence identifiers, mathematical descriptions, and practical usage examples
649
+ to help users understand how to access and utilize the OEIS interface functionality.
650
+
651
+ """
652
+ print(_formatHelpText()) # noqa: T201
439
653
 
440
654
  if __name__ == "__main__":
441
655
  getOEISids()