npsai 1.0.0__tar.gz

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.
@@ -0,0 +1,77 @@
1
+ """AI assignment study reference. Usage: import Num as NPS; NPS.show()."""
2
+ from importlib.resources import files
3
+ from pathlib import Path
4
+ import json
5
+ import runpy
6
+
7
+ __version__ = "1.0.0"
8
+ _CATALOG = json.loads(files(__package__).joinpath("data/catalog.json").read_text())
9
+
10
+
11
+ def show(assignment=None):
12
+ """List assignments, or display one assignment's questions and full source."""
13
+ if assignment is not None:
14
+ return _display(assignment)
15
+ print("AI lab assignments 2, 3, 4, 6, 8, 9")
16
+ for item in _CATALOG:
17
+ print(f"Assignment {item['number']} ({item['title']})")
18
+ print(f" NPS.{item['function']}()")
19
+ print("Display: NPS.assignment2_agents() | Run: NPS.run(2) | Export: NPS.export(2)")
20
+
21
+
22
+ def _validate(number):
23
+ if number not in [x["number"] for x in _CATALOG]:
24
+ raise ValueError("Choose assignment 2, 3, 4, 6, 8 or 9")
25
+ return number
26
+
27
+
28
+ def question(number):
29
+ """Print the assignment question and source note."""
30
+ print(files(__package__).joinpath(f"data/assignment{_validate(number)}.txt").read_text())
31
+
32
+
33
+ def code(number):
34
+ """Return full standalone Python source without executing it."""
35
+ return files(__package__).joinpath(f"solutions/assignment{_validate(number)}.py").read_text()
36
+
37
+
38
+ def _display(number):
39
+ question(number)
40
+ print("FULL PYTHON CODE\n")
41
+ print(code(number))
42
+
43
+
44
+ def run(number, **kwargs):
45
+ """Run the selected solution. Lab 8 accepts csv_path='/path/spam.csv'."""
46
+ number = _validate(number)
47
+ if number == 8:
48
+ from .solutions.assignment8 import main
49
+ return main(**kwargs)
50
+ if kwargs:
51
+ raise TypeError("Only assignment 8 accepts csv_path")
52
+ return runpy.run_module(f"Num.solutions.assignment{number}", run_name="__main__")
53
+
54
+
55
+ def export(number, directory="."):
56
+ """Write full code and question to files, refusing to overwrite existing files."""
57
+ number = _validate(number)
58
+ folder = Path(directory)
59
+ folder.mkdir(parents=True, exist_ok=True)
60
+ targets = [folder / f"assignment{number}.py", folder / f"assignment{number}_question.txt"]
61
+ if any(path.exists() for path in targets):
62
+ raise FileExistsError("An export file already exists; use a different directory")
63
+ targets[0].write_text(code(number), encoding="utf-8")
64
+ targets[1].write_text(files(__package__).joinpath(f"data/assignment{number}.txt").read_text(), encoding="utf-8")
65
+ return tuple(str(path.resolve()) for path in targets)
66
+
67
+
68
+ def _make_display(number, name):
69
+ def display():
70
+ return _display(number)
71
+ display.__name__ = name
72
+ display.__doc__ = f"Display all questions and full code for assignment {number}."
73
+ return display
74
+
75
+ for _item in _CATALOG:
76
+ globals()[_item["function"]] = _make_display(_item["number"], _item["function"])
77
+ globals()[f"assignment{_item['number']}"] = globals()[_item["function"]]
@@ -0,0 +1,17 @@
1
+ from . import show, run
2
+ import argparse
3
+
4
+ def main():
5
+ parser = argparse.ArgumentParser(description="AI lab study package")
6
+ parser.add_argument("assignment", type=int, nargs="?")
7
+ parser.add_argument("--run", action="store_true")
8
+ args = parser.parse_args()
9
+ if args.run:
10
+ if args.assignment is None:
11
+ parser.error("--run requires an assignment number")
12
+ run(args.assignment)
13
+ else:
14
+ show(args.assignment)
15
+
16
+ if __name__ == "__main__":
17
+ main()
@@ -0,0 +1,7 @@
1
+ Assignment 2 (Agents)
2
+
3
+ QUESTION
4
+ Implement a two-room Simple Reflex Vacuum Cleaner Agent. Show every state transition and stop when both rooms are clean. Convert it to a Model-Based Reflex Agent that remembers visited rooms, prints its memory, and chooses the next room using that memory. Also demonstrate the vending-machine reflex agent from the submitted notebook.
5
+
6
+ SOURCE NOTE
7
+ Task wording condensed from the Lab 2 document; the notebook additionally uses four rooms and a vending machine.
@@ -0,0 +1,7 @@
1
+ Assignment 3 (BFS and DFS)
2
+
3
+ QUESTION
4
+ Implement BFS and DFS to find a path from a start node to a goal node, and print their traversal orders. Use the submitted A-H graph with start A and goal H. Explain which algorithm guarantees the shortest path.
5
+
6
+ SOURCE NOTE
7
+ Condensed from the Lab 3 document and submitted code. BFS guarantees the fewest edges for an unweighted graph; DFS does not guarantee a shortest path.
@@ -0,0 +1,7 @@
1
+ Assignment 4 (Informed Search)
2
+
3
+ QUESTION
4
+ Implement Greedy Best First Search and A* for the submitted weighted A-Z graph and heuristics. Print the expansion order, actual start-to-goal path, and total path cost. Explain h(n) versus g(n)+h(n).
5
+
6
+ SOURCE NOTE
7
+ Condensed from the Lab 4 document and submitted notebook. The revised greedy code reconstructs the parent path rather than treating expansion order as a path.
@@ -0,0 +1,472 @@
1
+ Assignment 6 (Model Checking Algorithm)
2
+
3
+ QUESTION
4
+ Implement Sentence, Symbol, Not, And, Or, Implication, Biconditional and recursive model_check. Test operators, all six supplied inference cases, and an original three-proposition knowledge base. Explain why removing P from (P -> Q) AND (Q -> R) AND P changes entailment of R.
5
+
6
+ SOURCE NOTE
7
+ All 17 original notebook tasks are included below.
8
+
9
+ To implement a Propositional Logic Inference System using the Model Checking algorithm in Python.
10
+
11
+ ## Learning Objectives
12
+
13
+ After completing this experiment, students will be able to:
14
+
15
+ 1. Represent propositions using Python classes.
16
+ 2. Implement logical operators such as NOT, AND, OR, Implication and Biconditional.
17
+ 3. Represent a Knowledge Base (KB) and Query.
18
+ 4. Generate possible truth-value assignments called models.
19
+ 5. Implement Model Checking to determine logical entailment.
20
+
21
+ ## Problem Statement
22
+
23
+ Develop a Python-based Propositional Logic Inference System that determines whether a given Query logically follows from a Knowledge Base using Model Checking.
24
+
25
+ The system should support:
26
+
27
+ - Atomic propositions
28
+ - NOT
29
+ - AND
30
+ - OR
31
+ - Implication
32
+ - Biconditional
33
+ - Model Checking
34
+
35
+ Final Knowledge Base:
36
+
37
+ (P → Q) ∧ (Q → R) ∧ P
38
+
39
+ Query:
40
+
41
+ R
42
+
43
+ ## Theory
44
+
45
+ A proposition is a statement that can have either a True or False value.
46
+
47
+ Examples:
48
+
49
+ P = It is raining.
50
+
51
+ Q = The road is wet.
52
+
53
+ The following logical operators will be implemented:
54
+
55
+ | Operator | Symbol | Meaning |
56
+ |----------|--------|---------|
57
+ | NOT | ¬P | Opposite of P |
58
+ | AND | P ∧ Q | Both P and Q must be True |
59
+ | OR | P ∨ Q | At least one must be True |
60
+ | Implication | P → Q | If P is True, Q should be True |
61
+ | Biconditional | P ↔ Q | P and Q have the same truth value |
62
+
63
+ ### Model Checking
64
+
65
+ Model checking determines whether:
66
+
67
+ KB ⊨ Query
68
+
69
+ A Knowledge Base entails a Query if the Query is True in every possible model in which the Knowledge Base is True.
70
+
71
+ # Task 1: Create the Base Sentence Class
72
+
73
+ Create a base class named `Sentence`.
74
+
75
+ The class should contain the following methods:
76
+
77
+ 1. `evaluate(model)`
78
+ 2. `formula()`
79
+ 3. `symbols()`
80
+
81
+ ### Requirements
82
+
83
+ - `evaluate(model)` should evaluate a logical sentence.
84
+ - `formula()` should return the logical formula as a string.
85
+ - `symbols()` should return all symbols present in the sentence.
86
+
87
+ ### Student Task
88
+
89
+ Complete the following class.
90
+
91
+ # Task 2: Create the Symbol Class
92
+
93
+ Create a class named `Symbol` that inherits from `Sentence`.
94
+
95
+ For example:
96
+
97
+ P = Symbol("P")
98
+
99
+ The class should:
100
+
101
+ 1. Store the name of the symbol.
102
+ 2. Return its truth value from the given model.
103
+ 3. Return the symbol name as its formula.
104
+ 4. Return the symbol as a set.
105
+
106
+ ### Example Model
107
+
108
+ model = {
109
+ "P": True
110
+ }
111
+
112
+ For the above model, evaluating P should return True.
113
+
114
+ ### Student Task
115
+
116
+ Complete the following class.
117
+
118
+ # Task 3: Implement NOT
119
+
120
+ Implement the logical NOT operator.
121
+
122
+ NOT P is represented as:
123
+
124
+ ¬P
125
+
126
+ The NOT operation reverses the truth value.
127
+
128
+ If:
129
+
130
+ P = True
131
+
132
+ then:
133
+
134
+ ¬P = False
135
+
136
+ If:
137
+
138
+ P = False
139
+
140
+ then:
141
+
142
+ ¬P = True
143
+
144
+ ### Student Task
145
+
146
+ Create the `Not` class by completing the code below.
147
+
148
+ # Task 4: Implement AND
149
+
150
+ Implement the logical AND operator.
151
+
152
+ P ∧ Q is True only when both P and Q are True.
153
+
154
+ Truth Table:
155
+
156
+ | P | Q | P ∧ Q |
157
+ |---|---|-------|
158
+ | T | T | T |
159
+ | T | F | F |
160
+ | F | T | F |
161
+ | F | F | F |
162
+
163
+ ### Student Task
164
+
165
+ Create the `And` class.
166
+
167
+ # Task 5: Implement OR
168
+
169
+ Implement the logical OR operator.
170
+
171
+ P ∨ Q is True when at least one of P or Q is True.
172
+
173
+ Truth Table:
174
+
175
+ | P | Q | P ∨ Q |
176
+ |---|---|-------|
177
+ | T | T | T |
178
+ | T | F | T |
179
+ | F | T | T |
180
+ | F | F | F |
181
+
182
+ ### Student Task
183
+
184
+ Create the `Or` class.
185
+
186
+ # Task 6: Implement Implication
187
+
188
+ Implement:
189
+
190
+ P → Q
191
+
192
+ An implication is False only when:
193
+
194
+ P = True and Q = False
195
+
196
+ Truth Table:
197
+
198
+ | P | Q | P → Q |
199
+ |---|---|-------|
200
+ | T | T | T |
201
+ | T | F | F |
202
+ | F | T | T |
203
+ | F | F | T |
204
+
205
+ ### Student Task
206
+
207
+ Create the `Implication` class.
208
+
209
+ # Task 7: Implement Biconditional
210
+
211
+ Implement:
212
+
213
+ P ↔ Q
214
+
215
+ A biconditional is True when P and Q have the same truth value.
216
+
217
+ Truth Table:
218
+
219
+ | P | Q | P ↔ Q |
220
+ |---|---|-------|
221
+ | T | T | T |
222
+ | T | F | F |
223
+ | F | T | F |
224
+ | F | F | T |
225
+
226
+ ### Student Task
227
+
228
+ Create the `Biconditional` class.
229
+
230
+ # Task 8: Create Propositions
231
+
232
+ Create three propositions:
233
+
234
+ P
235
+ Q
236
+ R
237
+
238
+ Use the `Symbol` class created above.
239
+
240
+ ### Student Task
241
+
242
+ Create the three symbols and display them.
243
+
244
+ # Task 9: Test the Logical Operators
245
+
246
+ Create the following model:
247
+
248
+ P = True
249
+ Q = False
250
+
251
+ Use the model to test:
252
+
253
+ 1. P
254
+ 2. ¬P
255
+ 3. P ∧ Q
256
+ 4. P ∨ Q
257
+ 5. P → Q
258
+ 6. P ↔ Q
259
+
260
+ ### Student Task
261
+
262
+ Write Python code to evaluate all six expressions.
263
+
264
+ # Task 10: Implement Model Checking
265
+
266
+ Now implement the Model Checking algorithm.
267
+
268
+ The function should determine whether:
269
+
270
+ KB ⊨ Query
271
+
272
+ ### Algorithm
273
+
274
+ 1. Collect all symbols present in the Knowledge Base and Query.
275
+ 2. Generate all possible truth assignments.
276
+ 3. If the Knowledge Base is True for a model, check the Query.
277
+ 4. If the Query is False in even one model where the KB is True, return False.
278
+ 5. Otherwise return True.
279
+
280
+ ### Student Task
281
+
282
+ Complete the following function.
283
+
284
+ ### Hint
285
+
286
+ Use recursion.
287
+
288
+ For each symbol, create two possibilities:
289
+
290
+ - Symbol = True
291
+ - Symbol = False
292
+
293
+ # Task 11: Test Case 1
294
+
295
+ Knowledge Base:
296
+
297
+ P → Q
298
+
299
+ Query:
300
+
301
+ Q
302
+
303
+ ### Question
304
+
305
+ Does the Knowledge Base entail Q?
306
+
307
+ ### Expected Output
308
+
309
+ False
310
+
311
+ ### Student Task
312
+
313
+ Create the Knowledge Base and Query and use `model_check()` to obtain the result.
314
+
315
+ # Task 12: Test Case 2
316
+
317
+ Knowledge Base:
318
+
319
+ (P → Q) ∧ P
320
+
321
+ Query:
322
+
323
+ Q
324
+
325
+ This represents:
326
+
327
+ 1. If P is true, then Q is true.
328
+ 2. P is true.
329
+
330
+ Therefore, according to Modus Ponens:
331
+
332
+ Q should be true.
333
+
334
+ ### Expected Output
335
+
336
+ True
337
+
338
+ ### Student Task
339
+
340
+ Construct the Knowledge Base and Query using the classes developed above.
341
+
342
+ # Task 13: Test Case 3
343
+
344
+ Knowledge Base:
345
+
346
+ (P ∨ Q) ∧ ¬P
347
+
348
+ Query:
349
+
350
+ Q
351
+
352
+ ### Question
353
+
354
+ Does the Knowledge Base entail Q?
355
+
356
+ ### Expected Output
357
+
358
+ True
359
+
360
+ ### Student Task
361
+
362
+ Construct the Knowledge Base using:
363
+
364
+ - And
365
+ - Or
366
+ - Not
367
+
368
+ Then perform model checking.
369
+
370
+ # Task 14: Test Case 4
371
+
372
+ Knowledge Base:
373
+
374
+ P ↔ Q
375
+
376
+ Query:
377
+
378
+ P
379
+
380
+ ### Question
381
+
382
+ Does the Knowledge Base entail P?
383
+
384
+ ### Expected Output
385
+
386
+ False
387
+
388
+ ### Student Task
389
+
390
+ Implement the test using the `Biconditional` class.
391
+
392
+ Also explain in one or two sentences why the answer is False.
393
+
394
+ # Task 15: Three-Condition Inference
395
+
396
+ Consider the following Knowledge Base:
397
+
398
+ (P → Q) ∧ (Q → R) ∧ P
399
+
400
+ Query:
401
+
402
+ R
403
+
404
+ ### Reasoning
405
+
406
+ If:
407
+
408
+ P → Q
409
+
410
+ and:
411
+
412
+ Q → R
413
+
414
+ and:
415
+
416
+ P
417
+
418
+ then:
419
+
420
+ P → Q → R
421
+
422
+ Therefore, R should follow from the Knowledge Base.
423
+
424
+ ### Student Task
425
+
426
+ Construct the complete Knowledge Base using nested `And` and `Implication` objects.
427
+
428
+ Then use Model Checking to determine whether:
429
+
430
+ KB ⊨ R
431
+
432
+ # Task 16: Modify the Knowledge Base
433
+
434
+ Now remove the fact P from the Knowledge Base.
435
+
436
+ New Knowledge Base:
437
+
438
+ (P → Q) ∧ (Q → R)
439
+
440
+ Query:
441
+
442
+ R
443
+
444
+ ### Student Task
445
+
446
+ 1. Modify the Knowledge Base.
447
+ 2. Run Model Checking.
448
+ 3. Observe the result.
449
+ 4. Explain why the answer is different from Task 15.
450
+
451
+ # Task 17: Create Your Own Knowledge Base
452
+
453
+ Create your own Knowledge Base using:
454
+
455
+ - At least 3 propositions
456
+ - At least 2 different logical operators
457
+
458
+ Your Knowledge Base should contain meaningful logical relationships.
459
+
460
+ For example, you may use:
461
+
462
+ P, Q, R
463
+
464
+ ### Student Task
465
+
466
+ 1. Create the Knowledge Base.
467
+ 2. Create a Query.
468
+ 3. Apply Model Checking.
469
+ 4. Record whether the KB entails the Query.
470
+ 5. Explain the result.
471
+
472
+
@@ -0,0 +1,7 @@
1
+ Assignment 8 (Bayes Theorem and Spam Classification)
2
+
3
+ QUESTION
4
+ Load an SMS spam CSV; encode ham/spam; split training and test sets; build CountVectorizer features; train MultinomialNB; report accuracy, confusion matrix and classification report; classify two new messages.
5
+
6
+ SOURCE NOTE
7
+ Question reconstructed from the submitted Lab 8 code because Teams Instructions is None. No separate teacher question sheet was attached. Included CSV is synthetic demo data.
@@ -0,0 +1,7 @@
1
+ Assignment 9 (Bayesian Belief Network)
2
+
3
+ QUESTION
4
+ Build the submitted nine-variable Bayesian network A-I with its exact CPTs. Validate it; print CPTs and adjacency; draw the network; compute marginal, conditional, joint, MAP and independence queries; cross-check the 15 textbook probability queries by enumeration.
5
+
6
+ SOURCE NOTE
7
+ Question reconstructed from the submitted Lab 9 code because Teams Instructions is None. All submitted CPTs, example queries and enumeration checks are retained.
@@ -0,0 +1,32 @@
1
+ [
2
+ {
3
+ "number": 2,
4
+ "title": "Agents",
5
+ "function": "assignment2_agents"
6
+ },
7
+ {
8
+ "number": 3,
9
+ "title": "BFS and DFS",
10
+ "function": "assignment3_bfs_dfs"
11
+ },
12
+ {
13
+ "number": 4,
14
+ "title": "Informed Search",
15
+ "function": "assignment4_informed_search"
16
+ },
17
+ {
18
+ "number": 6,
19
+ "title": "Model Checking Algorithm",
20
+ "function": "assignment6_model_checking"
21
+ },
22
+ {
23
+ "number": 8,
24
+ "title": "Bayes Theorem and Spam Classification",
25
+ "function": "assignment8_bayes_theorem"
26
+ },
27
+ {
28
+ "number": 9,
29
+ "title": "Bayesian Belief Network",
30
+ "function": "assignment9_bayesian_belief_network"
31
+ }
32
+ ]
@@ -0,0 +1,33 @@
1
+ Label,Message
2
+ ham,Are we meeting today
3
+ ham,Please call me after class
4
+ ham,Lunch at noon with friends
5
+ ham,I will reach home soon
6
+ ham,Send me the lecture notes
7
+ ham,The project meeting is tomorrow
8
+ ham,Can you bring my book
9
+ ham,Let us study for the exam
10
+ ham,See you at the library
11
+ ham,Your appointment is at ten
12
+ ham,Thanks for helping yesterday
13
+ ham,Please buy milk on your way
14
+ ham,We have class this morning
15
+ ham,I am waiting near the station
16
+ ham,Dinner is ready at home
17
+ ham,Remember to submit your homework
18
+ spam,Congratulations win a free ticket now
19
+ spam,Claim your cash prize today
20
+ spam,Free offer click now to win
21
+ spam,You won a lottery claim your prize
22
+ spam,Exclusive discount offer buy now
23
+ spam,Win cash with this free offer
24
+ spam,Urgent claim your winning voucher
25
+ spam,Click here for a free prize
26
+ spam,Congratulations your reward is waiting
27
+ spam,Limited offer get free tickets
28
+ spam,You are selected for a cash reward
29
+ spam,Claim a free holiday voucher now
30
+ spam,Win a bonus prize click today
31
+ spam,Special promotion buy one get free
32
+ spam,Your lottery reward expires today
33
+ spam,Click now and claim cash bonus
File without changes