rgwfuncs 0.0.26__py3-none-any.whl → 0.0.27__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
@@ -1,7 +1,7 @@
1
1
  # This file is automatically generated
2
2
  # Dynamically importing functions from modules
3
3
 
4
- from .algebra_lib import compute_algebraic_expression, get_prime_factors_latex, simplify_algebraic_expression, solve_algebraic_expression
4
+ from .algebra_lib import compute_algebraic_expression, compute_matrix_operation, compute_ordered_series_operation, get_prime_factors_latex, simplify_algebraic_expression, solve_algebraic_expression
5
5
  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, 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
6
6
  from .docs_lib import docs
7
7
  from .str_lib import send_telegram_message
rgwfuncs/algebra_lib.py CHANGED
@@ -1,6 +1,7 @@
1
1
  import re
2
2
  import math
3
3
  import ast
4
+ # import numpy as np
4
5
  from sympy import symbols, latex, simplify, solve, diff, Expr
5
6
  from sympy.parsing.sympy_parser import parse_expr
6
7
  from typing import Tuple, List, Dict, Optional
@@ -242,6 +243,198 @@ def solve_algebraic_expression(
242
243
  raise ValueError(f"Error solving the expression: {e}")
243
244
 
244
245
 
246
+ def compute_matrix_operation(expression: str) -> str:
247
+ """
248
+ Computes the result of a matrix-like operation on 1D or 2D list inputs and returns it as a LaTeX string.
249
+
250
+ Evaluates an operation where lists are treated as matrices, performs operations on them sequentially, and
251
+ returns the result formatted as a LaTeX-style string.
252
+
253
+ Parameters:
254
+ expression (str): The matrix operation expression to compute. Example format includes operations such as "+", "-", "*", "/".
255
+
256
+ Returns:
257
+ str: The LaTeX-formatted string representation of the result or a message indicating an error in dimensions.
258
+ """
259
+
260
+ def elementwise_operation(matrix1: List[List[float]], matrix2: List[List[float]], operation: str) -> List[List[float]]:
261
+ if len(matrix1) != len(matrix2) or any(len(row1) != len(row2) for row1, row2 in zip(matrix1, matrix2)):
262
+ return "Operations between matrices must involve matrices of the same dimension"
263
+
264
+ if operation == '+':
265
+ return [[a + b for a, b in zip(row1, row2)] for row1, row2 in zip(matrix1, matrix2)]
266
+ elif operation == '-':
267
+ return [[a - b for a, b in zip(row1, row2)] for row1, row2 in zip(matrix1, matrix2)]
268
+ elif operation == '*':
269
+ return [[a * b for a, b in zip(row1, row2)] for row1, row2 in zip(matrix1, matrix2)]
270
+ elif operation == '/':
271
+ return [[a / b for a, b in zip(row1, row2) if b != 0] for row1, row2 in zip(matrix1, matrix2)]
272
+ else:
273
+ return f"Unsupported operation {operation}"
274
+
275
+ try:
276
+ # Use a stack-based method to properly parse matrices
277
+ elements = []
278
+ buffer = ''
279
+ bracket_level = 0
280
+ operators = set('+-*/')
281
+
282
+ for char in expression:
283
+ if char == '[':
284
+ if bracket_level == 0 and buffer.strip():
285
+ elements.append(buffer.strip())
286
+ buffer = ''
287
+ bracket_level += 1
288
+ elif char == ']':
289
+ bracket_level -= 1
290
+ if bracket_level == 0:
291
+ buffer += char
292
+ elements.append(buffer.strip())
293
+ buffer = ''
294
+ continue
295
+ if bracket_level == 0 and char in operators:
296
+ if buffer.strip():
297
+ elements.append(buffer.strip())
298
+ buffer = ''
299
+ elements.append(char)
300
+ else:
301
+ buffer += char
302
+
303
+ if buffer.strip():
304
+ elements.append(buffer.strip())
305
+
306
+ result = ast.literal_eval(elements[0])
307
+
308
+ if not any(isinstance(row, list) for row in result):
309
+ result = [result] # Convert 1D matrix to 2D
310
+
311
+ i = 1
312
+ while i < len(elements):
313
+ operation = elements[i]
314
+ matrix = ast.literal_eval(elements[i + 1])
315
+
316
+ if not any(isinstance(row, list) for row in matrix):
317
+ matrix = [matrix]
318
+
319
+ operation_result = elementwise_operation(result, matrix, operation)
320
+
321
+ # Check if the operation resulted in an error message
322
+ if isinstance(operation_result, str):
323
+ return operation_result
324
+
325
+ result = operation_result
326
+ i += 2
327
+
328
+ # Create a LaTeX-style matrix representation
329
+ matrix_entries = '\\\\'.join(' & '.join(str(x) for x in row) for row in result)
330
+ return r"\begin{bmatrix}" + f"{matrix_entries}" + r"\end{bmatrix}"
331
+
332
+ except Exception as e:
333
+ return f"Error computing matrix operation: {e}"
334
+
335
+
336
+ def compute_ordered_series_operation(expression: str) -> str:
337
+ """
338
+ Computes the result of operations on ordered series expressed as 1D lists, including discrete difference (ddd),
339
+ and returns it as a string.
340
+
341
+ The function first applies the discrete difference operator to any series where applicable, then evaluates
342
+ arithmetic operations between series.
343
+
344
+ Parameters:
345
+ expression (str): The series operation expression to compute. Includes operations "+", "-", "*", "/", and "ddd".
346
+
347
+ Returns:
348
+ str: The string representation of the resultant series after performing operations, or an error message
349
+ if the series lengths do not match.
350
+
351
+ Raises:
352
+ ValueError: If the expression cannot be evaluated.
353
+ """
354
+
355
+ def elementwise_operation(series1: List[float], series2: List[float], operation: str) -> List[float]:
356
+ if len(series1) != len(series2):
357
+ return "Operations between ordered series must involve series of equal length"
358
+
359
+ if operation == '+':
360
+ return [a + b for a, b in zip(series1, series2)]
361
+ elif operation == '-':
362
+ return [a - b for a, b in zip(series1, series2)]
363
+ elif operation == '*':
364
+ return [a * b for a, b in zip(series1, series2)]
365
+ elif operation == '/':
366
+ return [a / b for a, b in zip(series1, series2) if b != 0]
367
+ else:
368
+ return f"Unsupported operation {operation}"
369
+
370
+ def discrete_difference(series: list) -> list:
371
+ """Computes the discrete difference of a series."""
372
+ return [series[i + 1] - series[i] for i in range(len(series) - 1)]
373
+
374
+ try:
375
+ # First, apply the discrete difference operator where applicable
376
+ pattern = r'ddd\((\[[^\]]*\])\)'
377
+ matches = re.findall(pattern, expression)
378
+
379
+ for match in matches:
380
+ if match.strip() == '[]':
381
+ result_series = [] # Handle the empty list case
382
+ else:
383
+ series = ast.literal_eval(match)
384
+ result_series = discrete_difference(series)
385
+ expression = expression.replace(f'ddd({match})', str(result_series))
386
+
387
+ # Now parse and evaluate the full expression with basic operations
388
+ elements = []
389
+ buffer = ''
390
+ bracket_level = 0
391
+ operators = set('+-*/')
392
+
393
+ for char in expression:
394
+ if char == '[':
395
+ if bracket_level == 0 and buffer.strip():
396
+ elements.append(buffer.strip())
397
+ buffer = ''
398
+ bracket_level += 1
399
+ elif char == ']':
400
+ bracket_level -= 1
401
+ if bracket_level == 0:
402
+ buffer += char
403
+ elements.append(buffer.strip())
404
+ buffer = ''
405
+ continue
406
+ if bracket_level == 0 and char in operators:
407
+ if buffer.strip():
408
+ elements.append(buffer.strip())
409
+ buffer = ''
410
+ elements.append(char)
411
+ else:
412
+ buffer += char
413
+
414
+ if buffer.strip():
415
+ elements.append(buffer.strip())
416
+
417
+ result = ast.literal_eval(elements[0])
418
+
419
+ i = 1
420
+ while i < len(elements):
421
+ operation = elements[i]
422
+ series = ast.literal_eval(elements[i + 1])
423
+ operation_result = elementwise_operation(result, series, operation)
424
+
425
+ # Check if the operation resulted in an error message
426
+ if isinstance(operation_result, str):
427
+ return operation_result
428
+
429
+ result = operation_result
430
+ i += 2
431
+
432
+ return str(result)
433
+
434
+ except Exception as e:
435
+ return f"Error computing ordered series operation: {e}"
436
+
437
+
245
438
  def get_prime_factors_latex(n: int) -> str:
246
439
  """
247
440
  Computes the prime factors of a number and returns the factorization as a LaTeX string.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: rgwfuncs
3
- Version: 0.0.26
3
+ Version: 0.0.27
4
4
  Summary: A functional programming paradigm for mathematical modelling and data science
5
5
  Home-page: https://github.com/ryangerardwilson/rgwfunc
6
6
  Author: Ryan Gerard Wilson
@@ -252,6 +252,66 @@ Computes prime factors of a number and presents them in LaTeX format.
252
252
 
253
253
  --------------------------------------------------------------------------------
254
254
 
255
+ ### 5. `compute_matrix_operation`
256
+
257
+ Computes the results of 1D or 2D matrix operations and formats them as LaTeX strings.
258
+
259
+ - **Parameters:**
260
+ - `expression` (str): A string representing a sequence of matrix operations involving either 1D or 2D lists. Supported operations include addition (`+`), subtraction (`-`), multiplication (`*`), and division (`/`).
261
+
262
+ - **Returns:**
263
+ - `str`: The LaTeX-formatted string representation of the computed matrix, or an error message if the operations cannot be performed due to dimensional mismatches.
264
+
265
+ - **Example:**
266
+
267
+ from rgwfuncs import compute_matrix_operation
268
+
269
+ # Example with addition of 2D matrices
270
+ result = compute_matrix_operation("[[2, 6, 9], [1, 3, 5]] + [[1, 2, 3], [4, 5, 6]]")
271
+ print(result) # Output: \begin{bmatrix}3 & 8 & 12\\5 & 8 & 11\end{bmatrix}
272
+
273
+ # Example of mixed operations with 1D matrices treated as 2D
274
+ result = compute_matrix_operation("[3, 6, 9] + [1, 2, 3] - [2, 2, 2]")
275
+ print(result) # Output: \begin{bmatrix}2 & 6 & 10\end{bmatrix}
276
+
277
+ # Example with dimension mismatch
278
+ result = compute_matrix_operation("[[4, 3, 51]] + [[1, 1]]")
279
+ print(result) # Output: Operations between matrices must involve matrices of the same dimension
280
+
281
+ This function performs elementwise operations on both 1D and 2D matrices represented as Python lists and formats the result as a LaTeX string. It handles operations sequentially from left to right and gracefully handles dimension mismatches by returning a meaningful message. It utilizes Python's `ast.literal_eval` for safe and robust parsing.
282
+
283
+ --------------------------------------------------------------------------------
284
+
285
+ ### 6. `compute_ordered_series_operations`
286
+
287
+ Computes the result of operations on ordered series expressed as 1D lists, including the discrete difference operator `ddd`.
288
+
289
+ - **Parameters:**
290
+ - `expression` (str): A series operation expression. Supports operations such as "+", "-", "*", "/", and `ddd` for discrete differences.
291
+
292
+ - **Returns:**
293
+ - `str`: The string representation of the resultant series after performing operations, or an error message if series lengths do not match.
294
+
295
+ - **Example:**
296
+
297
+ from rgwfuncs import compute_ordered_series_operations
298
+
299
+ # Example with addition and discrete differences
300
+ result = compute_ordered_series_operations("ddd([2, 6, 9, 60]) + ddd([78, 79, 80])")
301
+ print(result) # Output: [4, 3, 51] + [1, 1]
302
+
303
+ # Example with elementwise subtraction
304
+ result = compute_ordered_series_operations("[10, 15, 21] - [5, 5, 5]")
305
+ print(result) # Output: [5, 10, 16]
306
+
307
+ # Example with length mismatch
308
+ result = compute_ordered_series_operations("[4, 3, 51] + [1, 1]")
309
+ print(result) # Output: Operations between ordered series must involve series of equal length
310
+
311
+ This function first applies the discrete difference operator to any series where applicable, then evaluates arithmetic operations between series. It returns a string representation of the result or an error message if the series lengths do not match. The function is robust, directly parsing and evaluating given series expressions with safety checks in place.
312
+
313
+ --------------------------------------------------------------------------------
314
+
255
315
  ## String Based Functions
256
316
 
257
317
  ### 1. send_telegram_message
@@ -0,0 +1,11 @@
1
+ rgwfuncs/__init__.py,sha256=6QXVaHomLh1AIbC-b-edLf-GS1oEqRT-JffHPNIKowA,1375
2
+ rgwfuncs/algebra_lib.py,sha256=VZS0d-sUGJvfHv00HmgD1htxBGbugsKkKuUKsJbLPkI,18205
3
+ rgwfuncs/df_lib.py,sha256=G_H3PXNVeseX2YLjkkrmO9eXA_7r29swUZlbPBDZjXA,66612
4
+ rgwfuncs/docs_lib.py,sha256=y3wSAOPO3qsA4HZ7xAtW8HimM8w-c8hjcEzMRLJ96ao,1960
5
+ rgwfuncs/str_lib.py,sha256=rtAdRlnSJIu3JhI-tA_A0wCiPK2m-zn5RoGpBxv_g-4,2228
6
+ rgwfuncs-0.0.27.dist-info/LICENSE,sha256=7EI8xVBu6h_7_JlVw-yPhhOZlpY9hP8wal7kHtqKT_E,1074
7
+ rgwfuncs-0.0.27.dist-info/METADATA,sha256=NSNgM-VFveOpzvmosZgjg7kSC9KovbyXspCTXCdMdrU,41874
8
+ rgwfuncs-0.0.27.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
9
+ rgwfuncs-0.0.27.dist-info/entry_points.txt,sha256=j-c5IOPIQ0252EaOV6j6STio56sbXl2C4ym_fQ0lXx0,43
10
+ rgwfuncs-0.0.27.dist-info/top_level.txt,sha256=aGuVIzWsKiV1f2gCb6mynx0zx5ma0B1EwPGFKVEMTi4,9
11
+ rgwfuncs-0.0.27.dist-info/RECORD,,
@@ -1,11 +0,0 @@
1
- rgwfuncs/__init__.py,sha256=SZg1HPP5D_3QimoYFH8zongQ9D9XPZWp-Qi-MZglvXw,1315
2
- rgwfuncs/algebra_lib.py,sha256=1_ZTDVdfZcnXTlOOZlI2sAyJm2gA1lyje8l3h68kjlI,10902
3
- rgwfuncs/df_lib.py,sha256=G_H3PXNVeseX2YLjkkrmO9eXA_7r29swUZlbPBDZjXA,66612
4
- rgwfuncs/docs_lib.py,sha256=y3wSAOPO3qsA4HZ7xAtW8HimM8w-c8hjcEzMRLJ96ao,1960
5
- rgwfuncs/str_lib.py,sha256=rtAdRlnSJIu3JhI-tA_A0wCiPK2m-zn5RoGpBxv_g-4,2228
6
- rgwfuncs-0.0.26.dist-info/LICENSE,sha256=7EI8xVBu6h_7_JlVw-yPhhOZlpY9hP8wal7kHtqKT_E,1074
7
- rgwfuncs-0.0.26.dist-info/METADATA,sha256=VXXptuvGxZt1riPsQjIGkYTnyxvikcWht9sjcnLEpU4,38637
8
- rgwfuncs-0.0.26.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
9
- rgwfuncs-0.0.26.dist-info/entry_points.txt,sha256=j-c5IOPIQ0252EaOV6j6STio56sbXl2C4ym_fQ0lXx0,43
10
- rgwfuncs-0.0.26.dist-info/top_level.txt,sha256=aGuVIzWsKiV1f2gCb6mynx0zx5ma0B1EwPGFKVEMTi4,9
11
- rgwfuncs-0.0.26.dist-info/RECORD,,