Spaces:
Runtime error
Runtime error
Download app.py from shahnawaz1365/PetroBotAI: direct link, hf CLI and curl.
- Browser
- Download file 30.1 kB
-
https://huggingface.co/spaces/shahnawaz1365/PetroBotAI/resolve/main/app.py
- Command line
-
hf download hf://spaces/shahnawaz1365/PetroBotAI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/shahnawaz1365/PetroBotAI/resolve/main/app.py
30.1 kB
| import re | |
| import math | |
| import numpy as np | |
| import pandas as pd | |
| from typing import Dict, List, Tuple, Union, Optional | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| from sklearn.metrics.pairwise import cosine_similarity | |
| import json | |
| import gradio as gr | |
| import matplotlib.pyplot as plt | |
| from io import BytesIO | |
| import base64 | |
| class OilGasChatbot: | |
| def __init__(self): | |
| # Initialize conversation context and history | |
| self.context = {} | |
| self.conversation_history = [] | |
| # Load predefined intents and their training phrases | |
| self.load_intent_data() | |
| # Prepare vectorizer for intent classification | |
| self.train_intent_classifier() | |
| # Unit conversion dictionaries | |
| self.pressure_units = { | |
| "psi": 1.0, | |
| "bar": 14.5038, | |
| "kpa": 0.145038, | |
| "mpa": 145.038 | |
| } | |
| self.density_units = { | |
| "ppg": 1.0, # pounds per gallon | |
| "kg/m3": 0.00835, | |
| "sg": 8.345, # specific gravity | |
| "psi/ft": 0.052 | |
| } | |
| self.length_units = { | |
| "ft": 1.0, | |
| "m": 3.28084, | |
| "km": 3280.84, | |
| "mi": 5280.0 | |
| } | |
| self.flowrate_units = { | |
| "gpm": 1.0, # gallons per minute | |
| "bpm": 42.0, # barrels per minute | |
| "l/s": 15.8503, # liters per second | |
| "m3/h": 4.4029 # cubic meters per hour | |
| } | |
| # Map intents to functions | |
| self.intent_map = { | |
| "hydrostatic_pressure": self.calculate_hydrostatic_pressure, | |
| "ecd": self.calculate_ecd, | |
| "kick_tolerance": self.calculate_kick_tolerance, | |
| "drilling_hydraulics": self.calculate_drilling_hydraulics, | |
| "ipr_calculation": self.calculate_ipr, | |
| "tpr_calculation": self.calculate_tpr, | |
| "darcy_flow": self.calculate_darcy_flow, | |
| "pipeline_pressure_drop": self.calculate_pipeline_pressure_drop, | |
| "help": self.provide_help, | |
| "unit_convert": self.convert_units, | |
| "greeting": self.greeting, | |
| "farewell": self.farewell, | |
| "explain_concept": self.explain_concept, | |
| "clear_parameters": self.clear_parameters | |
| } | |
| # Load knowledge base | |
| self.load_knowledge_base() | |
| def load_intent_data(self): | |
| """Load predefined intents and their training phrases""" | |
| self.intent_data = { | |
| "hydrostatic_pressure": [ | |
| "calculate hydrostatic pressure", | |
| "what is the hydrostatic pressure", | |
| "find bottom hole pressure", | |
| "determine bhp", | |
| "compute the pressure at depth", | |
| "what's the pressure at bottom hole", | |
| "calculate the hydrostatic head", | |
| "hydrostatic pressure calculation" | |
| ], | |
| "ecd": [ | |
| "calculate ecd", | |
| "what is the equivalent circulating density", | |
| "determine ecd", | |
| "find the equivalent mud weight while circulating", | |
| "calculate equivalent circulating density", | |
| "what's the ecd for this mud", | |
| "compute ecd value" | |
| ], | |
| "kick_tolerance": [ | |
| "calculate kick tolerance", | |
| "what is the kick tolerance", | |
| "determine maximum allowable kick", | |
| "compute kick tolerance volume", | |
| "what influx can this well handle", | |
| "maximum kick volume calculation" | |
| ], | |
| "drilling_hydraulics": [ | |
| "calculate pressure loss", | |
| "determine hydraulic horsepower", | |
| "optimize bit hydraulics", | |
| "calculate annular velocity", | |
| "what's the pressure drop in the drill string", | |
| "compute circulation pressure losses" | |
| ], | |
| "ipr_calculation": [ | |
| "calculate inflow performance", | |
| "determine ipr curve", | |
| "what's the production rate at this drawdown", | |
| "vogel ipr calculation", | |
| "find productivity index", | |
| "calculate well deliverability" | |
| ], | |
| "tpr_calculation": [ | |
| "calculate tubing performance", | |
| "determine tpr curve", | |
| "what's the flowing tubing pressure", | |
| "calculate pressure drop in tubing", | |
| "find tubing performance curve" | |
| ], | |
| "darcy_flow": [ | |
| "calculate flow using darcy's law", | |
| "determine permeability", | |
| "what's the flow rate through porous media", | |
| "compute darcy flow rate", | |
| "darcy equation calculation" | |
| ], | |
| "pipeline_pressure_drop": [ | |
| "calculate pipeline pressure drop", | |
| "determine optimal pipe diameter", | |
| "what's the pressure loss in this pipeline", | |
| "compute erosional velocity", | |
| "find pressure gradient in pipeline" | |
| ], | |
| "unit_convert": [ | |
| "convert units", | |
| "change from psi to bar", | |
| "what is 10 ppg in kg/m3", | |
| "convert meters to feet", | |
| "change units from ppg to sg" | |
| ], | |
| "help": [ | |
| "what can you do", | |
| "help me", | |
| "what calculations can you perform", | |
| "show me available commands", | |
| "list your capabilities", | |
| "how to use this chatbot" | |
| ], | |
| "greeting": [ | |
| "hello", | |
| "hi there", | |
| "good morning", | |
| "hey", | |
| "greetings" | |
| ], | |
| "farewell": [ | |
| "goodbye", | |
| "bye", | |
| "see you later", | |
| "exit", | |
| "quit" | |
| ], | |
| "explain_concept": [ | |
| "explain hydrostatic pressure", | |
| "what is ecd", | |
| "describe kick tolerance", | |
| "define drilling hydraulics", | |
| "explain the concept of ipr", | |
| "what does tpr mean" | |
| ], | |
| "clear_parameters": [ | |
| "clear parameters", | |
| "reset context", | |
| "clear inputs", | |
| "start over", | |
| "reset calculations" | |
| ] | |
| } | |
| def train_intent_classifier(self): | |
| """Prepare the TF-IDF vectorizer for intent classification""" | |
| # Prepare data for training | |
| training_texts = [] | |
| self.training_intents = [] | |
| for intent, phrases in self.intent_data.items(): | |
| for phrase in phrases: | |
| training_texts.append(phrase) | |
| self.training_intents.append(intent) | |
| # Create and fit TF-IDF vectorizer | |
| self.vectorizer = TfidfVectorizer(ngram_range=(1, 2), min_df=1) | |
| self.tfidf_matrix = self.vectorizer.fit_transform(training_texts) | |
| def classify_intent(self, text): | |
| """Classify user input into an intent using TF-IDF and cosine similarity""" | |
| # Transform input text using the vectorizer | |
| text_vector = self.vectorizer.transform([text]) | |
| # Calculate cosine similarity with all training examples | |
| similarities = cosine_similarity(text_vector, self.tfidf_matrix)[0] | |
| # Find the index of the highest similarity | |
| best_match_index = similarities.argmax() | |
| best_match_score = similarities[best_match_index] | |
| # If similarity is too low, return unknown intent | |
| if best_match_score < 0.2: | |
| return "unknown" | |
| # Return the corresponding intent | |
| return self.training_intents[best_match_index] | |
| def load_knowledge_base(self): | |
| """Load knowledge base of concepts and definitions""" | |
| # This would typically load from a JSON or database | |
| # For demonstration, we'll define it inline | |
| self.knowledge_base = { | |
| "hydrostatic pressure": "Hydrostatic pressure is the pressure exerted by a fluid at rest due to the force of gravity. In drilling, it's calculated as 0.052 × mud weight (ppg) × true vertical depth (ft). It's one of the primary components of wellbore pressure and is essential for maintaining well control.", | |
| "ecd": "Equivalent Circulating Density (ECD) is the effective density exerted by a circulating fluid against the formation, taking into account the friction pressure in the annulus. It's calculated as: ECD = MW + (APL / (0.052 × TVD)), where MW is mud weight, APL is annular pressure loss, and TVD is true vertical depth. Managing ECD is critical to prevent formation damage, lost circulation, and well control issues.", | |
| "kick tolerance": "Kick tolerance is the maximum influx volume that a well can safely handle. It depends on factors like casing shoe depth, maximum allowable pressure at the shoe, mud weight, and formation pressure. It's a critical well control parameter used in drilling planning to ensure that a well can be safely controlled in case of a kick (formation fluid influx).", | |
| "ipr": "Inflow Performance Relationship (IPR) describes the relationship between bottomhole flowing pressure and production rate. It characterizes the reservoir's ability to deliver fluids to the wellbore. Common IPR models include the straight-line IPR for single-phase liquid flow and the Vogel correlation for solution gas drive reservoirs.", | |
| "tpr": "Tubing Performance Relationship (TPR) describes the pressure drop in the tubing for different flow rates. It characterizes the well's ability to deliver fluids to the surface. TPR curves are influenced by tubing size, wellhead pressure, fluid properties, and well depth. The intersection of IPR and TPR curves determines the well's operating point.", | |
| "darcy's law": "Darcy's Law describes fluid flow through porous media. It states that flow rate is proportional to pressure gradient and permeability, and inversely proportional to fluid viscosity. Mathematically, it's expressed as: q = (kA/μ)(dp/dl), where q is flow rate, k is permeability, A is cross-sectional area, μ is fluid viscosity, and dp/dl is pressure gradient.", | |
| "drilling hydraulics": "Drilling hydraulics refers to the behavior of drilling fluids while circulating through the wellbore system. It encompasses calculations of pressure losses, flow rates, velocities, and other parameters necessary for efficient drilling operations. Proper hydraulics management is essential for hole cleaning, bit cooling, and preventing formation damage.", | |
| "pipeline pressure drop": "Pipeline pressure drop refers to the loss of pressure that occurs as fluid flows through a pipeline due to friction. It's influenced by pipe diameter, length, roughness, fluid properties, and flow rate. Accurate prediction of pressure drop is essential for proper sizing of pipelines and pumping equipment.", | |
| "kick": "A kick is an unplanned, unwanted influx of formation fluids into the wellbore during drilling operations. It occurs when the pressure exerted by the drilling fluid column is less than the formation pressure. Kicks must be detected early and controlled properly to prevent blowouts.", | |
| "bop": "BOP (Blowout Preventer) is a large, specialized valve used to seal, control and monitor oil and gas wells. It's designed to prevent blowouts, catastrophic failures of pressure control systems that can lead to uncontrolled release of formation fluids.", | |
| "frac gradient": "Fracture gradient is the pressure required to induce fractures in rock at a given depth. It's typically expressed in psi/ft or ppg equivalent. Knowledge of the fracture gradient is crucial for setting casing depths, determining maximum allowable mud weights, and designing hydraulic fracturing operations." | |
| } | |
| def extract_parameters(self, text): | |
| """Extract parameters from user input using enhanced regex patterns""" | |
| params = {} | |
| text = text.lower() | |
| # Enhanced regex patterns for parameter extraction | |
| # Mud weight | |
| mud_weight_patterns = [ | |
| r'(?:mud weight|mud density|fluid density|mud).*?(\d+\.?\d*)\s*(ppg|kg/m3|sg)', | |
| r'(\d+\.?\d*)\s*(ppg|kg/m3|sg).*?(?:mud|density|weight)', | |
| r'weight\D*(\d+\.?\d*)\s*(ppg|kg/m3|sg)', | |
| r'density\D*(\d+\.?\d*)\s*(ppg|kg/m3|sg)' | |
| ] | |
| for pattern in mud_weight_patterns: | |
| mud_weight_match = re.search(pattern, text) | |
| if mud_weight_match: | |
| value = float(mud_weight_match.group(1)) | |
| unit = mud_weight_match.group(2) | |
| params["mud_weight"] = (value, unit) | |
| break | |
| # Depth | |
| depth_patterns = [ | |
| r'(?:depth|well depth).*?(\d+\.?\d*)[,\s]*(\d+)?\s*(ft|m)', | |
| r'depth\D*(\d+\.?\d*)[,\s]*(\d+)?\s*(ft|m)', | |
| r'(\d+\.?\d*)[,\s]*(\d+)?\s*(ft|m).*?depth', | |
| r'(\d+\.?\d*)[,\s]*(\d+)?\s*(ft|m)\D*deep' | |
| ] | |
| for pattern in depth_patterns: | |
| depth_match = re.search(pattern, text) | |
| if depth_match: | |
| value_str = depth_match.group(1) | |
| if depth_match.group(2): # Handle thousand separators or commas | |
| value_str += depth_match.group(2) | |
| value = float(value_str.replace(",", "")) | |
| unit = depth_match.group(3) | |
| params["depth"] = (value, unit) | |
| break | |
| # TVD | |
| tvd_patterns = [ | |
| r'(?:tvd|true vertical depth).*?(\d+\.?\d*)[,\s]*(\d+)?\s*(ft|m)', | |
| r'tvd\D*(\d+\.?\d*)[,\s]*(\d+)?\s*(ft|m)', | |
| r'(\d+\.?\d*)[,\s]*(\d+)?\s*(ft|m).*?tvd', | |
| r'vertical depth\D*(\d+\.?\d*)[,\s]*(\d+)?\s*(ft|m)' | |
| ] | |
| for pattern in tvd_patterns: | |
| tvd_match = re.search(pattern, text) | |
| if tvd_match: | |
| value_str = tvd_match.group(1) | |
| if tvd_match.group(2): # Handle thousand separators | |
| value_str += tvd_match.group(2) | |
| value = float(value_str.replace(",", "")) | |
| unit = tvd_match.group(3) | |
| params["tvd"] = (value, unit) | |
| break | |
| # Pressure values (annular pressure loss, formation pressure) | |
| pressure_patterns = [ | |
| r'(?:annular pressure loss|pressure loss|apl).*?(\d+\.?\d*)\s*(psi|bar|kpa|mpa)', | |
| r'pressure loss\D*(\d+\.?\d*)\s*(psi|bar|kpa|mpa)', | |
| r'apl\D*(\d+\.?\d*)\s*(psi|bar|kpa|mpa)', | |
| r'(?:formation pressure|pore pressure).*?(\d+\.?\d*)\s*(psi|bar|kpa|mpa)', | |
| r'formation\D*(\d+\.?\d*)\s*(psi|bar|kpa|mpa)' | |
| ] | |
| for pattern in pressure_patterns: | |
| pressure_match = re.search(pattern, text) | |
| if pressure_match: | |
| value = float(pressure_match.group(1)) | |
| unit = pressure_match.group(2) | |
| # Determine the parameter type based on context | |
| if re.search(r'(annular|apl)', pressure_match.group(0)): | |
| params["annular_pressure_loss"] = (value, unit) | |
| else: | |
| params["formation_pressure"] = (value, unit) | |
| # Flow Rate | |
| flow_patterns = [ | |
| r'(?:flow rate|flow|rate|pump).*?(\d+\.?\d*)\s*(gpm|bpm|l/s|m3/h)', | |
| r'flow\D*(\d+\.?\d*)\s*(gpm|bpm|l/s|m3/h)', | |
| r'rate\D*(\d+\.?\d*)\s*(gpm|bpm|l/s|m3/h)', | |
| r'pump\D*(\d+\.?\d*)\s*(gpm|bpm|l/s|m3/h)' | |
| ] | |
| for pattern in flow_patterns: | |
| flow_match = re.search(pattern, text) | |
| if flow_match: | |
| value = float(flow_match.group(1)) | |
| unit = flow_match.group(2) | |
| params["flow_rate"] = (value, unit) | |
| break | |
| # Additional parameters for specific calculations | |
| # Pipe diameter | |
| pipe_diameter_patterns = [ | |
| r'(?:pipe diameter|diameter|id|od).*?(\d+\.?\d*)\s*(in|mm|cm)', | |
| r'diameter\D*(\d+\.?\d*)\s*(in|mm|cm)', | |
| r'(\d+\.?\d*)\s*(in|mm|cm).*?diameter' | |
| ] | |
| for pattern in pipe_diameter_patterns: | |
| diameter_match = re.search(pattern, text) | |
| if diameter_match: | |
| value = float(diameter_match.group(1)) | |
| unit = diameter_match.group(2) | |
| # Convert to inches if needed | |
| if unit == "mm": | |
| value /= 25.4 | |
| elif unit == "cm": | |
| value /= 2.54 | |
| params["diameter"] = (value, "in") | |
| break | |
| # Permeability | |
| perm_match = re.search(r'(?:permeability|perm).*?(\d+\.?\d*)\s*(md|darcy)', text) | |
| if perm_match: | |
| value = float(perm_match.group(1)) | |
| unit = perm_match.group(2) | |
| # Convert to md if in darcy | |
| if unit == "darcy": | |
| value *= 1000 | |
| params["permeability"] = (value, "md") | |
| # Pipe length | |
| pipe_length_patterns = [ | |
| r'(?:pipe length|length).*?(\d+\.?\d*)[,\s]*(\d+)?\s*(ft|m|km)', | |
| r'length\D*(\d+\.?\d*)[,\s]*(\d+)?\s*(ft|m|km)' | |
| ] | |
| for pattern in pipe_length_patterns: | |
| length_match = re.search(pattern, text) | |
| if length_match: | |
| value_str = length_match.group(1) | |
| if length_match.group(2): # Handle thousand separators | |
| value_str += length_match.group(2) | |
| value = float(value_str.replace(",", "")) | |
| unit = length_match.group(3) | |
| if unit in self.length_units: | |
| # Convert to standard unit (ft) | |
| standard_value = value * self.length_units["ft"] / self.length_units[unit] | |
| params["pipe_length"] = (standard_value, "ft") | |
| break | |
| # Reservoir pressure | |
| res_pressure_match = re.search(r'(?:reservoir pressure|res pressure).*?(\d+\.?\d*)\s*(psi|bar|kpa|mpa)', text) | |
| if res_pressure_match: | |
| value = float(res_pressure_match.group(1)) | |
| unit = res_pressure_match.group(2) | |
| if unit in self.pressure_units: | |
| # Convert to standard unit (psi) | |
| standard_value = value * self.pressure_units["psi"] / self.pressure_units[unit] | |
| params["reservoir_pressure"] = (standard_value, "psi") | |
| # Productivity index | |
| pi_match = re.search(r'(?:productivity index|pi).*?(\d+\.?\d*)', text) | |
| if pi_match: | |
| value = float(pi_match.group(1)) | |
| params["productivity_index"] = (value, "STB/day/psi") | |
| # Convert all extracted parameters to standard units | |
| standard_params = {} | |
| for param, (value, unit) in params.items(): | |
| if param in ["mud_weight"] and unit in self.density_units: | |
| standard_value = value * self.density_units["ppg"] / self.density_units[unit] | |
| standard_params[param] = standard_value | |
| elif param in ["depth", "tvd"] and unit in self.length_units: | |
| standard_value = value * self.length_units["ft"] / self.length_units[unit] | |
| standard_params[param] = standard_value | |
| elif param in ["annular_pressure_loss", "formation_pressure"] and unit in self.pressure_units: | |
| standard_value = value * self.pressure_units["psi"] / self.pressure_units[unit] | |
| standard_params[param] = standard_value | |
| elif param in ["flow_rate"] and unit in self.flowrate_units: | |
| standard_value = value * self.flowrate_units["gpm"] / self.flowrate_units[unit] | |
| standard_params[param] = standard_value | |
| else: | |
| # Pass through parameters that don't need conversion | |
| standard_params[param] = value | |
| return standard_params | |
| def process_input(self, user_input: str) -> str: | |
| """Main function to process user input and generate response""" | |
| # Add input to conversation history | |
| self.conversation_history.append({"role": "user", "content": user_input}) | |
| # Identify intent using the classifier | |
| intent = self.classify_intent(user_input) | |
| # Extract parameters from the input | |
| params = self.extract_parameters(user_input) | |
| # Update context with new parameters | |
| self.context.update(params) | |
| # Process the intent | |
| if intent in self.intent_map: | |
| response = self.intent_map[intent]() | |
| else: | |
| response = "I'm not sure how to help with that. Try asking about hydrostatic pressure, ECD, kick tolerance, or type 'help' for more options." | |
| # Add response to conversation history | |
| self.conversation_history.append({"role": "assistant", "content": response}) | |
| return response | |
| def calculate_hydrostatic_pressure(self) -> str: | |
| """Calculate hydrostatic pressure""" | |
| # Check if we have the necessary parameters | |
| if "mud_weight" not in self.context: | |
| return "Please provide the mud weight to calculate hydrostatic pressure. For example: 'Calculate hydrostatic pressure with mud weight 12 ppg at depth 10,000 ft'" | |
| if "depth" not in self.context and "tvd" not in self.context: | |
| return "Please provide the depth or TVD to calculate hydrostatic pressure. For example: 'Calculate hydrostatic pressure with mud weight 12 ppg at depth 10,000 ft'" | |
| # Use TVD if available, otherwise use depth | |
| depth = self.context.get("tvd", self.context.get("depth")) | |
| mud_weight = self.context["mud_weight"] | |
| # Calculate hydrostatic pressure (P = ρgh) | |
| # For drilling fluids: P (psi) = 0.052 * mud_weight (ppg) * depth (ft) | |
| pressure = 0.052 * mud_weight * depth | |
| # Convert to different units | |
| pressure_bar = pressure / self.pressure_units["bar"] | |
| pressure_kpa = pressure / self.pressure_units["kpa"] | |
| result = f""" | |
| Hydrostatic Pressure Calculation: | |
| -------------------------------- | |
| Mud Weight: {mud_weight:.2f} ppg | |
| Depth: {depth:.2f} ft | |
| Formula: Pressure = 0.052 × Mud Weight × Depth | |
| Results: | |
| - {pressure:.2f} psi | |
| - {pressure_bar:.2f} bar | |
| - {pressure_kpa:.2f} kPa | |
| """ | |
| return result | |
| def calculate_ecd(self) -> str: | |
| """Calculate Equivalent Circulating Density""" | |
| # Check for required parameters | |
| if "mud_weight" not in self.context: | |
| return "Please provide the mud weight to calculate ECD. For example: 'Calculate ECD with mud weight 10.5 ppg, annular pressure loss 300 psi, and TVD 8,500 ft'" | |
| if "annular_pressure_loss" not in self.context: | |
| return "Please provide the annular pressure loss to calculate ECD. For example: 'Calculate ECD with mud weight 10.5 ppg, annular pressure loss 300 psi, and TVD 8,500 ft'" | |
| if "tvd" not in self.context: | |
| return "Please provide the true vertical depth (TVD) to calculate ECD. For example: 'Calculate ECD with mud weight 10.5 ppg, annular pressure loss 300 psi, and TVD 8,500 ft'" | |
| mud_weight = self.context["mud_weight"] | |
| annular_pressure_loss = self.context["annular_pressure_loss"] | |
| tvd = self.context["tvd"] | |
| # ECD = MW + (APL / (0.052 * TVD)) | |
| ecd = mud_weight + (annular_pressure_loss / (0.052 * tvd)) | |
| # Calculate the ECD increase | |
| ecd_increase = ecd - mud_weight | |
| result = f""" | |
| Equivalent Circulating Density (ECD) Calculation: | |
| ----------------------------------------------- | |
| Mud Weight: {mud_weight:.2f} ppg | |
| Annular Pressure Loss: {annular_pressure_loss:.2f} psi | |
| True Vertical Depth: {tvd:.2f} ft | |
| Formula: ECD = MW + (APL / (0.052 × TVD)) | |
| Results: | |
| - ECD: {ecd:.2f} ppg | |
| - ECD Increase: {ecd_increase:.2f} ppg | |
| Note: High ECD can lead to lost circulation if it exceeds the formation fracture gradient. | |
| """ | |
| return result | |
| def calculate_kick_tolerance(self) -> str: | |
| """Calculate kick tolerance""" | |
| # Check for required parameters | |
| if "mud_weight" not in self.context: | |
| return "Please provide the mud weight to calculate kick tolerance." | |
| if "depth" not in self.context and "tvd" not in self.context: | |
| return "Please provide the depth or TVD to calculate kick tolerance." | |
| if "formation_pressure" not in self.context: | |
| return "Please provide the formation pressure to calculate kick tolerance." | |
| # Use TVD if available, otherwise use depth | |
| depth = self.context.get("tvd", self.context.get("depth")) | |
| mud_weight = self.context["mud_weight"] | |
| formation_pressure = self.context["formation_pressure"] | |
| # Calculate formation pressure gradient | |
| formation_gradient = formation_pressure / depth | |
| # Calculate kick tolerance (simplified) | |
| # This is a very simplified kick tolerance calculation | |
| # Real kick tolerance would involve more parameters and complex calculations | |
| kick_margin = 0.5 # ppg safety margin | |
| max_allowable_mud_weight = mud_weight + kick_margin | |
| kick_tolerance_volume = (max_allowable_mud_weight - mud_weight) * depth / 100 | |
| result = f""" | |
| Kick Tolerance Calculation (Simplified): | |
| -------------------------------------- | |
| Mud Weight: {mud_weight:.2f} ppg | |
| Depth: {depth:.2f} ft | |
| Formation Pressure: {formation_pressure:.2f} psi | |
| Formation Gradient: {formation_gradient:.4f} psi/ft ({formation_gradient/0.052:.2f} ppg equivalent) | |
| Results: | |
| - Maximum Allowable Mud Weight: {max_allowable_mud_weight:.2f} ppg | |
| - Estimated Kick Tolerance: {kick_tolerance_volume:.2f} bbls | |
| Note: This is a simplified estimation. Actual kick tolerance calculation involves more parameters including casing shoe depth, fracture gradient, and influx type. | |
| """ | |
| return result | |
| def calculate_drilling_hydraulics(self) -> str: | |
| """Calculate drilling hydraulics""" | |
| # Check for required parameters | |
| if "flow_rate" not in self.context: | |
| return "Please provide the flow rate to calculate drilling hydraulics." | |
| if "mud_weight" not in self.context: | |
| return "Please provide the mud weight to calculate drilling hydraulics." | |
| if "diameter" not in self.context: | |
| return "Please provide the pipe diameter to calculate drilling hydraulics." | |
| flow_rate = self.context["flow_rate"] | |
| mud_weight = self.context["mud_weight"] | |
| diameter = self.context["diameter"] | |
| # Calculate annular velocity (simplified) | |
| # Assuming a hole diameter and drill pipe diameter | |
| hole_diameter = diameter * 2 # simplified assumption | |
| annular_area = 3.14159 * (hole_diameter**2 - diameter**2) / 4 # square inches | |
| # Convert flow rate from gpm to cubic inches per minute | |
| flow_rate_cim = flow_rate * 231 # 1 gallon = 231 cubic inches | |
| # Calculate velocity in feet per minute | |
| velocity_fpm = flow_rate_cim / annular_area / 12 | |
| velocity_fps = velocity_fpm / 60 | |
| result = f""" | |
| Drilling Hydraulics Calculation (Simplified): | |
| ------------------------------------------- | |
| Flow Rate: {flow_rate:.2f} gpm | |
| Mud Weight: {mud_weight:.2f} ppg | |
| Pipe Diameter: {diameter:.2f} in | |
| Estimated Hole Diameter: {hole_diameter:.2f} in (simplified assumption) | |
| Results: | |
| - Annular Area: {annular_area:.2f} sq in | |
| - Annular Velocity: {velocity_fpm:.2f} ft/min ({velocity_fps:.2f} ft/sec) | |
| Note: This is a simplified calculation. Complete drilling hydraulics would include pressure losses through the drill string, bit nozzles, and annulus. | |
| """ | |
| return result | |
| def calculate_ipr(self) -> str: | |
| """Calculate Inflow Performance Relationship""" | |
| # Simplified Vogel IPR calculation | |
| reservoir_pressure = self.context.get("reservoir_pressure", 3000) # psi | |
| pi = self.context.get("productivity_index", 1.0) # STB/day/psi | |
| # Maximum flow rate (AOFP) | |
| max_flow_rate = pi * reservoir_pressure / 1.8 | |
| result = f""" | |
| Inflow Performance Relationship (Vogel Method): | |
| -------------------------------------------- | |
| Reservoir Pressure: {reservoir_pressure:.2f} psi | |
| Productivity Index (PI): {pi:.2f} STB/day/psi | |
| Results: | |
| - Maximum Flow Rate (AOFP): {max_flow_rate:.2f} STB/day | |
| - IPR Type: Vogel (Solution Gas Drive) | |
| Sample points on IPR curve: | |
| - At Pwf = {0.8*reservoir_pressure:.0f} psi, Rate = {0.63*max_flow_rate:.0f} STB/day | |
| - At Pwf = {0.5*reservoir_pressure:.0f} psi, Rate = {0.83*max_flow_rate:.0f} STB/day | |
| - At Pwf = {0.2*reservoir_pressure:.0f} psi, Rate = {0.97*max_flow_rate:.0f} STB/day | |
| """ | |
| return result | |
| def calculate_tpr(self) -> str: | |
| """Calculate Tubing Performance Relationship""" | |
| # Get parameters or use defaults | |
| tubing_id = self.context.get("diameter", 2.441) # inches | |
| depth = self.context.get("depth", 8000) # ft | |
| flow_rate = self.context.get("flow_rate", 1000) # STB/day | |
| # Simple TPR |