### Install formulas from source Source: https://github.com/vinci1it2000/formulas/blob/master/README.rst Installs the 'formulas' Python package by downloading the latest version from GitHub and running the setup script. This method is useful for installing development versions or when PyPI is not accessible. ```console python setup.py install ``` -------------------------------- ### Install formulas using pip Source: https://github.com/vinci1it2000/formulas/blob/master/README.rst Installs the 'formulas' Python package using pip. This is the standard method for installing Python packages from the Python Package Index (PyPI). ```console pip install formulas ``` -------------------------------- ### Install formulas with all extras Source: https://github.com/vinci1it2000/formulas/blob/master/README.rst Installs the 'formulas' package along with all its optional extras, such as 'excel' for compiling Excel workbooks and 'plot' for visualizing formula ASTs. This command ensures all functionalities are available. ```console pip install formulas[all] ``` -------------------------------- ### Install formulas development version Source: https://github.com/vinci1it2000/formulas/blob/master/README.rst Installs the development version of the 'formulas' package directly from its GitHub repository. This is useful for testing the latest features or contributing to the project. ```console pip install https://github.com/vinci1it2000/formulas/archive/dev.zip ``` -------------------------------- ### Load, Calculate, and Write Excel Workbook in Python Source: https://github.com/vinci1it2000/formulas/blob/master/README.rst Shows how to load an Excel workbook, compile it into a model, calculate its values, and write the results to a specified directory. This functionality requires the 'excel' extra to be installed. ```python import formulas import os.path as osp from setup import mydir # Assuming mydir is available from setup # Define paths for the Excel file and output directory fpath = osp.join(mydir, 'test/test_files/excel.xlsx') dir_output = osp.join(mydir, 'test/test_files/tmp') # Load the Excel workbook, compile it, and finish the model setup # Add circular=True if the workbook contains circular references xl_model = formulas.ExcelModel().loads(fpath).finish() # Calculate all values in the workbook calculation_result = xl_model.calculate() print(calculation_result) # Write the calculated results to the specified output directory write_result = xl_model.write(dirpath=dir_output) print(write_result) ``` -------------------------------- ### Handle Circular References Source: https://context7.com/vinci1it2000/formulas/llms.txt Explains how to enable and manage circular references in Excel workbooks using iterative calculations. The example shows loading a workbook with circular references enabled and calculating the solution, noting that cells involved will be resolved iteratively or may result in a #CIRC! error. ```python import formulas # Load workbook with circular=True to handle circular references # Assume 'circular_workbook.xlsx' is available xl_model = formulas.ExcelModel().loads('circular_workbook.xlsx').finish(circular=True) # Calculate with circular reference resolution solution = xl_model.calculate() # Access specific cell that was part of circular reference cell_value = solution.get("'[circular_workbook.xlsx]Sheet1'!A1") print(cell_value) ``` -------------------------------- ### Visualize Formula AST and Workflow in Python Source: https://github.com/vinci1it2000/formulas/blob/master/README.rst Illustrates how to visualize the Abstract Syntax Tree (AST) of a parsed Excel formula and its execution workflow using the `plot` method. This helps in understanding the formula's structure and data flow. ```python import formulas parser = formulas.Parser() func = parser.ast('=(1 + 1) + B3 / A2')[1].compile() # Plot the formula's Abstract Syntax Tree (AST) # Set view=False to prevent opening the plot in a browser print(func.plot(view=False)) # Plot the formula's execution workflow # Set view=False to prevent opening the plot in a browser print(func.plot(workflow=True, view=False)) ``` -------------------------------- ### Load, Calculate, and Write Excel Workbook Source: https://github.com/vinci1it2000/formulas/blob/master/binder/index.ipynb Demonstrates the process of loading an Excel file, performing calculations on its data, and then writing the results back. It also mentions the option to handle circular references. ```python xl_model = formulas.ExcelModel().loads("../test/test_files/excel.xlsx").finish(circular=True) xl_model.calculate() xl_model.write() ``` -------------------------------- ### Compile Excel Model to DispatchPipe in Python Source: https://github.com/vinci1it2000/formulas/blob/master/README.rst Compiles an Excel model into a DispatchPipe object, which acts as a function. Inputs and outputs are defined by data node IDs (cell references). Requires the 'formulas' library. Returns a DispatchPipe object. Can be called with input values to retrieve output values and plotted as a SiteMap. ```python >>> func = xl_model.compile( ... inputs=[ ... "'[excel.xlsx]'!INPUT_A", # First argument of the function. ... "'[excel.xlsx]DATA'!B3" # Second argument of the function. ... ], # To define function inputs. ... outputs=[ ... "'[excel.xlsx]DATA'!C2", "'[excel.xlsx]DATA'!C4" ... ] # To define function outputs. ... ) >>> func >>> [v.value[0, 0] for v in func(3, 1)] # To retrieve the data. [10.0, 4.0] >>> func.plot(view=False) # Set view=True to plot in the default browser. SiteMap({ExcelModel: SiteMap(...)}) ``` -------------------------------- ### Execute Formulas with Pushed Values in Python Source: https://context7.com/vinci1it2000/formulas/llms.txt This Python code snippet demonstrates executing formulas by first pushing data into specified ranges ('A1:A10' and 'B1'). The `func` function then calculates a result based on these values, simulating an Excel calculation. The output shows the calculated result and the logic behind it. ```python result = func( formulas.Ranges().push('A1:A10', value=[[i] for i in range(1, 11)]), formulas.Ranges().push('B1', value=15) ) print(result) # Output: Array([[85.0]], dtype=object) # Calculation: SUM(1..10) + IF(15>10, 15*2, 15/2) = 55 + 30 = 85 ``` -------------------------------- ### Load, Calculate, and Write Excel Workbook Source: https://context7.com/vinci1it2000/formulas/llms.txt Loads an entire Excel workbook, calculates all formulas within it, and optionally writes the results back to a file. Dependencies: 'formulas' library, 'openpyxl'. Input: Path to an Excel file. Output: Calculated workbook solution and potentially updated Excel file. ```python import formulas # Load the Excel workbook xl_model = formulas.ExcelModel().loads('excel.xlsx').finish() # Calculate all formulas in the workbook solution = xl_model.calculate() print(solution) # Output: Solution([...]) # Contains all calculated cell values # Write results to output directory xl_model.write(dirpath='output') # Output: {'EXCEL.XLSX': {Book: }} # The workbook is now saved with all formulas calculated ``` -------------------------------- ### Export and Import ExcelModel to/from JSON in Python Source: https://github.com/vinci1it2000/formulas/blob/master/README.rst Demonstrates exporting an ExcelModel to a JSON-compatible dictionary and then back into an ExcelModel object. This is useful for version control and maintenance. Requires the 'formulas' and 'json' libraries. The `to_dict` method creates the dictionary, `json.dumps` converts it to a JSON string, and `from_dict` reconstructs the model. ```python >>> import json >>> xl_dict = xl_model.to_dict() # To JSON-able dict. >>> xl_json = json.dumps(xl_dict, indent=True) # To JSON. >>> xl_model = formulas.ExcelModel().from_dict(json.loads(xl_json)) # From JSON. ``` -------------------------------- ### Load Partial Excel Model from Output Cells Source: https://context7.com/vinci1it2000/formulas/llms.txt Loads only the necessary cells and their dependencies required to calculate specific output cells from an Excel workbook. This optimizes memory usage and calculation time by avoiding the loading of unused parts of the workbook. Dependencies: 'formulas' library. Input: List of output cell identifiers. Output: A partial ExcelModel object containing only the relevant data nodes and dependencies. ```python import formulas # Load only the dependency chain for specific output cells xl_model = formulas.ExcelModel().from_ranges( "'[excel.xlsx]DATA'!C2:D2", # Output range "'[excel.xlsx]DATA'!B4" # Another output cell ) # View all loaded data nodes (only dependencies of outputs) sorted(xl_model.dsp.data_nodes) # Output: # ["'[excel.xlsx]'!INPUT_A", # "'[excel.xlsx]'!INPUT_B", # "'[excel.xlsx]'!INPUT_C", # "'[excel.xlsx]DATA'!A2", # "'[excel.xlsx]DATA'!A3", # "'[excel.xlsx]DATA'!A3:A4", # "'[excel.xlsx]DATA'!A4", # "'[excel.xlsx]DATA'!B2", # "'[excel.xlsx]DATA'!B3", # "'[excel.xlsx]DATA'!B4", # "'[excel.xlsx]DATA'!C2", # "'[excel.xlsx]DATA'!D2"] # Calculate the partial model solution = xl_model.calculate() ``` -------------------------------- ### Load Partial Excel Model from Ranges in Python Source: https://github.com/vinci1it2000/formulas/blob/master/README.rst Loads a partial Excel model using the `from_ranges` method, specifying output cells or ranges. This is useful for creating a model based on specific outputs. Requires the 'formulas' library. Returns an ExcelModel object, from which the DispatchPipe (dsp) can be accessed. The data_nodes attribute lists all recognized data nodes. ```python >>> xl = formulas.ExcelModel().from_ranges( ... "'[%s]DATA'!C2:D2" % fpath, # Output range. ... "'[%s]DATA'!B4" % fpath, # Output cell. ... ) >>> dsp = xl.dsp >>> sorted(dsp.data_nodes) ["'[excel.xlsx]'!INPUT_A", "'[excel.xlsx]'!INPUT_B", "'[excel.xlsx]'!INPUT_C", "'[excel.xlsx]DATA'!A2", "'[excel.xlsx]DATA'!A3", "'[excel.xlsx]DATA'!A3:A4", "'[excel.xlsx]DATA'!A4", "'[excel.xlsx]DATA'!B2", "'[excel.xlsx]DATA'!B3", "'[excel.xlsx]DATA'!B4", "'[excel.xlsx]DATA'!C2", "'[excel.xlsx]DATA'!D2"] ``` -------------------------------- ### Execute and Plot Formula Source: https://github.com/vinci1it2000/formulas/blob/master/binder/index.ipynb This code shows how to execute a compiled formula function with provided inputs and then visualize the formula's execution workflow. ```python func(1, 5) func.plot(workflow=True, view=False) ``` -------------------------------- ### Add Custom Functions to Parser Source: https://context7.com/vinci1it2000/formulas/llms.txt Demonstrates how to extend the 'formulas' parser by registering custom functions. It shows adding simple functions like 'MYFUNC' and more complex ones like 'DOUBLE_ADD', then parsing and executing formulas using these custom functions. ```python import formulas # Get the function registry FUNCTIONS = formulas.get_functions() # Add a custom function FUNCTIONS['MYFUNC'] = lambda x, y: 1 + y + x # Parse and execute formula with custom function func = formulas.Parser().ast('=MYFUNC(1, 2)')[1].compile() result = func() print(result) # Add another custom function with more complex logic FUNCTIONS['DOUBLE_ADD'] = lambda x, y, z: (x * 2) + y + z func2 = formulas.Parser().ast('=DOUBLE_ADD(5, 10, 3)')[1].compile() result2 = func2() print(result2) ``` -------------------------------- ### Compare Excel Workbook Results Source: https://context7.com/vinci1it2000/formulas/llms.txt Shows how to compare the calculated results of an Excel model against an expected output file. It includes setting tolerances for numeric comparisons and demonstrates how to write the calculated results to a new file for inspection. ```python import formulas # Load and calculate Excel model # Assume 'input.xlsx' is available xl_model = formulas.ExcelModel().loads('input.xlsx').finish() solution = xl_model.calculate() # Compare results with expected output file # Assume 'expected_output.xlsx' is available comparison = xl_model.compare( 'expected_output.xlsx', # Target file to compare against solution=solution, tolerance=0, # Relative tolerance for numeric comparison absolute_tolerance=0.000001 # Absolute tolerance for numeric values ) print(comparison) # Write calculated results to file for inspection xl_model.write(dirpath='output', solution=solution) ``` -------------------------------- ### Parse and Compile Excel Formula Source: https://github.com/vinci1it2000/formulas/blob/master/binder/index.ipynb This snippet demonstrates how to parse an Excel formula string using the 'formulas' library, compile it into an executable function, and then retrieve the order of its inputs. ```python import formulas func = formulas.Parser().ast('=(1 + 1) + B3 / A2')[1].compile() list(func.inputs) ``` -------------------------------- ### Calculate Excel Workbook with Specific Inputs and Outputs Source: https://github.com/vinci1it2000/formulas/blob/master/README.rst Demonstrates how to calculate an Excel workbook model with custom input values for specific cells and define which cells' outputs should be calculated. This allows for targeted calculations and overriding default values. ```python import formulas # Assume xl_model is already loaded and finished as in the previous example # Example: xl_model = formulas.ExcelModel().loads('excel.xlsx').finish() # Define custom inputs and desired outputs custom_inputs = { "'[excel.xlsx]'!INPUT_A": 3, # Overwrite default value for INPUT_A "'[excel.xlsx]DATA'!B3": 1 # Impose value to cell B3 } output_cells = [ "'[excel.xlsx]DATA'!C2", "'[excel.xlsx]DATA'!C4" ] # Perform calculation with specified inputs and outputs solution = xl_model.calculate(inputs=custom_inputs, outputs=output_cells) print(solution) ``` -------------------------------- ### Calculate Excel Model with Specific Inputs and Outputs Source: https://github.com/vinci1it2000/formulas/blob/master/binder/index.ipynb Shows how to calculate an Excel model by overriding default inputs and specifying which output cells to compute. This is useful for targeted calculations or imposing specific values. ```python xl_model.calculate( inputs={ "'[EXCEL.XLSX]DATA'!A2": 3, "'[EXCEL.XLSX]DATA'!B3": 1 }, outputs=[ "'[EXCEL.XLSX]DATA'!C2", "'[EXCEL.XLSX]DATA'!C4" ] ) ``` -------------------------------- ### Parse and Compile Excel Formula in Python Source: https://github.com/vinci1it2000/formulas/blob/master/README.rst Demonstrates parsing an Excel formula string, compiling it into an executable function, and retrieving the order of input variables. It uses the `formulas.Parser` class to interpret the formula. ```python import formulas parser = formulas.Parser() # Parse the formula and get the compiled function func = parser.ast('=(1 + 1) + B3 / A2')[1].compile() # Get the order of inputs for the formula print(list(func.inputs)) # Execute the compiled formula with sample inputs print(func(1, 5)) ``` -------------------------------- ### Parse Formula and Access Abstract Syntax Tree Source: https://context7.com/vinci1it2000/formulas/llms.txt Details how to parse an Excel formula and access its Abstract Syntax Tree (AST) before compilation. It demonstrates retrieving tokens, inspecting the AST builder, compiling the AST into a callable function, and accessing metadata such as function inputs and the formula name. ```python import formulas # Parse a formula and get both tokens and AST builder tokens, builder = formulas.Parser().ast('=SUM(A1:A10) + IF(B1>10, B1*2, B1/2)') # Inspect tokens print(f"Number of tokens: {len(tokens)}") for token in tokens[:5]: print(token) # Compile the AST func = builder.compile() # Get function metadata print(f"Inputs: {list(func.inputs.keys())}") print(f"Function name: {func.__name__}") ``` -------------------------------- ### Compile Excel Model to a Function Source: https://github.com/vinci1it2000/formulas/blob/master/binder/index.ipynb This code demonstrates how to compile an Excel model into a Python function with predefined inputs and outputs, identified by cell references. It also shows how to retrieve the results from the executed function. ```python func = xl_model.compile( inputs=[ "'[EXCEL.XLSX]DATA'!A2", "'[EXCEL.XLSX]DATA'!B3" ], outputs=[ "'[EXCEL.XLSX]DATA'!C2", "'[EXCEL.XLSX]DATA'!C4" ] ) [v.value[0, 0] for v in func(3, 1)] func.plot(view=False) ``` -------------------------------- ### Compile Excel Workbook to Standalone Python Function Source: https://context7.com/vinci1it2000/formulas/llms.txt Compiles an Excel model into a standalone Python function, defining specific inputs and outputs. This allows the Excel logic to be executed as a reusable Python function without loading the entire workbook each time. Dependencies: 'formulas' library. Input: Excel workbook, list of input cell IDs, list of output cell IDs. Output: A Python function that accepts input values and returns calculated output values. ```python import formulas xl_model = formulas.ExcelModel().loads('excel.xlsx').finish() # Compile to a function with specific inputs and outputs func = xl_model.compile( inputs=[ "'[excel.xlsx]'!INPUT_A", # First function argument "'[excel.xlsx]DATA'!B3" # Second function argument ], outputs=[ "'[excel.xlsx]DATA'!C2", # First return value "'[excel.xlsx]DATA'!C4" ] ) # Use the compiled function results = func(3, 1) print([v.value[0, 0] for v in results]) # Output: [10.0, 4.0] # Function can be called repeatedly with different inputs results2 = func(5, 2) print([v.value[0, 0] for v in results2]) # Output: [12.0, 9.0] # Different inputs produce different outputs ``` -------------------------------- ### Plot Excel Workbook Dependency Graph in Python Source: https://github.com/vinci1it2000/formulas/blob/master/README.rst Shows how to visualize the dependency graph of an Excel workbook model using the `dsp.plot` method. This graph illustrates the relationships and dependencies between different cells in the workbook. ```python import formulas # Assume xl_model is already loaded and finished # Example: xl_model = formulas.ExcelModel().loads('excel.xlsx').finish() # Get the dispatcher object which holds the dependency graph dsp = xl_model.dsp # Plot the dependency graph # Set view=False to prevent opening the plot in a browser print(dsp.plot(view=False)) ``` -------------------------------- ### Calculate Excel Workbook with Custom Inputs/Outputs Source: https://context7.com/vinci1it2000/formulas/llms.txt Calculates an Excel workbook while allowing specific input cells to be overridden and restricting calculations to a defined set of output cells. Dependencies: 'formulas' library. Input: Excel workbook path, custom input values, desired output cells. Output: A dictionary containing the calculated values for the specified output cells. ```python import formulas xl_model = formulas.ExcelModel().loads('excel.xlsx').finish() # Override inputs and select specific outputs solution = xl_model.calculate( inputs={ "'[excel.xlsx]'!INPUT_A": 3, # Override input cell value "'[excel.xlsx]DATA'!B3": 1 # Force specific cell value }, outputs=[ "'[excel.xlsx]DATA'!C2", # Calculate only these cells "'[excel.xlsx]DATA'!C4" ] ) # Access calculated values for cell_id, value in solution.items(): print(f"{cell_id}: {value}") # Output: # '[excel.xlsx]'!INPUT_A: ('[excel.xlsx]DATA'!A2)=[[3]] # '[excel.xlsx]DATA'!B3: ('[excel.xlsx]DATA'!B3)=[[1]] # '[excel.xlsx]DATA'!C2: ('[excel.xlsx]DATA'!C2)=[[10.0]] # '[excel.xlsx]DATA'!C4: ('[excel.xlsx]DATA'!C4)=[[4.0]] ``` -------------------------------- ### Export to JSON and Save to File Source: https://context7.com/vinci1it2000/formulas/llms.txt Converts an Excel model to a JSON-serializable dictionary, prints it, and saves it to a file named 'model.json'. It also demonstrates loading the data back from the JSON file and restoring the Excel model. ```python import json import formulas # Assume xl_model is an initialized ExcelModel object # xl_model = formulas.ExcelModel().loads('input.xlsx').finish() # Export to JSON-serializable dictionary xl_dict = xl_model.to_dict() print(json.dumps(xl_dict, indent=2)) # Save to JSON file with open('model.json', 'w') as f: json.dump(xl_dict, f, indent=2) # Load back from JSON with open('model.json', 'r') as f: xl_dict_loaded = json.load(f) xl_model_restored = formulas.ExcelModel().from_dict(xl_dict_loaded) solution = xl_model_restored.calculate() ``` -------------------------------- ### Add and Use Custom Function in Formulas Source: https://github.com/vinci1it2000/formulas/blob/master/binder/index.ipynb This snippet shows how to define a custom Python function and register it with the 'formulas' library. It then demonstrates parsing and executing a formula that utilizes this custom function. ```python import formulas FUNCTIONS = formulas.get_functions() FUNCTIONS['MYFUNC'] = lambda x, y: 1 + y + x func = formulas.Parser().ast('=MYFUNC(1, 2)')[1].compile() func() ``` -------------------------------- ### Export Excel Model to JSON Source: https://context7.com/vinci1it2000/formulas/llms.txt Exports an loaded Excel workbook model into a JSON format. This is useful for version control, sharing, or programmatic editing of the workbook structure and formulas. Dependencies: 'formulas' library, 'json' library. Input: An initialized ExcelModel object. Output: A JSON string representing the Excel model. ```python import formulas import json # Load Excel workbook xl_model = formulas.ExcelModel().loads('excel.xlsx').finish() # Export model to JSON (implementation not shown in provided text, but would follow) # json_output = json.dumps(xl_model.to_dict()) # Example hypothetical method ``` -------------------------------- ### Plot Excel Cell Dependency Graph Source: https://github.com/vinci1it2000/formulas/blob/master/binder/index.ipynb This snippet illustrates how to plot the dependency graph of an Excel model, visualizing the relationships between different cells. ```python dsp = xl_model.dsp dsp.plot(view=False) ``` -------------------------------- ### Add Custom Function to Formulas Parser in Python Source: https://github.com/vinci1it2000/formulas/blob/master/README.rst Shows how to add a custom function to the 'formulas' library's parser. A lambda function is defined and assigned to a new key in the global functions dictionary. The custom function can then be used in formulas parsed by the library. Requires the 'formulas' library. ```python >>> import formulas >>> FUNCTIONS = formulas.get_functions() >>> FUNCTIONS['MYFUNC'] = lambda x, y: 1 + y + x >>> func = formulas.Parser().ast('=MYFUNC(1, 2)')[1].compile() >>> func() 4 ``` -------------------------------- ### Parse and Execute Excel Formula String Source: https://context7.com/vinci1it2000/formulas/llms.txt Parses an Excel formula string and compiles it into an executable Python function. It identifies input cell references and allows the function to be called with corresponding values. Dependencies: 'formulas' library. Input: Excel formula string. Output: Compiled function and execution result. ```python import formulas # Parse a formula with cell references func = formulas.Parser().ast('=(1 + 1) + B3 / A2')[1].compile() # Get the input cell references in order list(func.inputs) # Output: ['A2', 'B3'] # Execute the compiled formula with values for A2=1 and B3=5 result = func(1, 5) print(result) # Output: Array(7.0, dtype=object) # The result is: (1 + 1) + 5 / 1 = 2 + 5 = 7.0 ``` -------------------------------- ### Work with Cell Ranges Source: https://context7.com/vinci1it2000/formulas/llms.txt Illustrates how to use the 'formulas.Ranges' class to manage and manipulate cell references and their values. It covers pushing individual cells, ranges with array values, accessing range values, combining ranges, and retrieving range information. ```python import formulas import numpy as np # Create a Ranges object rng = formulas.Ranges() # Push a cell reference with value rng.push('A1', value=10) print(rng) # Push a range with array values values = np.array([[1, 2], [3, 4]], dtype=object) rng2 = formulas.Ranges().push('B1:C2', value=values) print(rng2) # Access the value print(rng2.value) # Combine ranges using union operator rng3 = rng | rng2 print(rng3) # Get range information range_info = formulas.Ranges.get_range('A1:B10') print(range_info) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.