File size: 8,344 Bytes
23c3f1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
"""
Knowledge Base and Math Solver Components
"""

import re
import sympy as sp
from sympy import symbols, Eq, solve

class KnowledgeBase:
    def __init__(self):
        self.knowledge = {
            "Biology": {
                "photosynthesis": {
                    "definition": "Photosynthesis is the process by which plants, algae, and some bacteria convert light energy into chemical energy stored in glucose molecules.",
                    "equation": "6CO₂ + 6H₂O + light energy → C₆H₁₂O₆ + 6O₂",
                    "key_concepts": ["Light-dependent reactions", "Calvin cycle", "Chlorophyll absorption", "Glucose production"],
                    "applications": "Essential for life on Earth as it produces oxygen and forms the base of food chains.",
                    "detailed_explanation": "Photosynthesis occurs in two main stages: light reactions and Calvin cycle."
                },
                "genetics": {
                    "definition": "Genetics is the study of heredity and variation in living organisms through genes and DNA.",
                    "key_concepts": ["DNA", "Genes", "Chromosomes", "Inheritance", "Mutations"],
                    "applications": "Critical for medicine, agriculture, and evolutionary biology.",
                    "detailed_explanation": "Genetics explains how traits are passed from parents to offspring through DNA."
                }
            },
            "Mathematics": {
                "algebra": {
                    "definition": "Algebra uses symbols to represent unknown numbers in equations and expressions.",
                    "key_concepts": ["Variables", "Equations", "Functions", "Linear equations", "Quadratic equations"],
                    "applications": "Used in engineering, finance, science, and everyday problem-solving.",
                    "detailed_explanation": "Algebra starts with simple equations and progresses to complex systems.",
                    "examples": ["2x + 5 = 15 → x = 5", "x² - 5x + 6 = 0 → x = 2 or x = 3"]
                },
                "calculus": {
                    "definition": "Calculus is the study of continuous change, involving derivatives and integrals.",
                    "key_concepts": ["Limits", "Derivatives", "Integrals", "Chain Rule", "Optimization"],
                    "applications": "Essential for physics, engineering, economics, and rates of change.",
                    "detailed_explanation": "Calculus has differential and integral branches for studying change and accumulation."
                }
            },
            "Physics": {
                "mechanics": {
                    "definition": "Mechanics deals with motion and forces acting on bodies.",
                    "key_concepts": ["Force", "Motion", "Energy", "Momentum", "Newton's Laws"],
                    "applications": "Foundation for engineering, robotics, and understanding motion.",
                    "detailed_explanation": "Mechanics studies how objects move based on Newton's three laws."
                }
            },
            "Chemistry": {
                "organic_chemistry": {
                    "definition": "Organic chemistry studies carbon-containing compounds and their reactions.",
                    "key_concepts": ["Hydrocarbons", "Functional Groups", "Reactions", "Stereochemistry"],
                    "applications": "Essential for pharmaceuticals, plastics, and biochemistry.",
                    "detailed_explanation": "Organic chemistry focuses on carbon compounds forming life's basis."
                }
            }
        }

    def find_topic_match(self, query: str, subject: str) -> str:
        """Find the best matching topic for a query"""
        query_lower = query.lower()
        subject_data = self.knowledge.get(subject, {})

        for topic in subject_data.keys():
            if topic in query_lower:
                return topic

        keyword_mapping = {
            "photosynthesis": ["photosynthesis", "plant", "chlorophyll", "light"],
            "genetics": ["genetics", "dna", "gene", "heredity", "inheritance"],
            "algebra": ["algebra", "equation", "variable", "solve", "x", "linear"],
            "calculus": ["calculus", "derivative", "integral", "limit"],
            "mechanics": ["mechanics", "force", "motion", "newton", "velocity"],
            "organic_chemistry": ["organic", "carbon", "hydrocarbon"]
        }

        for topic, keywords in keyword_mapping.items():
            if any(keyword in query_lower for keyword in keywords):
                if topic in subject_data:
                    return topic
        return None

    def get_accurate_info(self, query: str, subject: str) -> dict:
        """Get accurate information about a topic"""
        topic = self.find_topic_match(query, subject)
        
        if topic and subject in self.knowledge and topic in self.knowledge[subject]:
            return self.knowledge[subject][topic]
        
        return {
            "definition": f"This is an important concept in {subject} requiring systematic study.",
            "key_concepts": ["Fundamental principles", "Core theories", "Practical applications"],
            "applications": f"This concept has various real-world applications in {subject}.",
            "detailed_explanation": f"Understanding this concept requires studying underlying principles in {subject}."
        }

class MathSolver:
    def __init__(self):
        self.x, self.y, self.z = symbols('x y z')

    def is_algebraic_equation(self, problem: str) -> bool:
        """Check if the problem is an algebraic equation"""
        patterns = [
            r'\d*[a-z]\s*[\+\-\*\/]\s*\d+\s*=\s*\d+',
            r'solve.*for.*[a-z]',
            r'find.*[a-z]',
            r'[a-z]\s*='
        ]
        return any(re.search(pattern, problem.lower()) for pattern in patterns)

    def solve_algebraic_equation(self, problem: str) -> str:
        """Solve algebraic equations step by step"""
        try:
            problem_clean = problem.lower().replace('find', '').replace('solve for', '').replace('solve', '').strip()
            
            if '=' in problem_clean:
                left_side, right_side = problem_clean.split('=')
                left_side, right_side = left_side.strip(), right_side.strip()
                
                left_expr = sp.sympify(left_side)
                right_expr = sp.sympify(right_side)
                equation = Eq(left_expr, right_expr)
                solution = solve(equation, self.x)
                
                solution_text = f"**🔢 Algebraic Equation Solution**\n\n"
                solution_text += f"**Problem:** {problem}\n\n"
                solution_text += f"**Equation:** {left_side} = {right_side}\n\n"
                solution_text += f"**Answer:** x = {solution[0]}\n\n"
                
                verification = left_expr.subs(self.x, solution[0])
                solution_text += f"**Verification:** {verification} = {right_expr} ✓\n\n"
                solution_text += "**Key Principles:** Isolation, inverse operations, balance, verification"
                
                return solution_text
        except Exception as e:
            return self.handle_algebraic_error(problem, str(e))

    def handle_algebraic_error(self, problem: str, error: str) -> str:
        """Handle errors in algebraic equation solving"""
        return f"""**🔢 Algebraic Equation Analysis**

**Problem:** {problem}

**Solution Approach:**
For Linear Equations (like ax + b = c):
1. Identify the equation and variable
2. Isolate the variable term
3. Solve for the variable
4. Check your answer

**Example:** 2x + 5 = 15 → x = 5
"""

    def solve_arithmetic_expression(self, problem: str) -> str:
        """Solve arithmetic expressions"""
        try:
            problem_clean = re.sub(r'[^\d+\-*/().\s]', '', problem)
            if problem_clean.strip():
                result = eval(problem_clean)
                return f"**🧮 Arithmetic Solution**\n\n**Problem:** {problem}\n**Answer:** {result}\n\n**Key:** Follow PEMDAS/BODMAS order of operations"
        except:
            return f"**🧮 Arithmetic Analysis**\n\n**Problem:** {problem}\n\n**Approach:** Break into steps, follow order of operations, verify answer"