rgwfuncs 0.0.42__py3-none-any.whl → 0.0.47__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_constant_expression, compute_constant_expression_involving_matrices, compute_constant_expression_involving_ordered_series, compute_prime_factors, expand_polynomial_expression, python_polynomial_expression_to_latex, simplify_polynomial_expression, solve_homogeneous_polynomial_expression
4
+ 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, python_polynomial_expression_to_latex, simplify_polynomial_expression, solve_homogeneous_polynomial_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 .interactive_shell_lib import interactive_shell
rgwfuncs/algebra_lib.py CHANGED
@@ -2,7 +2,9 @@ import re
2
2
  import math
3
3
  import ast
4
4
  # import numpy as np
5
- from sympy import symbols, latex, simplify, solve, diff, Expr
5
+ from sympy import symbols, latex, simplify, solve, diff, Expr, factor, cancel, Eq
6
+ from sympy.core.sympify import SympifyError
7
+ from sympy.core import S
6
8
  from sympy.parsing.sympy_parser import parse_expr
7
9
  from sympy import __all__ as sympy_functions
8
10
  from sympy.parsing.sympy_parser import (standard_transformations, implicit_multiplication_application)
@@ -320,6 +322,7 @@ def python_polynomial_expression_to_latex(
320
322
  latex_result = latex(expr)
321
323
  return latex_result
322
324
 
325
+
323
326
  def expand_polynomial_expression(
324
327
  expression: str,
325
328
  subs: Optional[Dict[str, float]] = None
@@ -327,15 +330,15 @@ def expand_polynomial_expression(
327
330
  """
328
331
  Expands a polynomial expression written in Python syntax and converts it to LaTeX format.
329
332
 
330
- This function takes an algebraic expression written in Python syntax,
331
- applies polynomial expansion, and converts the expanded expression
333
+ This function takes an algebraic expression written in Python syntax,
334
+ applies polynomial expansion, and converts the expanded expression
332
335
  to a LaTeX formatted string. The expression should be compatible with sympy.
333
336
 
334
337
  Parameters:
335
- expression (str): The algebraic expression to expand and convert to LaTeX.
338
+ expression (str): The algebraic expression to expand and convert to LaTeX.
336
339
  The expression should be written using Python syntax.
337
- subs (Optional[Dict[str, float]]): An optional dictionary of substitutions
338
- to apply to variables in the expression
340
+ subs (Optional[Dict[str, float]]): An optional dictionary of substitutions
341
+ to apply to variables in the expression
339
342
  before expansion.
340
343
 
341
344
  Returns:
@@ -345,15 +348,18 @@ def expand_polynomial_expression(
345
348
  ValueError: If the expression cannot be parsed due to syntax errors.
346
349
  """
347
350
  transformations = standard_transformations + (implicit_multiplication_application,)
348
-
351
+
349
352
  def parse_and_expand_expression(expr_str: str, sym_vars: Dict[str, symbols]) -> symbols:
350
353
  try:
351
354
  expr = parse_expr(expr_str, local_dict=sym_vars, transformations=transformations)
352
355
  if subs:
356
+ # Ensure that subs is a dictionary
357
+ if not isinstance(subs, dict):
358
+ raise ValueError(f"Substitutions must be a dictionary. Received: {subs}")
353
359
  subs_symbols = {symbols(k): v for k, v in subs.items()}
354
360
  expr = expr.subs(subs_symbols)
355
361
  return expr.expand()
356
- except (SyntaxError, ValueError, TypeError) as e:
362
+ except (SyntaxError, ValueError, TypeError, AttributeError) as e:
357
363
  raise ValueError(f"Error parsing expression: {expr_str}. Error: {e}")
358
364
 
359
365
  variable_names = set(re.findall(r'\b[a-zA-Z]\w*\b', expression))
@@ -364,6 +370,110 @@ def expand_polynomial_expression(
364
370
  return latex_result
365
371
 
366
372
 
373
+ def factor_polynomial_expression(
374
+ expression: str,
375
+ subs: Optional[Dict[str, float]] = None
376
+ ) -> str:
377
+ """
378
+ Factors a polynomial expression written in Python syntax and converts it to LaTeX format.
379
+
380
+ This function accepts an algebraic expression in Python syntax, performs polynomial factoring,
381
+ and translates the factored expression into a LaTeX formatted string.
382
+
383
+ Parameters:
384
+ expression (str): The algebraic expression to factor and convert to LaTeX.
385
+ subs (Optional[Dict[str, float]]): An optional dictionary of substitutions to apply before factoring.
386
+
387
+ Returns:
388
+ str: The LaTeX formatted string of the factored expression.
389
+
390
+ Raises:
391
+ ValueError: If the expression cannot be parsed due to syntax errors.
392
+ """
393
+ transformations = standard_transformations + (implicit_multiplication_application,)
394
+
395
+ def parse_and_factor_expression(expr_str: str, sym_vars: Dict[str, symbols]) -> symbols:
396
+ try:
397
+ expr = parse_expr(expr_str, local_dict=sym_vars, transformations=transformations)
398
+ if subs:
399
+ if not isinstance(subs, dict):
400
+ raise ValueError(f"Substitutions must be a dictionary. Received: {subs}")
401
+ subs_symbols = {symbols(k): v for k, v in subs.items()}
402
+ expr = expr.subs(subs_symbols)
403
+ return factor(expr)
404
+ except (SyntaxError, ValueError, TypeError, AttributeError) as e:
405
+ raise ValueError(f"Error parsing expression: {expr_str}. Error: {e}")
406
+
407
+ variable_names = set(re.findall(r'\b[a-zA-Z]\w*\b', expression))
408
+ sym_vars = {var: symbols(var) for var in variable_names}
409
+
410
+ expr = parse_and_factor_expression(expression, sym_vars)
411
+ latex_result = latex(expr)
412
+ return latex_result
413
+
414
+
415
+ def cancel_polynomial_expression(
416
+ expression: str,
417
+ subs: Optional[Dict[str, float]] = None
418
+ ) -> str:
419
+ """
420
+ Cancels common factors within a polynomial expression and converts it to LaTeX format.
421
+
422
+ This function parses an algebraic expression given in Python syntax, cancels any common factors,
423
+ and converts the resulting simplified expression into a LaTeX formatted string. The function can
424
+ also handle optional substitutions of variables before performing the cancellation.
425
+
426
+ Parameters:
427
+ expression (str): The algebraic expression to simplify and convert to LaTeX.
428
+ It should be a valid expression formatted using Python syntax.
429
+ subs (Optional[Dict[str, float]]): An optional dictionary where the keys are variable names in the
430
+ expression, and the values are the corresponding numbers to substitute
431
+ into the expression before simplification.
432
+
433
+ Returns:
434
+ str: The LaTeX formatted string of the simplified expression. If the expression involves
435
+ indeterminate forms due to operations like division by zero, a descriptive error message is returned instead.
436
+
437
+ Raises:
438
+ ValueError: If the expression cannot be parsed due to syntax errors or if operations result in
439
+ undefined behavior, such as division by zero.
440
+
441
+ """
442
+ transformations = standard_transformations + (implicit_multiplication_application,)
443
+
444
+ def parse_and_cancel_expression(expr_str: str, sym_vars: Dict[str, symbols]) -> symbols:
445
+ try:
446
+ expr = parse_expr(expr_str, local_dict=sym_vars, transformations=transformations)
447
+ if subs:
448
+ if not isinstance(subs, dict):
449
+ raise ValueError(f"Substitutions must be a dictionary. Received: {subs}")
450
+ subs_symbols = {symbols(k): v for k, v in subs.items()}
451
+ expr = expr.subs(subs_symbols)
452
+
453
+ canceled_expr = cancel(expr)
454
+
455
+ # Check for NaN or indeterminate forms
456
+ if canceled_expr.has(S.NaN) or canceled_expr.has(S.Infinity) or canceled_expr.has(S.ComplexInfinity):
457
+ return "Undefined result. This could be a division by zero error."
458
+
459
+ return canceled_expr
460
+
461
+ except (SyntaxError, ValueError, TypeError, AttributeError, ZeroDivisionError, SympifyError) as e:
462
+ return f"Error: {str(e)}"
463
+
464
+ variable_names = set(re.findall(r'\b[a-zA-Z]\w*\b', expression))
465
+ sym_vars = {var: symbols(var) for var in variable_names}
466
+
467
+ expr = parse_and_cancel_expression(expression, sym_vars)
468
+
469
+ # If the expression is already a string (i.e., "Undefined" or error message), return it directly
470
+ if isinstance(expr, str):
471
+ return expr
472
+
473
+ # Otherwise, convert to LaTeX as usual
474
+ latex_result = latex(expr)
475
+ return latex_result
476
+
367
477
 
368
478
  def simplify_polynomial_expression(
369
479
  expression: str,
@@ -566,28 +676,35 @@ def solve_homogeneous_polynomial_expression(
566
676
  ValueError: If the equation cannot be solved due to errors in expression or parameters.
567
677
  """
568
678
 
679
+ print("679", expression)
680
+ print("681", variable)
681
+ print("682", subs)
569
682
  try:
570
683
  # Create symbols for the variables in the expression
571
684
  variable_symbols = set(re.findall(r'\b[a-zA-Z]\w*\b', expression))
572
685
  sym_vars = {var: symbols(var) for var in variable_symbols}
573
686
 
574
- # Parse the expression and solve it
687
+ # Parse the expression
575
688
  expr = parse_expr(expression, local_dict=sym_vars)
576
- var_symbol = symbols(variable)
577
- solutions = solve(expr, var_symbol)
578
689
 
579
- # Apply substitutions if provided
690
+ # If substitutions are provided, apply them
580
691
  if subs:
581
- subs_symbols = {symbols(k): v for k, v in subs.items()}
582
- solutions = [simplify(sol.subs(subs_symbols)) for sol in solutions]
692
+ expr = expr.subs({symbols(k): v for k, v in subs.items()})
693
+
694
+ # Ensure the variable is treated as a symbol for solving
695
+ var_symbol = symbols(variable)
696
+
697
+ # Solve for the variable
698
+ eq = Eq(expr, 0)
699
+ solutions = solve(eq, var_symbol)
583
700
 
584
701
  # Convert solutions to LaTeX strings if possible
585
- latex_solutions = [
586
- latex(
587
- simplify(sol)) if sol.free_symbols else str(sol) for sol in solutions]
702
+ latex_solutions = [latex(simplify(sol)) for sol in solutions]
588
703
  result = r"\left[" + ", ".join(latex_solutions) + r"\right]"
589
- print("158", result)
704
+
705
+ print("704", result)
590
706
  return result
591
707
 
592
708
  except Exception as e:
593
709
  raise ValueError(f"Error solving the expression: {e}")
710
+
rgwfuncs/df_lib.py CHANGED
@@ -400,7 +400,6 @@ def load_data_from_query(db_preset_name: str, query: str) -> pd.DataFrame:
400
400
 
401
401
  return pd.DataFrame(rows, columns=columns)
402
402
 
403
-
404
403
  def query_athena(db_preset: Dict[str, Any], query: str) -> pd.DataFrame:
405
404
 
406
405
  def execute_athena_query(athena_client, query: str, database: str, output_bucket: str) -> str:
@@ -434,11 +433,10 @@ def load_data_from_query(db_preset_name: str, query: str) -> pd.DataFrame:
434
433
  data = [[col.get("VarCharValue", None) for col in row["Data"]] for row in rows[1:]]
435
434
  return pd.DataFrame(data, columns=columns)
436
435
 
437
-
438
436
  aws_region = db_preset['aws_region']
439
437
  database = db_preset['database']
440
438
  output_bucket = db_preset['output_bucket']
441
-
439
+
442
440
  athena_client = boto3.client(
443
441
  'athena',
444
442
  region_name=aws_region,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: rgwfuncs
3
- Version: 0.0.42
3
+ Version: 0.0.47
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
@@ -402,7 +402,63 @@ Expands a polynomial expression written in Python syntax and converts it into a
402
402
 
403
403
  --------------------------------------------------------------------------------
404
404
 
405
- ### 6. `simplify_polynomial_expression`
405
+ ### 7. `factor_polynomial_expression`
406
+
407
+ 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.
408
+
409
+ - Parameters:
410
+ - `expression` (str): The polynomial expression to factor and convert to LaTeX. This should be a valid expression formatted using Python syntax.
411
+ - `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.
412
+
413
+ - Returns:
414
+ - `str`: The LaTeX formatted string representing the factored expression.
415
+
416
+ - Raises:
417
+ - `ValueError`: If the expression cannot be parsed due to syntax errors.
418
+
419
+ - Example:
420
+
421
+ from rgwfuncs import factor_polynomial_expression
422
+
423
+ # Factor a polynomial expression and convert to LaTeX
424
+ latex_result1 = factor_polynomial_expression("x**2 - 4")
425
+ print(latex_result1) # Output: "\left(x - 2\right) \left(x + 2\right)"
426
+
427
+ # Factor with substituted values
428
+ latex_result2 = factor_polynomial_expression("x**2 - y**2", {"y": 3})
429
+ print(latex_result2) # Output: "\left(x - 3\right) \left(x + 3\right)"
430
+
431
+ --------------------------------------------------------------------------------
432
+
433
+ ### 8. `cancel_polynomial_expression`
434
+
435
+ 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.
436
+
437
+ - Parameters:
438
+ - `expression` (str): The algebraic expression to simplify and convert to LaTeX. This string should be formatted using Python syntax.
439
+ - `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.
440
+
441
+ - Returns:
442
+ - `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.
443
+
444
+ - Raises:
445
+ - `ValueError`: If the expression cannot be parsed due to syntax errors or involves undefined operations, such as division by zero.
446
+
447
+ - Example:
448
+
449
+ from rgwfuncs import cancel_polynomial_expression
450
+
451
+ # Cancel common factors within a polynomial expression
452
+ latex_result1 = cancel_polynomial_expression("(x**2 - 4) / (x - 2)")
453
+ print(latex_result1) # Output: "x + 2"
454
+
455
+ # Cancel with substituted values
456
+ latex_result2 = cancel_polynomial_expression("(x**2 - 4) / (x - 2)", {"x": 2})
457
+ print(latex_result2) # Output: "Undefined result. This could be a division by zero error."
458
+
459
+ --------------------------------------------------------------------------------
460
+
461
+ ### 9. `simplify_polynomial_expression`
406
462
 
407
463
  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.
408
464
 
@@ -435,7 +491,7 @@ Simplifies an algebraic expression in polynomial form and returns it in LaTeX fo
435
491
 
436
492
  --------------------------------------------------------------------------------
437
493
 
438
- ### 7. `solve_homogeneous_polynomial_expression`
494
+ ### 10. `solve_homogeneous_polynomial_expression`
439
495
 
440
496
  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.
441
497
 
@@ -0,0 +1,12 @@
1
+ rgwfuncs/__init__.py,sha256=vs8xv3IVx7KGpPxEXrIePD3gb_QI1XTXpD_n9817foA,1610
2
+ rgwfuncs/algebra_lib.py,sha256=9nnpF0dk3_EuLRlhACUXMQCg2uFbIAy6Fbk1CCssL_c,28423
3
+ rgwfuncs/df_lib.py,sha256=qqRQdakheLy8wMZRBfHwKyIp8DmdZIWfAiLKWgq03QU,68977
4
+ rgwfuncs/docs_lib.py,sha256=y3wSAOPO3qsA4HZ7xAtW8HimM8w-c8hjcEzMRLJ96ao,1960
5
+ rgwfuncs/interactive_shell_lib.py,sha256=A7EWsYxAfDev_N0-2GjRvAtp0bAwBPHIczXb8Gu9fzI,1107
6
+ rgwfuncs/str_lib.py,sha256=rtAdRlnSJIu3JhI-tA_A0wCiPK2m-zn5RoGpBxv_g-4,2228
7
+ rgwfuncs-0.0.47.dist-info/LICENSE,sha256=7EI8xVBu6h_7_JlVw-yPhhOZlpY9hP8wal7kHtqKT_E,1074
8
+ rgwfuncs-0.0.47.dist-info/METADATA,sha256=thxImUJuWvB1GTzLs1bCTt6jOOqhXYUehUs8uJLGd0w,55152
9
+ rgwfuncs-0.0.47.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
10
+ rgwfuncs-0.0.47.dist-info/entry_points.txt,sha256=j-c5IOPIQ0252EaOV6j6STio56sbXl2C4ym_fQ0lXx0,43
11
+ rgwfuncs-0.0.47.dist-info/top_level.txt,sha256=aGuVIzWsKiV1f2gCb6mynx0zx5ma0B1EwPGFKVEMTi4,9
12
+ rgwfuncs-0.0.47.dist-info/RECORD,,
@@ -1,12 +0,0 @@
1
- rgwfuncs/__init__.py,sha256=j1SH_GGf9EPXWvhKd_RWDMUI8GXvJGniq4whdmC-tRk,1550
2
- rgwfuncs/algebra_lib.py,sha256=OWltGhJqlP7mS0VszjeSICKQZjNlCrLjWVlaKwrb4Og,23435
3
- rgwfuncs/df_lib.py,sha256=b6uMBbj7JrTUusbBGSlGI6jJ37yCN5lb6Oiq-C9oGzg,68987
4
- rgwfuncs/docs_lib.py,sha256=y3wSAOPO3qsA4HZ7xAtW8HimM8w-c8hjcEzMRLJ96ao,1960
5
- rgwfuncs/interactive_shell_lib.py,sha256=A7EWsYxAfDev_N0-2GjRvAtp0bAwBPHIczXb8Gu9fzI,1107
6
- rgwfuncs/str_lib.py,sha256=rtAdRlnSJIu3JhI-tA_A0wCiPK2m-zn5RoGpBxv_g-4,2228
7
- rgwfuncs-0.0.42.dist-info/LICENSE,sha256=7EI8xVBu6h_7_JlVw-yPhhOZlpY9hP8wal7kHtqKT_E,1074
8
- rgwfuncs-0.0.42.dist-info/METADATA,sha256=xxKivycP7sQ5oLN65i5CIzl3H_yAMTf7HgO9uLUM_Vk,52072
9
- rgwfuncs-0.0.42.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
10
- rgwfuncs-0.0.42.dist-info/entry_points.txt,sha256=j-c5IOPIQ0252EaOV6j6STio56sbXl2C4ym_fQ0lXx0,43
11
- rgwfuncs-0.0.42.dist-info/top_level.txt,sha256=aGuVIzWsKiV1f2gCb6mynx0zx5ma0B1EwPGFKVEMTi4,9
12
- rgwfuncs-0.0.42.dist-info/RECORD,,