rgwfuncs 0.0.101__py3-none-any.whl → 0.0.106__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.
rgwfuncs/__init__.py CHANGED
@@ -3,6 +3,5 @@
3
3
 
4
4
  from .df_lib import append_columns, append_percentile_classification_column, append_ranged_classification_column, append_ranged_date_classification_column, append_rows, append_xgb_labels, append_xgb_logistic_regression_predictions, append_xgb_regression_predictions, bag_union_join, bottom_n_unique_values, cascade_sort, delete_rows, drop_duplicates, drop_duplicates_retain_first, drop_duplicates_retain_last, filter_dataframe, filter_indian_mobiles, first_n_rows, from_raw_data, insert_dataframe_in_sqlite_database, last_n_rows, left_join, limit_dataframe, load_data_from_path, load_data_from_query, load_data_from_sqlite_path, load_fresh_data_or_pull_from_cache, mask_against_dataframe, mask_against_dataframe_converse, numeric_clean, order_columns, print_correlation, print_dataframe, print_memory_usage, print_n_frequency_cascading, print_n_frequency_linear, rename_columns, retain_columns, right_join, send_data_to_email, send_data_to_slack, send_dataframe_via_telegram, sync_dataframe_to_sqlite_database, top_n_unique_values, union_join, update_rows
5
5
  from .interactive_shell_lib import interactive_shell
6
- from .algebra_lib import cancel_polynomial_expression, compute_constant_expression, compute_constant_expression_involving_matrices, compute_constant_expression_involving_ordered_series, compute_prime_factors, expand_polynomial_expression, factor_polynomial_expression, plot_polynomial_functions, plot_x_points_of_polynomial_functions, python_polynomial_expression_to_latex, simplify_polynomial_expression, solve_homogeneous_polynomial_expression
7
6
  from .docs_lib import docs
8
- from .str_lib import send_telegram_message
7
+ from .str_lib import heading, send_telegram_message, sub_heading, title
@@ -7,7 +7,6 @@ import os
7
7
  import atexit
8
8
  from typing import Dict, Any
9
9
  from .df_lib import * # noqa: F401, F403, E402
10
- from .algebra_lib import * # noqa: F401, F403, E402
11
10
  from .str_lib import * # noqa: F401, F403, E402
12
11
  from .docs_lib import * # noqa: F401, F403, E402
13
12
 
rgwfuncs/str_lib.py CHANGED
@@ -1,12 +1,21 @@
1
+ import sys
2
+ import time
1
3
  import os
2
4
  import json
3
5
  import requests
4
6
  from typing import Tuple, Optional, Union, Dict
7
+ from collections import defaultdict
5
8
  import warnings
9
+ from pyfiglet import Figlet
10
+ from datetime import datetime
6
11
 
7
12
  # Suppress all FutureWarnings
8
13
  warnings.filterwarnings("ignore", category=FutureWarning)
9
14
 
15
+ # Module-level variables
16
+ _PRINT_HEADING_CURRENT_CALL = 0
17
+ _PRINT_SUBHEADING_COUNTS = defaultdict(int) # Tracks sub-headings per heading
18
+ _CURRENT_HEADING_NUMBER = 0
10
19
 
11
20
  def send_telegram_message(preset_name: str, message: str, config: Optional[Union[str, dict]] = None) -> None:
