Comprehensive Notes on Search Algorithms, Fuzzy Logic, and Logic Programming
Best-First Search & Graph Search
Best-First Search is an informed search technique that combines the advantages of both Depth-First Search (DFS) and Breadth-First Search (BFS).
- Depth-First Search (DFS) Advantage: Allows a solution to be found without having to expand all competing branches.
- Breadth-First Search (BFS) Advantage: Prevents the algorithm from getting trapped on dead-end paths.
- Best-First Search Strategy: Follows a single path at a time, but switches paths whenever a competing path appears more promising.
Comparison: Best-First Search vs. Steepest-Ascent Hill Climbing:
- In hill climbing, one move is selected and all alternative moves are immediately rejected, never to be reconsidered. In best-first search, alternative moves remain stored in memory so they can be revisited later if required.
- If a successor state has a worse (lower/higher depending on goal) evaluation value than the current state, hill climbing halts immediately. Best-first search selects the best available state from all generated nodes, even if it is worse than the current state.

Graph Search Representation:
- Designed to avoid node duplication.
- Operates on a directed graph known as an 'OR' graph, where each branch represents an alternative problem-solving path.
- Information Stored in Each Node Structure:
- Description of the problem state it represents.
- Desirability (how promising the state is based on evaluation).
- A parent link to recover the solution path.
- A list of successors to propagate cost improvements downward.
Node Data Structures in Graph Search:
- OPEN List: Contains nodes that have been generated and evaluated by the heuristic function but have not yet been examined (generated but not expanded). Maintained as a priority queue where higher priority corresponds to a more promising heuristic value.
- CLOSED List: Contains nodes that have already been examined and expanded. Kept in memory to prevent expanding duplicate nodes.
Evaluation Heuristic Function:
- Evaluates nodes using the combined function:
- : Actual cost measure of getting from the initial state to the current node.
- : Estimated additional cost of getting from the current node to a goal state.
- : Estimated total cost of getting from the initial state to a goal state through the current node.
Best-First Search Algorithm Procedure:
- Start with
OPENcontaining only the initial state. - Until a goal is found or
OPENis empty, repeat: a. Pick the best node onOPEN(lowest value). b. Generate its successors. c. For each successor: i. If it has not been generated before, evaluate it using , add it toOPEN, and record its parent. ii. If it has been generated before, change its parent link if this new path is better than the previous path. Update the cost to this node and propagate the cost change to any existing successors.
- Start with
Greedy Nature of Pure Best-First Search:
- Selects the vertex closest to the goal without considering the distance already traveled from the starting point.
- Considers only (ignores ).
- Highly greedy in nature.
Example 1: Best-First Search Walkthrough:
- State Heuristics ():
- Actual Step-by-Step State Transitions:
- Step 1:
OPEN= ,CLOSED= - Step 2: Expand (successors , ).
OPEN= ,CLOSED= - Step 3: Expand (successors , ).
OPEN= ,CLOSED= - Step 4: Expand (successor ).
OPEN= ,CLOSED= - Step 5: Expand Goal .
CLOSED= - Resulting Path: with actual cost .
- Note: The optimal actual path is using cost , demonstrating that pure Best-First Search does not guarantee an optimal path.
Example 2: Route Finding on Romania Map:
- Start State: (Arad), Goal State: (Bucharest).
- Straight-Line Distance Heuristic ( to Bucharest):
- Best-First Search Result: Selects path (Arad Sibiu Fagaras Bucharest) with path cost
- Optimal Path: (Arad Sibiu Rimnicu Vilcea Pitesti Bucharest) with path cost
A* Search Algorithm
Algorithm Foundations:
- Dijkstra's Algorithm: Guarantees finding the shortest path from a starting vertex using edge relaxation for positive weighted edges: Selects the vertex closest to the starting point (based purely on accumulated path cost ). It is non-heuristic and relatively slow.
- A* Search Algorithm: Combines the heuristic-driven approach of Greedy Best-First Search with the formal optimal path guarantee of Dijkstra's algorithm.
- Uses total evaluation function: where is the exact path cost from start to current node, and is an admissible heuristic estimate of the cost from current node to goal.
Detailed A* Algorithm Steps:
- Start with
OPENcontaining only initial node . Set , . - Set
CLOSEDlist = Empty. - Repeat until goal is found or
OPENis empty: a. IfOPENis empty, exit with failure. b. PickbestnodefromOPEN(node with lowest value). RemovebestnodefromOPENand place it inCLOSED. c. Check ifbestnodeis the goal. If so, exit and construct path. d. Otherwise, generate successors ofbestnode. e. For each successor: i. Compute . ii. If successor is inOPEN: Check if the new path to successor is cheaper than the old path. If so, update successor's parent link to point tobestnode, and update its stored and values. iii. If successor is inCLOSED: Check if the new path is cheaper than the old path. If so, update successor's parent link and propagate the improved cost downward through all its existing descendants using a Depth-First Search traversal. iv. If successor is neither onOPENnorCLOSED: Add successor toOPEN, set parent link tobestnode, and calculate its and values.
- Start with
A* Step-by-Step Worked Example 1:
- Graph with nodes . Edges: , , . Goal node: .
- Heuristics: .
- Execution:
- Start at : .
OPEN= ,CLOSED= - Expand : Successors and .
- Node : .
- Node : .
OPEN= ,CLOSED= .
- Select
bestnode= (). - Expand : Successor .
- Node is already in
OPENwith old cost . - New cost via : g(C) = g(B) + \text{cost}(B, C) = 2 + 1 = 3$.\n - Since 3 < 4CBg(C) = 3f(C) = 3 + 3 = 6$.
- Node is already in
- Select
bestnode= (). is the goal state. Solution path found: with actual cost g = 3$.\n\n- **A* Step-by-Step Worked Example 2:**\n - Nodes: S, A, B, C, D, GSG\n - **Heuristics h(n)S=5, A=3, B=4, C=2, D=6, G=0\n - **Edge Costs gS \to A = 1, S \to G = 10, A \to B = 2, A \to C = 1, C \to D = 3, B \to D = 5, D \to G = 2\n - **Trace:**\n - Start Sg(S)=0, f(S)=5$.OPEN= ,CLOSED= - Expand :
- :
- :
OPEN= ,CLOSED=
- Select (). Expand :
- :
- :
OPEN= [C(4), B(7), G(10)]$, `CLOSED` = [S, A]\n - Select Cf=4C:\n - Dg(D) = 2+3 = 5, f(D) = 5+6 = 11\n - Check path to GCC \to Gg(G) = 2+4 = 6, f(G) = 6+0 = 6.\n - Re-evaluating `OPEN`: G(6)6 < 7 < 11).\n - Select Gf=6). Goal reached.\n\n\n# Fuzzy Logic Foundations & Operations\n\n- **Introduction to Fuzzy Logic:**\n - Introduced as a formal mathematical method to represent uncertainty associated with vagueness, imprecision, and lack of complete information.\n - Unlike Boolean logic, which forces sharp binary distinctions (0101.\n - **Real-world Applications:** Pattern recognition, data mining, information retrieval, automata theory, game theory, automatic train control, tunnel digging machinery, household appliances (washing machines, air conditioners).\n\n- **Crisp Sets vs. Fuzzy Sets:**\n - **Universe of Discourse (X):** The range of all possible values applicable to a selected variable (represented on the x-axis).\n - **Crisp Set:** Defined by a characteristic function f_A(x)X{0, 1}:\n f_A(x) = \begin{cases} 1 & \text{if } x \in A \ 0 & \text{if } x otin A \end{cases}\n - **Fuzzy Set:** Defined by a membership function \mu_A(x)X[0, 1]:\n \mu_A(x) = \begin{cases} 1 & \text{if } x \text{ is totally in } A \ 0 & \text{if } x \text{ is not in } A \ 0 < \mu_A(x) < 1 & \text{if } x \text{ is partly in } A \end{cases}\n - A Fuzzy set AX is represented as ordered pairs:\n A = { (x, \mu_A(x)) \mid x \in X }\n\n\n\n- **Concrete Numerical Example (Height Classification):**\n - For a man 184\,\text{cm} tall:\n - Crisp Set classification (180\,\text{cm}1.00.0).\n - Fuzzy Set classification: Belongs to set *average men* with membership grade \mu = 0.1\mu = 0.4\n\n- **Linguistic Variables and Hedges:**\n - **Linguistic Variable:** A fuzzy variable whose values are words/sentences in a natural language (e.g., statement "John is tall" means linguistic variable *John* takes linguistic value *tall*).\n - **Hedges:** Terms that modify the shape and degree of fuzzy sets (adverbs such as *very*, *somewhat*, *quite*, *more or less*, *slightly*).\n\n- **Core Operations on Fuzzy Sets:**\n - **Complement (NOT):** Opposite of a set. Measures degree of non-membership:\n \mu_{ eg A}(x) = 1 - \mu_A(x)\n - **Containment (Subset):** Fuzzy set ABA \subseteq B) if and only if:\n \mu_A(x) \le \mu_B(x) \quad \forall x \in X\n - **Intersection (AND):** Logical conjunction. Degree of membership is the minimum of both sets:\n \mu_{A \cap B}(x) = \min [\mu_A(x), \mu_B(x)]\n - **Union (OR):** Logical disjunction. Degree of membership is the maximum of both sets:\n \mu_{A \cup B}(x) = \max [\mu_A(x), \mu_B(x)]\n\n- **Formal Properties & Definitions:**\n - **Equality:** A = B \iff \mu_A(x) = \mu_B(x) \quad \forall x \in X\n - **Cardinality (Sigma Count):** Sum of membership function values across universe X:\n \text{card}(A) = \sum_{x \in X} \mu_A(x)\n - **Empty Set:** Fuzzy set A\mu_A(x) = 0 \quad \forall x \in X\n - **Alpha-Cut (\alphaA_\alpha\alpha:\n A_\alpha = { x \in X \mid \mu_A(x) \ge \alpha }\n - **Normality:** Fuzzy set A\exists x \in X\mu_A(x) = 1. Otherwise, it is subnormal.\n - **Height:** The largest membership grade of any element in A:\n \text{height}(A) = \max_x [\mu_A(x)]\n - **Support:** Crisp subset of X\mu_A(x) > 0\n - **Core:** Crisp subset of X\mu_A(x) = 1\n\n- **Complete Worked Example (Fuzzy Set Operations):**\n - Universe X = {a, b, c, d, e}\n - Set A = {1/a, 0.3/b, 0.2/c, 0.8/d, 0/e}\n - Set B = {0.6/a, 0.9/b, 0.1/c, 0.3/d, 0.2/e}\n - **Calculations:**\n - Support: \text{supp}(B) = {a, b, c, d, e}\n - Cardinality: \text{card}(A) = 1 + 0.3 + 0.2 + 0.8 + 0 = 2.3\n - Cardinality: \text{card}(B) = 0.6 + 0.9 + 0.1 + 0.3 + 0.2 = 2.1\n - Complement: eg A = {0/a, 0.7/b, 0.8/c, 0.2/d, 1/e}\n - Union (A \cup B{1/a, 0.9/b, 0.2/c, 0.8/d, 0.2/e}\n - Intersection (A \cap B{0.6/a, 0.3/b, 0.1/c, 0.3/d, 0/e}\n - Alpha-Cuts of A:\n - A_{0.2} = {a, b, c, d}\n - A_{0.3} = {a, b, d}\n - A_{0.8} = {a, d}\n - A_{1.0} = {a}\n\n\n# Mamdani Fuzzy Inference Process & Risk Assessment Example\n\n- **Mamdani Fuzzy Inference Architecture:**\n - Formulated by Lotfi Zadeh (1973) and Ebrahim Mamdani.\n - **Four Sequential Steps:**\n 1. **Fuzzification of Input Variables:** Take crisp numerical inputs and determine their degree of membership in corresponding fuzzy sets.\n 2. **Rule Evaluation (Inference):** Apply fuzzified inputs to rule antecedents using fuzzy operators (AND / OR) and evaluate rule consequents.\n 3. **Aggregation of Rule Outputs:** Combine clipped or scaled fuzzy output sets from all rules into a single aggregate fuzzy set.\n 4. **Defuzzification:** Convert the aggregated fuzzy output set into a single crisp numerical value.\n\n- **Rule Evaluation Methods (Clipping vs. Scaling):**\n - **Clipping (Alpha-cut):** Cuts off the top of the consequent membership function at the truth level of the antecedent. Slices top off membership shape (loses some shape information), but involves simpler/faster mathematics.\n - **Scaling:** Multiplies all membership degrees of the consequent function by the truth grade of the antecedent. Scales shape down proportionally, preserving original set geometry and retaining more information.\n\n- **Defuzzification Technique - Center of Gravity (COG) / Centroid:**\n - Calculates point where a vertical line slices the aggregated fuzzy set area into two equal masses.\n - Continuous Formula:\n \text{COG} = \frac{\int_a^b \mu_A(x) x \, dx}{\int_a^b \mu_A(x) \, dx}\n - Discrete Point Approximation:\n \text{COG} = \frac{\sum_{i} x_i \cdot \mu_A(x_i)}{\sum_{i} \mu_A(x_i)}\n\n- **Comprehensive Worked Example: Software Engineering Project Risk Assessment:**\n - **System Definitions:**\n - **Inputs:** Project Funding (35\%60\%).\n - **Funding Sets:** Inadequate, Marginal, Adequate.\n - **Staffing Sets:** Small, Large.\n - **Output (Risk Sets):** Low, Normal, High.\n - **Rule Base:**\n - Rule 1: `IF Project Funding IS Adequate OR Project Staffing IS Small THEN Risk IS Low`\n - Rule 2: `IF Project Funding IS Marginal AND Project Staffing IS Large THEN Risk IS Normal`\n - Rule 3: `IF Project Funding IS Inadequate THEN Risk IS High`\n\n - **Step 1: Input Fuzzification:**\n - **Input 1: Project Funding = 35%**\n - *Inadequate Membership Calculation:* Slope between points (20, 1)(40, 0):\n m = \frac{0 - 1}{40 - 20} = -\frac{1}{20}\n y - 0 = -\frac{1}{20}(35 - 40) \implies y = \frac{5}{20} = 0.25\n \mu_{\text{Inadequate}}(35) = 0.25\n - *Marginal Membership Calculation:* Slope between points (30, 0)(60, 1):\n m = \frac{1 - 0}{60 - 30} = \frac{1}{30}\n y - 0 = \frac{1}{30}(35 - 30) \implies y = \frac{5}{30} = 0.166 \approx 0.16\n \mu_{\text{Marginal}}(35) = 0.16\n - *Adequate Membership Calculation:* \mu_{\text{Adequate}}(35) = 0.0\n - **Input 2: Project Staffing = 60%**\n - *Small Membership Calculation:* Slope between (30, 1)(60, 0):\n \mu_{\text{Small}}(60) = 0.0\n - *Large Membership Calculation:* Slope between (50, 0)(70, 1):\n m = \frac{1 - 0}{70 - 50} = \frac{1}{20}\n y - 0 = \frac{1}{20}(60 - 50) \implies y = \frac{10}{20} = 0.5\n \mu_{\text{Large}}(60) = 0.5\n\n - **Step 2: Rule Evaluation:**\n - **Rule 1 Evaluation:** \max(\mu_{\text{Adequate}}(35), \mu_{\text{Small}}(60)) = \max(0.0, 0.0) = 0.0 \implies \text{Risk Low} = 0.0\n - **Rule 2 Evaluation:** \min(\mu_{\text{Marginal}}(35), \mu_{\text{Large}}(60)) = \min(0.16, 0.5) = 0.16 \implies \text{Risk Normal} = 0.16\n - **Rule 3 Evaluation:** \mu_{\text{Inadequate}}(35) = 0.25 \implies \text{Risk High} = 0.25\n\n - **Step 3 & 4: Aggregation and Defuzzification via COG:**\n - Combined aggregated set profile across sample points:\n - Points 0\dots 10\mu = 0.0\n - Points 20\dots 50\mu = 0.16\n - Points 60\dots 100\mu = 0.25\n - Discrete COG Formula Substitution:\n \text{COG} = \frac{(0 + 10)\times 0 + (20 + 30 + 40 + 50)\times 0.16 + (60 + 70 + 80 + 90 + 100)\times 0.25}{0 + 0 + 4(0.16) + 5(0.25)}\n \text{COG} = \frac{0 + 140 \times 0.16 + 400 \times 0.25}{0.64 + 1.25}\n \text{COG} = \frac{22.4 + 100}{1.89} = \frac{122.4}{1.89} = 64.76\n - Final Crisp Output Value: **64.76**\n\n\n# Simulated Annealing Algorithm\n\n- **Drawbacks of Traditional Hill Climbing:**\n - Trapped easily at local optima (local maxima/minima), ridges, and plateaus.\n - Greedy optimization approach only accepts moves that immediately improve the objective function.\n - Outcome is heavily dependent on the chosen initial starting point.\n\n- **Concept of Simulated Annealing:**\n - Stochastic/evolutionary global optimization algorithm designed to locate the global optimum in a multi-dimensional search space with multiple hills and valleys.\n - Takes the risk of occasionally accepting moves to worse (lower height/higher cost) points to escape local sub-optima.\n - Willingness to accept bad moves starts high and gradually decreases over time (as temperature drops), eventually terminating as a pure local search.\n\n- **Physical vs. Simulated Annealing Analogy:**\n - Modeled after the physical annealing process of solids (cooling molten metals to form low-energy crystalline lattices).\n - **Thermodynamics \leftrightarrow Combinatorial Optimization Mapping:**\n - System States \leftrightarrow Feasible Solutions\n - Energy Level (E\leftrightarrow Cost / Objective Function Value\n - Change of Physical State \leftrightarrow Transition to Neighboring Solution\n - Temperature (T\leftrightarrowT)\n - Frozen Crystalline State \leftrightarrow Final Heuristic Solution\n\n- **Transition Probability Equation:**\n - In physical thermodynamics, probability of transition to higher energy state follows Boltzmann distribution:\n P = e^{-\frac{\Delta E}{k T}}\n where \Delta ETk is Boltzmann's constant.\n - In artificial optimization, kT:\n P' = e^{-\frac{\Delta E}{T}}\n - **Acceptance Rule:**\n - Downhill/improving moves are accepted **always** (P = 1.0).\n - Uphill/worse moves are accepted with probability P' = e^{-\frac{\Delta E}{T}}.\n\n- **Acceptance Probability vs. Temperature Table (\Delta E = 1):**\n - T = 10,000 \implies P = 99.99990\%\n - T = 1,000 \implies P = 99.9905\%\n - T = 100 \implies P = 99.99000\%\n - T = 10 \implies P = 90.04\%\n - T = 5 \implies P = 81.87\%\n - T = 3 \implies P = 71.89\%\n - T = 2 \implies P = 60.65\%\n - T = 1 \implies P = 36.78\%\n\n- **Annealing Schedule Requirements:**\n 1. Initial starting value of Temperature T.\n 2. Temperature reduction rate/rule (e.g., T_{\text{new}} = \alpha T_{\text{old}}).\n 3. Number of iterations at each temperature step.\n 4. Termination condition / final minimum temperature threshold.\n\n- **Worked Table Example: Acceptance Probabilities for Maximization Problem:**\n - Current State Evaluation = 120\n - Row 1: New State = 50T = 20 \implies \Delta E = 50 - 120 = -70 \implies P = e^{-\frac{70}{20}} = 0.030197\n - Row 2: New State = 50T = 500 \implies \Delta E = -70 \implies P = e^{-\frac{70}{500}} = 0.869358\n - Row 3: New State = 100T = 20 \implies \Delta E = 100 - 120 = -20 \implies P = e^{-\frac{20}{20}} = e^{-1} = 0.367879\n - Row 4: New State = 100T = 500 \implies \Delta E = -20 \implies P = e^{-\frac{20}{500}} = 0.960789\n - Row 5: New State = 150T = 20 \implies \Delta E = +30P > 1.0 \implies \text{Always Accepted}).\n - Row 6: New State = 150T = 500 \implies \Delta E = +30P > 1.0 \implies \text{Always Accepted}).\n\n- **Worked Example 2: Continuous Function Maximization:**\n - Objective function to maximize:\n f(x) = x^3 - 60x^2 + 900x + 100\n - Solution x represented as 5-bit string. Neighborhood generated by flipping 1 bit randomly.\n - Global maximum at string `01010` (x = 10, f(x) = 4100).\n - Initial Solution string `10011` (x = 19, f(19) = 2399).\n - **Scenario A (T = 500f = 3556, \Delta f = 247, P = 0.54f = 4100).\n - **Scenario B (T = 100f = 3236).\n\n\n# Knowledge Representation & Logic Systems\n\n- **Taxonomy of Logic Systems:**\n - **Propositional Logic:** Operates on atomic propositional variables (e.g., RAINING, SUNNY).\n - **First-Order Predicate Logic (FOL / Predicate Calculus):** Expresses predicates, functions, objects, and quantifiers (\forall, \exists).\n - **Second-Order Predicate Logic:** Allows quantification over predicates themselves.\n - **Modal Logic:** Handles concepts of necessity, possibility, beliefs, and temporal states.\n\n- **Monotonic vs. Non-Monotonic Logic:**\n - **Monotonic Logic Systems:** Include Propositional, First-Order, and Second-Order logic. Knowledge Base (KB) size strictly increases monotonicly as new inferences are made. Facts can never be deleted.\n - **Non-Monotonic Logic Systems:** Include Modal Logic and Default Reasoning systems. Asserted facts can be retracted/deleted if newly acquired data contradicts prior assumptions made in the absence of complete information.\n\n- **Three Kinds of Logical Reasoning:**\n 1. **Deduction:** Derives sound, guaranteed conclusions from true premises (e.g., \forall x : man(x) \to mortal(x)man(John) \implies mortal(John)). Standard style used by mathematicians.\n 2. **Induction:** Generalizes abstract rules from finite sets of observed instances (Machine Learning). Standard style used by empirical scientists.\n 3. **Abduction:** Plausible plausible reasoning from effect to cause (B \to AAB). Used by medical diagnosticians and detectives.\n\n- **First-Order Logic Representation Example (Marcus Knowledge Base):**\n 1. Marcus was a man: \text{man}(\text{Marcus})\n 2. Marcus was a Pompeian: \text{pompeian}(\text{Marcus})\n 3. All Pompeians were Romans: \forall x: \text{pompeian}(x) \to \text{roman}(x)\n 4. Caesar was a ruler: \text{ruler}(\text{Caesar})\n 5. All Romans were either loyal to Caesar or hated him: \forall x: \text{roman}(x) \to \text{loyalto}(x, \text{Caesar}) \lor \text{hate}(x, \text{Caesar})\n 6. Everyone is loyal to someone: \forall x: \exists y: \text{loyalto}(x, y)\n 7. People only try to assassinate rulers they are not loyal to: \forall x: \forall y: \text{person}(x) \land \text{ruler}(y) \land \text{tryassassinate}(x, y) \to eg \text{loyalto}(x, y)\n 8. Marcus tried to assassinate Caesar: \text{tryassassinate}(\text{Marcus}, \text{Caesar})\n 9. All men are persons: \forall x: \text{man}(x) \to \text{person}(x)\n - **Goal Proof:** Proving eg \text{loyalto}(\text{Marcus}, \text{Caesar}) by unifying statements 7, 8, 4, and 9.\n\n\n# Prolog Programming & Control Mechanisms\n\n- **Prolog Implementation Patterns:**\n - **Finding nth Element of a List:**\n ```prolog\n nth_element([Head|_], 1) :- write(Head), nl.\n nth_element([_|Tail], N) :- N > 1, NN is N - 1, nth_element(Tail, NN).\n ```\n - **Finding Maximum Element of a List:**\n ```prolog\n max([], Max, Max).\n max([Head|Tail], Max, R) :- Head > Max, max(Tail, Head, R).\n max([Head|Tail], Max, R) :- Head