12
21
  """
@@ -104,3 +113,164 @@ def send_telegram_message(preset_name: str, message: str, config: Optional[Union
104
113
  # Send the message
105
114
  response = requests.post(url, json=payload)
106
115
  response.raise_for_status()
116
+
117
+ def title(text: str, font: str = "slant", typing_speed: float = 0.005) -> None:
118
+ """
119
+ Print text as ASCII art with a typewriter effect using the specified font (default: slant),
120
+ indented by 4 spaces. All output, including errors and separators, is printed with the
121
+ typewriter effect within this function.
122
+
123
+ Args:
124
+ text (str): The text to convert to ASCII art.
125
+ font (str, optional): The pyfiglet font to use. Defaults to "slant".
126
+ typing_speed (float, optional): Delay between printing each character in seconds.
127
+ Defaults to 0.005.
128
+
129
+ Raises:
130
+ ValueError: If the specified font is invalid or unavailable.
131
+ RuntimeError: If there is an error generating the ASCII art.
132
+ """
133
+ # ANSI color codes
134
+ heading_color = '\033[92m' # Bright green for headings
135
+ reset_color = '\033[0m' # Reset to default
136
+
137
+ try:
138
+ # Initialize Figlet with the specified font
139
+ figlet = Figlet(font=font)
140
+ # Generate ASCII art
141
+ ascii_art = figlet.renderText(text)
142
+ # Indent each line by 4 spaces
143
+ indented_ascii_art = '\n'.join(' ' + line for line in ascii_art.splitlines())
144
+
145
+ # Print ASCII art with typewriter effect
146
+ print(heading_color, end='')
147
+ for char in indented_ascii_art + '\n':
148
+ print(char, end='', flush=True)
149
+ if char != '\n': # Don't delay on newlines
150
+ time.sleep(typing_speed)
151
+ print(reset_color, end='')
152
+
153
+ # Print separator line with typewriter effect
154
+ print(heading_color, end='')
155
+ for char in '=' * 79 + '\n':
156
+ print(char, end='', flush=True)
157
+ if char != '\n':
158
+ time.sleep(typing_speed)
159
+ print(reset_color, end='')
160
+
161
+ except Exception as e:
162
+ error_msg = ''
163
+ if "font" in str(e).lower():
164
+ error_msg = f"Invalid or unavailable font: {font}. Ensure the font is supported by pyfiglet.\n"
165
+ print(reset_color, end='')
166
+ for char in error_msg:
167
+ print(char, end='', flush=True)
168
+ if char != '\n':
169
+ time.sleep(typing_speed)
170
+ raise ValueError(error_msg)
171
+ error_msg = f"Error generating ASCII art for \"{text}\" with font {font}: {e}\n"
172
+ print(reset_color, end='')
173
+ for char in error_msg:
174
+ print(char, end='', flush=True)
175
+ if char != '\n':
176
+ time.sleep(typing_speed)
177
+ raise RuntimeError(error_msg)
178
+
179
+ def heading(text: str, typing_speed: float = 0.005) -> None:
180
+ """
181
+ Print a heading with the specified text in uppercase,
182
+ formatted as '[current_call] TEXT' with a timestamp and typewriter effect.
183
+ Ensures the formatted heading is <= 50 characters and total line is 79 characters.
184
+ Adds empty lines before and after the heading.
185
+
186
+ Args:
187
+ text (str): The heading text to print.
188
+ typing_speed (float, optional): Delay between printing each character in seconds.
189
+ Defaults to 0.005.
190
+ """
191
+ global _PRINT_HEADING_CURRENT_CALL, _CURRENT_HEADING_NUMBER, _PRINT_SUBHEADING_COUNTS
192
+
193
+ # Increment heading call
194
+ _PRINT_HEADING_CURRENT_CALL += 1
195
+ _CURRENT_HEADING_NUMBER = _PRINT_HEADING_CURRENT_CALL
196
+ _PRINT_SUBHEADING_COUNTS[_CURRENT_HEADING_NUMBER] = 0 # Reset sub-heading count
197
+
198
+ # ANSI color codes
199
+ color = '\033[92m' # Bright green for headings
200
+ reset_color = '\033[0m'
201
+
202
+ # Format heading
203
+ prefix = f"[{_PRINT_HEADING_CURRENT_CALL}] "
204
+ max_text_length = 50 - len(prefix)
205
+ formatted_text = text.upper()[:max_text_length]
206
+ heading = f"{prefix}{formatted_text}"
207
+
208
+ # Get timestamp
209
+ timestamp = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]"
210
+
211
+ # Calculate padding
212
+ padding_length = 79 - len(heading) - 1 - len(timestamp) - 1 # Spaces before padding and timestamp
213
+ padding = '=' * padding_length if padding_length > 0 else ''
214
+ full_line = f"{heading} {padding} {timestamp}"
215
+
216
+ # Print with line breaks and typewriter effect
217
+ print() # Empty line before
218
+ print(color, end='')
219
+ for char in full_line + '\n':
220
+ print(char, end='', flush=True)
221
+ if char != '\n':
222
+ time.sleep(typing_speed)
223
+ print(reset_color, end='')
224
+ print() # Empty line after
225
+
226
+ def sub_heading(text: str, typing_speed: float = 0.005) -> None:
227
+ """
228
+ Print a sub-heading under the most recent heading, formatted as
229
+ '[heading_num.sub_heading_num] TEXT' with a timestamp and typewriter effect.
230
+ Ensures the formatted sub-heading is <= 50 characters and total line is 79 characters.
231
+ Adds empty lines before and after the sub-heading.
232
+
233
+ Args:
234
+ text (str): The sub-heading text to print.
235
+ typing_speed (float, optional): Delay between printing each character in seconds.
236
+ Defaults to 0.005.
237
+
238
+ Raises:
239
+ ValueError: If no heading has been called.
240
+ """
241
+ global _PRINT_SUBHEADING_COUNTS, _CURRENT_HEADING_NUMBER
242
+
243
+ if _CURRENT_HEADING_NUMBER == 0:
244
+ raise ValueError("No heading called before sub_heading.")
245
+
246
+ # Increment sub-heading count
247
+ _PRINT_SUBHEADING_COUNTS[_CURRENT_HEADING_NUMBER] += 1
248
+ current_sub = _PRINT_SUBHEADING_COUNTS[_CURRENT_HEADING_NUMBER]
249
+
250
+ # ANSI color codes
251
+ color = '\033[92m' # Bright green for sub-headings
252
+ reset_color = '\033[0m'
253
+
254
+ # Format sub-heading
255
+ prefix = f"[{_CURRENT_HEADING_NUMBER}.{current_sub}] "
256
+ max_text_length = 50 - len(prefix)
257
+ formatted_text = text.lower()[:max_text_length]
258
+ sub_heading = f"{prefix}{formatted_text}"
259
+
260
+ # Get timestamp
261
+ timestamp = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]"
262
+
263
+ # Calculate padding
264
+ padding_length = 79 - len(sub_heading) - 1 - len(timestamp) - 1 # Spaces before padding and timestamp
265
+ padding = '-' * padding_length if padding_length > 0 else ''
266
+ full_line = f"{sub_heading} {padding} {timestamp}"
267
+
268
+ # Print with line breaks and typewriter effect
269
+ print() # Empty line before
270
+ print(color, end='')
271
+ for char in full_line + '\n':
272
+ print(char, end='', flush=True)
273
+ if char != '\n':
274
+ time.sleep(typing_speed)
275
+ print(reset_color, end='')
276
+ print() # Empty line after
@@ -1,8 +1,8 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rgwfuncs
3
- Version: 0.0.101
3
+ Version: 0.0.106
4
4
  Summary: A functional programming paradigm for mathematical modelling and data science
5
- Home-page: https://github.com/ryangerardwilson/rgwfunc
5
+ Home-page: https://github.com/ryangerardwilson/rgwfuncs
6
6
  Author: Ryan Gerard Wilson
7
7
  Author-email: Ryan Gerard Wilson <ryangerardwilson@gmail.com>
8
8
  Project-URL: Homepage, https://github.com/ryangerardwilson/rgwfuncs
@@ -24,16 +24,18 @@ Requires-Dist: requests
24
24
  Requires-Dist: slack-sdk
25
25
  Requires-Dist: google-api-python-client
26
26
  Requires-Dist: boto3
27
+ Requires-Dist: pyfiglet
27
28
  Dynamic: license-file
28
29
 
29
30
  # RGWFUNCS
30
31
 
31
32
  ***By Ryan Gerard Wilson (https://ryangerardwilson.com)***
32
33
 
34
+ `rgwfuncs` keeps your Python data science and ML code clean by avoiding types defined in external libraries. Foreign types make debugging a nightmare—rgwfuncs uses functional and procedural paradigms, ensuring your types stay local and under your control.
33
35
 
34
- This library is meant to protect your eyes (and brain) from OOP syntax. It is unbelievably sad that some of the best work done in creating math and data science libraries in Python has been corrupted by the OOP mind-virus.
36
+ It wraps complex data science patterns into clear, reusable functions with well-defined, type-casted returns. No wrestling with weird objects you don’t have time to decipher—just simple, predictable outputs that make your life easier. You get the power of Python’s best libraries without the headache of their opaque classes.
35
37
 
36
- By creating a functional-programming wrapper around these libraries, we aim to soothe. This library assumes a Linux environment and the existence of a `.rgwfuncsrc` file for certain features (like database querying, sending data to Slack, etc.).
38
+ Built for Linux, some features (like database queries or Slack integration) require a .rgwfuncsrc file. With rgwfuncs, your code is debug-friendly, maintainable, and refreshingly straightforward—because type-casted functions beat cryptic objects every time.
37
39
 
38
40
  --------------------------------------------------------------------------------
39
41
 
@@ -47,7 +49,7 @@ Install the package using:
47
49
 
48
50
  ## Create a `.rgwfuncsrc` File
49
51
 
50
- A `.rgwfuncsrc` file (located at `vi ~/.rgwfuncsrc) is required for MSSQL, CLICKHOUSE, MYSQL, GOOGLE BIG QUERY, SLACK, TELEGRAM, and GMAIL integrations.
52
+ A `.rgwfuncsrc` file (located in the current, or any parent directory) is required for MSSQL, CLICKHOUSE, MYSQL, GOOGLE BIG QUERY, SLACK, TELEGRAM, and GMAIL integrations.
51
53
 
52
54
  {
53
55
  "db_presets" : [
@@ -218,410 +220,6 @@ Subsequently, in the interactive shell you can use any library in your python fi
218
220
 
219
221
  --------------------------------------------------------------------------------
220
222
 
221
- ## Algebra Based Functions
222
-
223
- This section provides comprehensive functions for handling algebraic expressions, performing tasks such as computation, simplification, solving equations, and prime factorization, all outputted in LaTeX format.
224
-
225
- ### 1. `compute_prime_factors`
226
-
227
- Computes prime factors of a number and presents them in LaTeX format.
228
-
229
- • Parameters:
230
- - `n` (int): The integer to factorize.
231
-
232
- • Returns:
233
- - `str`: Prime factorization in LaTeX.
234
-
235
- • Example:
236
-
237
- from rgwfuncs import compute_prime_factors
238
- factors_1 = compute_prime_factors(100)
239
- print(factors_1) # Output: "2^{2} \cdot 5^{2}"
240
-
241
- factors_2 = compute_prime_factors(60)
242
- print(factors_2) # Output: "2^{2} \cdot 3 \cdot 5"
243
-
244
- factors_3 = compute_prime_factors(17)
245
- print(factors_3) # Output: "17"
246
-
247
- --------------------------------------------------------------------------------
248
-
249
- ### 2. `compute_constant_expression`
250
-
251
- Computes the numerical result of a given expression, which can evaluate to a constant, represented as a float. Evaluates an constant expression provided as a string and returns the computed result. Supports various arithmetic operations, including addition, subtraction, multiplication, division, and modulo, as well as mathematical functions from the math module.
252
-
253
- • Parameters:
254
- - `expression` (str): The constant expression to compute. This should be a string consisting of arithmetic operations and Python's math module functions.
255
-
256
- • Returns:
257
- - `float`: The computed numerical result.
258
-
259
- • Example:
260
-
261
- from rgwfuncs import compute_constant_expression
262
- result1 = compute_constant_expression("2 + 2")
263
- print(result1) # Output: 4.0
264
-
265
- result2 = compute_constant_expression("10 % 3")
266
- print(result2) # Output: 1.0
267
-
268
- result3 = compute_constant_expression("math.gcd(36, 60) * math.sin(math.radians(45)) * 10000")
269
- print(result3) # Output: 84852.8137423857
270
-
271
- --------------------------------------------------------------------------------
272
-
273
- ### 3. `compute_constant_expression_involving_matrices`
274
-
275
- Computes the result of a constant expression involving matrices and returns it as a LaTeX string.
276
-
277
- • Parameters:
278
- - `expression` (str): The constant expression involving matrices. Example format includes operations such as "+", "-", "*", "/".
279
-
280
- • Returns:
281
- - `str`: The LaTeX-formatted string representation of the computed matrix, or an error message if the operations cannot be performed due to dimensional mismatches.
282
-
283
- • Example:
284
-
285
- from rgwfuncs import compute_constant_expression_involving_matrices
286
-
287
- # Example with addition of 2D matrices
288
- result = compute_constant_expression_involving_matrices("[[2, 6, 9], [1, 3, 5]] + [[1, 2, 3], [4, 5, 6]]")
289
- print(result) # Output: \begin{bmatrix}3 & 8 & 12\\5 & 8 & 11\end{bmatrix}
290
-
291
- # Example of mixed operations with 1D matrices treated as 2D
292
- result = compute_constant_expression_involving_matrices("[3, 6, 9] + [1, 2, 3] - [2, 2, 2]")
293
- print(result) # Output: \begin{bmatrix}2 & 6 & 10\end{bmatrix}
294
-
295
- # Example with dimension mismatch
296
- result = compute_constant_expression_involving_matrices("[[4, 3, 51]] + [[1, 1]]")
297
- print(result) # Output: Operations between matrices must involve matrices of the same dimension
298
-
299
- --------------------------------------------------------------------------------
300
-
301
- ### 4. `compute_constant_expression_involving_ordered_series`
302
-
303
- Computes the result of a constant expression involving ordered series, and returns it as a Latex string.
304
-
305
-
306
- • Parameters:
307
- - `expression` (str): A series operation expression. Supports operations such as "+", "-", "*", "/", and `dd()` for discrete differences.
308
-
309
- • Returns:
310
- - `str`: The string representation of the resultant series after performing operations, or an error message if series lengths do not match.
311
-
312
- • Example:
313
-
314
- from rgwfuncs import compute_constant_expression_involving_ordered_series
315
-
316
- # Example with addition and discrete differences
317
- result = compute_constant_expression_involving_ordered_series("dd([2, 6, 9, 60]) + dd([78, 79, 80])")
318
- print(result) # Output: [4, 3, 51] + [1, 1]
319
-
320
- # Example with elementwise subtraction
321
- result = compute_constant_expression_involving_ordered_series("[10, 15, 21] - [5, 5, 5]")
322
- print(result) # Output: [5, 10, 16]
323
-
324
- # Example with length mismatch
325
- result = compute_constant_expression_involving_ordered_series("[4, 3, 51] + [1, 1]")
326
- print(result) # Output: Operations between ordered series must involve series of equal length
327
-
328
- --------------------------------------------------------------------------------
329
-
330
- ### 5. `python_polynomial_expression_to_latex`
331
-
332
- Converts a polynomial expression written in Python syntax to a LaTeX formatted string. This function parses algebraic expressions provided as strings using Python’s syntax and translates them into equivalent LaTeX representations, making them suitable for academic or professional documentation. The function supports inclusion of named variables, with an option to substitute specific values into the expression.
333
-
334
- • Parameters:
335
- - `expression` (str): The algebraic expression to convert to LaTeX. This should be a string formatted with Python syntax acceptable by SymPy.
336
- - `subs` (Optional[Dict[str, float]]): An optional dictionary of substitutions where the keys are variable names in the expression, and the values are the numbers with which to substitute those variables.
337
-
338
- • Returns:
339
- - `str`: The LaTeX formatted string equivalent to the provided expression.
340
-
341
- • Raises:
342
- - `ValueError`: If the expression cannot be parsed due to syntax errors.
343
-
344
- • Example:
345
-
346
- from rgwfuncs import python_polynomial_expression_to_latex
347
-
348
- # Convert a simple polynomial expression to LaTeX format
349
- latex_result1 = python_polynomial_expression_to_latex("x**2 + y**2")
350
- print(latex_result1) # Output: "x^{2} + y^{2}"
351
-
352
- # Convert polynomial expression with substituted values
353
- latex_result2 = python_polynomial_expression_to_latex("x**2 + y**2", {"x": 3, "y": 4})
354
- print(latex_result2) # Output: "25"
355
-
356
- # Another example with partial substitution
357
- latex_result3 = python_polynomial_expression_to_latex("x**2 + y**2", {"x": 3})
358
- print(latex_result3) # Output: "y^{2} + 9"
359
-
360
- # Trigonometric functions included with symbolic variables
361
- latex_result4 = python_polynomial_expression_to_latex("sin(x+z**2) + cos(y)", {"x": 55})
362
- print(latex_result4) # Output: "cos y + sin \\left(z^{2} + 55\\right)"
363
-
364
- # Simplified trigonometric functions example with substitution
365
- latex_result5 = python_polynomial_expression_to_latex("sin(x) + cos(y)", {"x": 0})
366
- print(latex_result5) # Output: "cos y"
367
-
368
- --------------------------------------------------------------------------------
369
-
370
- ### 6. `expand_polynomial_expression`
371
-
372
- Expands a polynomial expression written in Python syntax and converts it into a LaTeX formatted string. This function takes algebraic expressions provided as strings using Python's syntax, applies polynomial expansion through SymPy, and translates them into LaTeX representations, suitable for academic or professional documentation. It supports expressions with named variables and provides an option to substitute specific values into the expression before expansion.
373
-
374
- • Parameters:
375
- - `expression` (str): The algebraic expression to expand and convert to LaTeX. This string should be formatted using Python syntax acceptable by SymPy.
376
- - `subs` (Optional[Dict[str, float]]): An optional dictionary of substitutions where the keys are variable names in the expression, and the values are the numbers with which to substitute those variables before expanding.
377
-
378
- • Returns:
379
- - `str`: The LaTeX formatted string of the expanded expression.
380
-
381
- • Raises:
382
- - `ValueError`: If the expression cannot be parsed due to syntax errors.
383
-
384
- • Example:
385
-
386
- from rgwfuncs import expand_polynomial_expression
387
-
388
- # Expand a simple polynomial expression and convert to LaTeX
389
- latex_result1 = expand_polynomial_expression("(x + y)**2")
390
- print(latex_result1) # Output: "x^{2} + 2 x y + y^{2}"
391
-
392
- # Expand polynomial expression with substituted values
393
- latex_result2 = expand_polynomial_expression("(x + y)**2", {"x": 3, "y": 4})
394
- print(latex_result2) # Output: "49"
395
-
396
- # Another example with partial substitution
397
- latex_result3 = expand_polynomial_expression("(x + y)**2", {"x": 3})
398
- print(latex_result3) # Output: "y^{2} + 6 y + 9"
399
-
400
- # Handling trigonometric functions with symbolic variables
401
- latex_result4 = expand_polynomial_expression("sin(x + z**2) + cos(y)", {"x": 55})
402
- print(latex_result4) # Output: "cos y + sin \\left(z^{2} + 55\\right)"
403
-
404
- --------------------------------------------------------------------------------
405
-
406
- ### 7. `factor_polynomial_expression`
407
-
408
- Factors a polynomial expression written in Python syntax and converts it into a LaTeX formatted string. This function parses an algebraic expression, performs polynomial factoring using SymPy, and converts the factored expression into a LaTeX representation, ideal for academic or professional use. Optional substitutions can be made before factoring.
409
-
410
- • Parameters:
411
- - `expression` (str): The polynomial expression to factor and convert to LaTeX. This should be a valid expression formatted using Python syntax.
412
- - `subs` (Optional[Dict[str, float]]): An optional dictionary of substitutions. The keys are variable names in the expression, and the values are numbers that replace these variables.
413
-
414
- • Returns:
415
- - `str`: The LaTeX formatted string representing the factored expression.
416
-
417
- • Raises:
418
- - `ValueError`: If the expression cannot be parsed due to syntax errors.
419
-
420
- • Example:
421
-
422
- from rgwfuncs import factor_polynomial_expression
423
-
424
- # Factor a polynomial expression and convert to LaTeX
425
- latex_result1 = factor_polynomial_expression("x**2 - 4")
426
- print(latex_result1) # Output: "\left(x - 2\right) \left(x + 2\right)"
427
-
428
- # Factor with substituted values
429
- latex_result2 = factor_polynomial_expression("x**2 - y**2", {"y": 3})
430
- print(latex_result2) # Output: "\left(x - 3\right) \left(x + 3\right)"
431
-
432
- --------------------------------------------------------------------------------
433
-
434
- ### 8. `simplify_polynomial_expression`
435
-
436
- Simplifies an algebraic expression in polynomial form and returns it in LaTeX format. Takes an algebraic expression, in polynomial form, written in Python syntax and simplifies it. The result is returned as a LaTeX formatted string, suitable for academic or professional documentation.
437
-
438
- • Parameters:
439
- - `expression` (str): The algebraic expression, in polynomial form, to simplify. For instance, the expression 'np.diff(8*x**30) where as 'np.diff([2,5,9,11)' is not a polynomial.
440
- - `subs` (Optional[Dict[str, float]]): An optional dictionary of substitutions where keys are variable names and values are the numbers to substitute them with.
441
-
442
- • Returns:
443
- - `str`: The simplified expression formatted as a LaTeX string.
444
-
445
- • Example:
446
-
447
- from rgwfuncs import simplify_polynomial_expression
448
-
449
- # Example 1: Simplifying a polynomial expression without substitutions
450
- simplified_expr1 = simplify_polynomial_expression("2*x + 3*x")
451
- print(simplified_expr1) # Output: "5 x"
452
-
453
- # Example 2: Simplifying a complex expression involving derivatives
454
- simplified_expr2 = simplify_polynomial_expression("(np.diff(3*x**8)) / (np.diff(8*x**30) * 11*y**3)")
455
- print(simplified_expr2) # Output: r"\frac{1}{110 x^{22} y^{3}}"
456
-
457
- # Example 3: Simplifying with substitutions
458
- simplified_expr3 = simplify_polynomial_expression("x**2 + y**2", subs={"x": 3, "y": 4})
459
- print(simplified_expr3) # Output: "25"
460
-
461
- # Example 4: Simplifying with partial substitution
462
- simplified_expr4 = simplify_polynomial_expression("a*b + b", subs={"b": 2})
463
- print(simplified_expr4) # Output: "2 a + 2"
464
-
465
- --------------------------------------------------------------------------------
466
-
467
- ### 9. `cancel_polynomial_expression`
468
-
469
- Cancels common factors within a polynomial expression written in Python syntax and converts it to a LaTeX formatted string. This function parses an algebraic expression, cancels common factors using SymPy, and translates the reduced expression into a LaTeX representation. It can also accommodate optional substitutions to be made prior to simplification.
470
-
471
- • Parameters:
472
- - `expression` (str): The algebraic expression to simplify and convert to LaTeX. This string should be formatted using Python syntax.
473
- - `subs` (Optional[Dict[str, float]]): An optional dictionary of substitutions where the keys are variable names in the expression, and the values are the numbers to substitute.
474
-
475
- • Returns:
476
- - `str`: The LaTeX formatted string of the simplified expression. If the expression involves indeterminate forms due to operations like division by zero, a descriptive error message is returned instead.
477
-
478
- • Raises:
479
- - `ValueError`: If the expression cannot be parsed due to syntax errors or involves undefined operations, such as division by zero.
480
-
481
- • Example:
482
-
483
- from rgwfuncs import cancel_polynomial_expression
484
-
485
- # Cancel common factors within a polynomial expression
486
- latex_result1 = cancel_polynomial_expression("(x**2 - 4) / (x - 2)")
487
- print(latex_result1) # Output: "x + 2"
488
-
489
- # Cancel with substituted values
490
- latex_result2 = cancel_polynomial_expression("(x**2 - 4) / (x - 2)", {"x": 2})
491
- print(latex_result2) # Output: "Undefined result. This could be a division by zero error."
492
-
493
- --------------------------------------------------------------------------------
494
-
495
- ### 10. `solve_homogeneous_polynomial_expression`
496
-
497
- Solves a homogeneous polynomial expression for a specified variable and returns solutions in LaTeX format. Assumes that the expression is homoegeneous (i.e. equal to zero), and solves for a designated variable. May optionally include substitutions for other variables in the equation. The solutions are provided as a LaTeX formatted string. The method solves equations for specified variables, with optional substitutions, returning LaTeX-formatted solutions.
498
-
499
- • Parameters:
500
- - `expression` (str): A string of the homogeneous polynomial expression to solve.
501
- - `variable` (str): The variable to solve for.
502
- - `subs` (Optional[Dict[str, float]]): Substitutions for variables.
503
-
504
- • Returns:
505
- - `str`: Solutions formatted in LaTeX.
506
-
507
- • Example:
508
-
509
- from rgwfuncs import solve_homogeneous_polynomial_expression
510
- solutions1 = solve_homogeneous_polynomial_expression("a*x**2 + b*x + c", "x", {"a": 3, "b": 7, "c": 5})
511
- print(solutions1) # Output: "\left[-7/6 - sqrt(11)*I/6, -7/6 + sqrt(11)*I/6\right]"
512
-
513
- solutions2 = solve_homogeneous_polynomial_expression("x**2 - 4", "x")
514
- print(solutions2) # Output: "\left[-2, 2\right]"
515
-
516
- --------------------------------------------------------------------------------
517
-
518
- ### 11. `plot_polynomial_functions`
519
-
520
- This function plots polynomial functions described by a list of expressions and their corresponding substitution dictionaries. It generates SVG markup of the plots, with options for specifying the domain, axis zoom, and legend display.
521
-
522
- • Parameters:
523
- - `functions` (`List[Dict[str, Dict[str, Any]]]`): A list of dictionaries, each containing:
524
- - A key which is a string representing a Python/NumPy expression (e.g., `"x**2"`, `"np.diff(x,2)"`).
525
- - A value which is a dictionary containing substitutions for the expression. Must include an `"x"` key, either as `"*"` for default domain or a NumPy array.
526
- - `zoom` (`float`): Determines the numeric axis range from `-zoom` to `+zoom` for both x and y axes (default is `10.0`).
527
- - `show_legend` (`bool`): Specifies whether to include a legend in the plot (default is `True`).
528
- - `open_file` (`bool`): If saving to path is not desireable, opens the svg as a temp file, else opens the file from the actual location using the system's default viewer (defaults to False).
529
- - `save_path` (`Optional[str]`): If specified, saves the output string as a .svg at the indicated path (defaults to None).
530
-
531
- • Returns:
532
- - `str`: The raw SVG markup of the resulting plot.
533
-
534
- • Example:
535
-
536
- from rgwfuncs import plot_polynomial_functions
537
-
538
- # Generate the SVG
539
- plot_svg_string = plot_polynomial_functions(
540
- functions=[
541
- {"x**2": {"x": "*"}}, # Single expression, "*" means plot all discernable points
542
- {"x**2/(2 + a) + a": {"x": np.linspace(-3, 4, 101), "a": 1.23}},
543
- {"np.diff(x**3, 2)": {"x": np.linspace(-2, 2, 10)}}
544
- ],
545
- zoom=2,
546
- open_file=True,
547
- save_path="plot_polynomial_functions_example_1.svg"
548
- )
549
-
550
- • Displaying the SVG:
551
-
552
- ![Plot](./media/plot_polynomial_functions_example_1.svg)
553
-
554
- --------------------------------------------------------------------------------
555
-
556
- ### 12. `plot_x_points_of_polynomial_functions`
557
-
558
- This function plots one or more expressions described by a list of dictionaries. For each item in the list, the function evaluates the given Python/NumPy expression at the specified x-values (converted to NumPy arrays if they are Python lists) and plots the resulting points on a single figure.
559
-
560
- • Parameters:
561
- - `functions` (`List[Dict[str, Dict[str, Any]]]`): A list of one or more items, each of which has exactly one key-value pair:
562
- - Key (`str`): A valid Python/NumPy expression (e.g., `x**2`, `np.sin(x)`, `x - a`).
563
- - Value (`Dict[str, Any]`): Must assign `x` a value
564
- - `zoom` (`float`): Numeric range from -zoom to +zoom on both x and y axes (default 10.0).
565
- - `show_legend` (`bool`): If True, includes a legend (default True).
566
- - `open_file` (bool):
567
- - If True and `save_path` is given, opens that file with the system viewer.
568
- - If True and `save_path` is None, writes to a temporary file and opens it (default False).
569
- - `save_path` (`Optional[str]`): If specified, writes the resulting SVG to this path (default None).
570
-
571
- • Returns:
572
- - `str`: The raw SVG markup of the resulting scatter plot.
573
-
574
- • Example:
575
-
576
- from rgwfuncs import plot_x_points_of_polynomial_functions
577
- import numpy as np
578
-
579
- svg_output = plot_x_points_of_polynomial_functions(
580
- functions=[
581
- {"x**2": {"x": np.array([-2, -1, 0, 1, 2])}},
582
- {"np.sin(x)": {"x": np.linspace(0, 2*np.pi, 5)}},
583
- {"x - 3": {"x": np.array([-2, 0, 2, 4, 6])}}
584
- ],
585
- zoom=6,
586
- show_legend=True,
587
- open_file=True,
588
- save_path="plot_x_points_of_polynomial_functions_example_5.svg"
589
- )
590
-
591
- • Displaying the SVG:
592
-
593
- ![Plot](./media/plot_x_points_of_polynomial_functions_example_5.svg)
594
-
595
- --------------------------------------------------------------------------------
596
-
597
- ## String Based Functions
598
-
599
- ### 1. send_telegram_message
600
-
601
- Send a message to a Telegram chat using a specified preset from your configuration file.
602
-
603
- • Parameters:
604
- - `preset_name` (str): The name of the preset to use for sending the message. This should match a preset in the configuration file.
605
- - `message` (str): The message text that you want to send to the Telegram chat.
606
- - config (Optional[Union[str, dict]], optional): Configuration source. Can be:
607
- - None: Uses default path '~/.rgwfuncsrc'
608
- - str: Path to a JSON configuration file
609
- - dict: Direct configuration dictionary
610
-
611
- • Raises:
612
- - `RuntimeError`: If the preset is not found in the configuration file or if necessary details (bot token or chat ID) are missing.
613
-
614
- • Example:
615
-
616
- from rgwfuncs import send_telegram_message
617
-
618
- preset_name = "daily_updates"
619
- message = "Here is your daily update!"
620
-
621
- send_telegram_message(preset_name, message)
622
-
623
- --------------------------------------------------------------------------------
624
-
625
223
  ## Dataframe Based Functions
626
224
 
627
225
  Below is a quick reference of available functions, their purpose, and basic usage examples.
@@ -0,0 +1,11 @@
1
+ rgwfuncs/__init__.py,sha256=XIbMHeEimBLNcX2PK7uQGquG-eAYXsetVEJrlBZIH5U,1295
2
+ rgwfuncs/df_lib.py,sha256=3foomRHlunCpf_accTcqfdgwDmSPIVkVCnlWJ4ag4XQ,76947
3
+ rgwfuncs/docs_lib.py,sha256=i63NzX-V8cGhikYdtkRGAEe2VcuwpXxDUyTRa9xI7l8,1972
4
+ rgwfuncs/interactive_shell_lib.py,sha256=YeJBW9YgH5Nv77ONdOyIKFgtf0ItXStdlKGN9GGf8bU,4228
5
+ rgwfuncs/str_lib.py,sha256=ZI-SNVFy__theOl0HifLiRXtLQ3bJ8kfKzEiwiAEbOg,11391
6
+ rgwfuncs-0.0.106.dist-info/licenses/LICENSE,sha256=jLvt20gcUZYB8UOvyBvyKQ1qhYYhD__qP7ZDx2lPFkU,1062
7
+ rgwfuncs-0.0.106.dist-info/METADATA,sha256=hWc25xg1tl2OM7VcZa876gz37n9lV0XsyL1qkLGzVf0,42972
8
+ rgwfuncs-0.0.106.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ rgwfuncs-0.0.106.dist-info/entry_points.txt,sha256=j-c5IOPIQ0252EaOV6j6STio56sbXl2C4ym_fQ0lXx0,43
10
+ rgwfuncs-0.0.106.dist-info/top_level.txt,sha256=aGuVIzWsKiV1f2gCb6mynx0zx5ma0B1EwPGFKVEMTi4,9
11
+ rgwfuncs-0.0.106.dist-info/RECORD,,