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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GreedyOptim Scheduling API Documentation
2
+
3
+ ## Overview
4
+
5
+ The GreedyOptim API provides advanced train scheduling optimization using multiple algorithms including Genetic Algorithms, Particle Swarm Optimization, CMA-ES, and more. This API allows you to submit your own trainset data and receive optimized scheduling recommendations.
6
+
7
+ **Base URL:** `http://localhost:8001`
8
+
9
+ **API Version:** 2.0.0
10
+
11
+ ---
12
+
13
+ ## Quick Start
14
+
15
+ ### 1. Start the API Server
16
+
17
+ ```bash
18
+ python api/run_greedyoptim_api.py
19
+ ```
20
+
21
+ The API will be available at:
22
+ - **API Endpoint:** http://localhost:8001
23
+ - **Interactive Docs:** http://localhost:8001/docs
24
+ - **Alternative Docs:** http://localhost:8001/redoc
25
+
26
+ ### 2. Test the API
27
+
28
+ ```bash
29
+ python api/test_greedyoptim_api.py
30
+ ```
31
+
32
+ ---
33
+
34
+ ## Authentication
35
+
36
+ Currently, the API does not require authentication. Configure authentication as needed for production use.
37
+
38
+ ---
39
+
40
+ ## Endpoints
41
+
42
+ ### 1. Health Check
43
+
44
+ **GET** `/health`
45
+
46
+ Check if the API is running.
47
+
48
+ **Response:**
49
+ ```json
50
+ {
51
+ "status": "healthy",
52
+ "timestamp": "2025-11-09T10:30:00",
53
+ "service": "greedyoptim-api"
54
+ }
55
+ ```
56
+
57
+ ---
58
+
59
+ ### 2. List Available Methods
60
+
61
+ **GET** `/methods`
62
+
63
+ Get information about all available optimization methods.
64
+
65
+ **Response:**
66
+ ```json
67
+ {
68
+ "available_methods": {
69
+ "ga": {
70
+ "name": "Genetic Algorithm",
71
+ "description": "Evolutionary optimization using selection, crossover, and mutation",
72
+ "typical_time": "medium",
73
+ "solution_quality": "high"
74
+ },
75
+ "pso": {
76
+ "name": "Particle Swarm Optimization",
77
+ "description": "Swarm intelligence-based optimization",
78
+ "typical_time": "medium",
79
+ "solution_quality": "high"
80
+ },
81
+ "cmaes": {
82
+ "name": "CMA-ES",
83
+ "description": "Covariance Matrix Adaptation Evolution Strategy",
84
+ "typical_time": "medium-high",
85
+ "solution_quality": "very high"
86
+ },
87
+ ...
88
+ },
89
+ "default_method": "ga",
90
+ "recommended_for_speed": "ga",
91
+ "recommended_for_quality": "ensemble"
92
+ }
93
+ ```
94
+
95
+ ---
96
+
97
+ ### 3. Optimize Schedule
98
+
99
+ **POST** `/optimize`
100
+
101
+ Submit trainset data and receive an optimized schedule.
102
+
103
+ **Request Body:**
104
+ ```json
105
+ {
106
+ "trainset_status": [
107
+ {
108
+ "trainset_id": "KMRL-01",
109
+ "operational_status": "Available",
110
+ "last_maintenance_date": "2025-10-01",
111
+ "total_mileage_km": 45000.0,
112
+ "age_years": 3.5
113
+ },
114
+ ...
115
+ ],
116
+ "fitness_certificates": [
117
+ {
118
+ "trainset_id": "KMRL-01",
119
+ "department": "Safety",
120
+ "status": "Valid",
121
+ "issue_date": "2025-01-01",
122
+ "expiry_date": "2026-01-01"
123
+ },
124
+ ...
125
+ ],
126
+ "job_cards": [
127
+ {
128
+ "trainset_id": "KMRL-01",
129
+ "job_id": "JOB-001",
130
+ "priority": "Medium",
131
+ "status": "Closed",
132
+ "description": "Routine inspection",
133
+ "estimated_hours": 2.0
134
+ },
135
+ ...
136
+ ],
137
+ "component_health": [
138
+ {
139
+ "trainset_id": "KMRL-01",
140
+ "component": "Brakes",
141
+ "status": "Good",
142
+ "wear_level": 25.0,
143
+ "last_inspection": "2025-10-15"
144
+ },
145
+ ...
146
+ ],
147
+ "method": "ga",
148
+ "config": {
149
+ "required_service_trains": 15,
150
+ "min_standby": 2,
151
+ "population_size": 50,
152
+ "generations": 100,
153
+ "mutation_rate": 0.1,
154
+ "crossover_rate": 0.8,
155
+ "elite_size": 5
156
+ }
157
+ }
158
+ ```
159
+
160
+ **Field Descriptions:**
161
+
162
+ **trainset_status** (required):
163
+ - `trainset_id`: Unique identifier (string)
164
+ - `operational_status`: One of: `Available`, `In-Service`, `Maintenance`, `Standby`, `Out-of-Order`
165
+ - `last_maintenance_date`: ISO date string (optional)
166
+ - `total_mileage_km`: Total kilometers traveled (optional)
167
+ - `age_years`: Age of trainset in years (optional)
168
+
169
+ **fitness_certificates** (required):
170
+ - `trainset_id`: Must match trainset_status
171
+ - `department`: One of: `Safety`, `Operations`, `Technical`, `Electrical`, `Mechanical`
172
+ - `status`: One of: `Valid`, `Expired`, `Expiring-Soon`, `Suspended`
173
+ - `issue_date`: ISO date string (optional)
174
+ - `expiry_date`: ISO date string (optional)
175
+
176
+ **job_cards** (required, can be empty array):
177
+ - `trainset_id`: Must match trainset_status
178
+ - `job_id`: Unique job identifier
179
+ - `priority`: One of: `Critical`, `High`, `Medium`, `Low`
180
+ - `status`: One of: `Open`, `In-Progress`, `Closed`, `Pending-Parts`
181
+ - `description`: Job description (optional)
182
+ - `estimated_hours`: Estimated completion time (optional)
183
+
184
+ **component_health** (required):
185
+ - `trainset_id`: Must match trainset_status
186
+ - `component`: Component name (e.g., `Brakes`, `HVAC`, `Doors`, `Propulsion`)
187
+ - `status`: One of: `Good`, `Fair`, `Warning`, `Critical`
188
+ - `wear_level`: Wear percentage 0-100 (optional)
189
+ - `last_inspection`: ISO date string (optional)
190
+
191
+ **method** (optional, default: "ga"):
192
+ - `ga`: Genetic Algorithm (recommended for most cases)
193
+ - `pso`: Particle Swarm Optimization
194
+ - `cmaes`: CMA-ES (best quality, slower)
195
+ - `sa`: Simulated Annealing
196
+ - `nsga2`: Multi-objective optimization
197
+ - `adaptive`: Auto-selects best method
198
+ - `ensemble`: Runs multiple methods (best quality, slowest)
199
+
200
+ **config** (optional):
201
+ - `required_service_trains`: Minimum trains needed in service (default: 15)
202
+ - `min_standby`: Minimum standby trains (default: 2)
203
+ - `population_size`: Algorithm population size (default: 50, range: 10-200)
204
+ - `generations`: Number of iterations (default: 100, range: 10-1000)
205
+ - `mutation_rate`: Mutation probability (default: 0.1, range: 0.0-1.0)
206
+ - `crossover_rate`: Crossover probability (default: 0.8, range: 0.0-1.0)
207
+ - `elite_size`: Number of elite solutions preserved (default: 5)
208
+
209
+ **Response:**
210
+ ```json
211
+ {
212
+ "success": true,
213
+ "method": "ga",
214
+ "fitness_score": 0.8542,
215
+ "service_trains": ["KMRL-01", "KMRL-02", "KMRL-03", ...],
216
+ "standby_trains": ["KMRL-15", "KMRL-16"],
217
+ "maintenance_trains": ["KMRL-17", "KMRL-18"],
218
+ "unavailable_trains": [],
219
+ "num_service": 15,
220
+ "num_standby": 2,
221
+ "num_maintenance": 2,
222
+ "num_unavailable": 0,
223
+ "service_score": 0.95,
224
+ "standby_score": 0.85,
225
+ "health_score": 0.78,
226
+ "certificate_score": 0.92,
227
+ "execution_time_seconds": 2.341,
228
+ "timestamp": "2025-11-09T10:35:00",
229
+ "constraints_satisfied": true,
230
+ "warnings": null
231
+ }
232
+ ```
233
+
234
+ ---
235
+
236
+ ### 4. Compare Methods
237
+
238
+ **POST** `/compare`
239
+
240
+ Compare multiple optimization methods on the same data.
241
+
242
+ **Request Body:**
243
+ ```json
244
+ {
245
+ "trainset_status": [...],
246
+ "fitness_certificates": [...],
247
+ "job_cards": [...],
248
+ "component_health": [...],
249
+ "methods": ["ga", "pso", "cmaes"],
250
+ "config": {
251
+ "required_service_trains": 15,
252
+ "min_standby": 2,
253
+ "population_size": 30,
254
+ "generations": 50
255
+ }
256
+ }
257
+ ```
258
+
259
+ **Response:**
260
+ ```json
261
+ {
262
+ "methods": {
263
+ "ga": {
264
+ "success": true,
265
+ "method": "ga",
266
+ "fitness_score": 0.8542,
267
+ "service_trains": [...],
268
+ "execution_time_seconds": 1.234,
269
+ ...
270
+ },
271
+ "pso": {
272
+ "success": true,
273
+ "method": "pso",
274
+ "fitness_score": 0.8398,
275
+ ...
276
+ },
277
+ "cmaes": {
278
+ "success": true,
279
+ "method": "cmaes",
280
+ "fitness_score": 0.8721,
281
+ ...
282
+ }
283
+ },
284
+ "summary": {
285
+ "total_execution_time": 5.678,
286
+ "methods_compared": 3,
287
+ "best_method": "cmaes",
288
+ "best_score": 0.8721,
289
+ "timestamp": "2025-11-09T10:40:00"
290
+ }
291
+ }
292
+ ```
293
+
294
+ ---
295
+
296
+ ### 5. Generate Synthetic Data
297
+
298
+ **POST** `/generate-synthetic`
299
+
300
+ Generate synthetic test data for testing purposes.
301
+
302
+ **Request Body:**
303
+ ```json
304
+ {
305
+ "num_trainsets": 25,
306
+ "maintenance_rate": 0.1,
307
+ "availability_rate": 0.8
308
+ }
309
+ ```
310
+
311
+ **Response:**
312
+ ```json
313
+ {
314
+ "success": true,
315
+ "data": {
316
+ "trainset_status": [...],
317
+ "fitness_certificates": [...],
318
+ "job_cards": [...],
319
+ "component_health": [...],
320
+ "metadata": {...}
321
+ },
322
+ "metadata": {
323
+ "num_trainsets": 25,
324
+ "num_fitness_certificates": 125,
325
+ "num_job_cards": 50,
326
+ "num_component_health": 150,
327
+ "generated_at": "2025-11-09T10:45:00"
328
+ }
329
+ }
330
+ ```
331
+
332
+ ---
333
+
334
+ ### 6. Validate Data
335
+
336
+ **POST** `/validate`
337
+
338
+ Validate your data structure before submitting for optimization.
339
+
340
+ **Request Body:**
341
+ ```json
342
+ {
343
+ "trainset_status": [...],
344
+ "fitness_certificates": [...],
345
+ "job_cards": [...],
346
+ "component_health": [...],
347
+ "method": "ga"
348
+ }
349
+ ```
350
+
351
+ **Response (Valid):**
352
+ ```json
353
+ {
354
+ "valid": true,
355
+ "message": "Data structure is valid",
356
+ "num_trainsets": 25,
357
+ "num_certificates": 125,
358
+ "num_job_cards": 50,
359
+ "num_component_health": 150
360
+ }
361
+ ```
362
+
363
+ **Response (Invalid):**
364
+ ```json
365
+ {
366
+ "valid": false,
367
+ "validation_errors": [
368
+ "Missing required data section: trainset_status",
369
+ "Invalid operational_status value: 'Running' for trainset KMRL-05"
370
+ ],
371
+ "suggestions": [
372
+ "Check that all trainset_ids are consistent across sections",
373
+ "Ensure operational_status values are valid (Available, In-Service, Maintenance, Standby, Out-of-Order)",
374
+ "Verify certificate status values are valid (Valid, Expired, Expiring-Soon, Suspended)",
375
+ "Verify certificate expiry dates are in ISO format",
376
+ "Confirm component wear_level is between 0-100 if provided"
377
+ ]
378
+ }
379
+ ```
380
+
381
+ ---
382
+
383
+ ## Usage Examples
384
+
385
+ ### Example 1: Basic Optimization (Python)
386
+
387
+ ```python
388
+ import requests
389
+
390
+ # Your trainset data
391
+ data = {
392
+ "trainset_status": [
393
+ {"trainset_id": "KMRL-01", "operational_status": "Available"},
394
+ {"trainset_id": "KMRL-02", "operational_status": "Available"},
395
+ # ... more trainsets
396
+ ],
397
+ "fitness_certificates": [
398
+ {
399
+ "trainset_id": "KMRL-01",
400
+ "department": "Safety",
401
+ "status": "Valid",
402
+ "expiry_date": "2026-01-01"
403
+ },
404
+ # ... more certificates
405
+ ],
406
+ "job_cards": [], # No pending jobs
407
+ "component_health": [
408
+ {
409
+ "trainset_id": "KMRL-01",
410
+ "component": "Brakes",
411
+ "status": "Good",
412
+ "wear_level": 20.0
413
+ },
414
+ # ... more components
415
+ ],
416
+ "method": "ga",
417
+ "config": {
418
+ "required_service_trains": 15,
419
+ "min_standby": 2
420
+ }
421
+ }
422
+
423
+ # Send request
424
+ response = requests.post("http://localhost:8001/optimize", json=data)
425
+ result = response.json()
426
+
427
+ print(f"Fitness Score: {result['fitness_score']}")
428
+ print(f"Service Trains: {result['num_service']}")
429
+ print(f"Execution Time: {result['execution_time_seconds']}s")
430
+ ```
431
+
432
+ ### Example 2: Compare Methods (cURL)
433
+
434
+ ```bash
435
+ curl -X POST "http://localhost:8001/compare" \
436
+ -H "Content-Type: application/json" \
437
+ -d '{
438
+ "trainset_status": [...],
439
+ "fitness_certificates": [...],
440
+ "job_cards": [],
441
+ "component_health": [...],
442
+ "methods": ["ga", "pso"],
443
+ "config": {
444
+ "population_size": 30,
445
+ "generations": 50
446
+ }
447
+ }'
448
+ ```
449
+
450
+ ### Example 3: Validate Before Optimizing (JavaScript)
451
+
452
+ ```javascript
453
+ const data = {
454
+ trainset_status: [...],
455
+ fitness_certificates: [...],
456
+ job_cards: [],
457
+ component_health: [...],
458
+ method: "ga"
459
+ };
460
+
461
+ // Validate first
462
+ const validateResponse = await fetch('http://localhost:8001/validate', {
463
+ method: 'POST',
464
+ headers: { 'Content-Type': 'application/json' },
465
+ body: JSON.stringify(data)
466
+ });
467
+
468
+ const validation = await validateResponse.json();
469
+
470
+ if (validation.valid) {
471
+ // Now optimize
472
+ const optimizeResponse = await fetch('http://localhost:8001/optimize', {
473
+ method: 'POST',
474
+ headers: { 'Content-Type': 'application/json' },
475
+ body: JSON.stringify(data)
476
+ });
477
+
478
+ const result = await optimizeResponse.json();
479
+ console.log('Optimization successful:', result);
480
+ } else {
481
+ console.error('Validation errors:', validation.validation_errors);
482
+ }
483
+ ```
484
+
485
+ ---
486
+
487
+ ## Error Handling
488
+
489
+ ### HTTP Status Codes
490
+
491
+ - **200**: Success
492
+ - **400**: Bad Request (validation error)
493
+ - **500**: Internal Server Error
494
+
495
+ ### Error Response Format
496
+
497
+ ```json
498
+ {
499
+ "error": "Data validation failed",
500
+ "validation_errors": [
501
+ "Missing required field: trainset_id in trainset_status",
502
+ "Invalid operational_status value"
503
+ ],
504
+ "message": "Please fix the data structure and try again"
505
+ }
506
+ ```
507
+
508
+ ---
509
+
510
+ ## Data Requirements
511
+
512
+ ### Minimum Required Data
513
+
514
+ To successfully optimize a schedule, you must provide:
515
+
516
+ 1. **At least 10 trainsets** in `trainset_status`
517
+ 2. **At least one fitness certificate** per trainset
518
+ 3. **Component health data** for each trainset
519
+ 4. **job_cards** can be an empty array if no maintenance is pending
520
+
521
+ ### Valid Status Values
522
+
523
+ **Operational Status:**
524
+ - `Available` - Ready for service
525
+ - `In-Service` - Currently operating
526
+ - `Maintenance` - Under maintenance
527
+ - `Standby` - On standby
528
+ - `Out-of-Order` - Not operational
529
+
530
+ **Certificate Status:**
531
+ - `Valid` - Certificate is valid
532
+ - `Expired` - Certificate has expired
533
+ - `Expiring-Soon` - Certificate expires within 30 days
534
+ - `Suspended` - Certificate suspended
535
+
536
+ **Job Priority:**
537
+ - `Critical` - Must be addressed immediately
538
+ - `High` - High priority
539
+ - `Medium` - Medium priority
540
+ - `Low` - Low priority
541
+
542
+ **Job Status:**
543
+ - `Open` - Not started
544
+ - `In-Progress` - Currently being worked on
545
+ - `Closed` - Completed
546
+ - `Pending-Parts` - Waiting for parts
547
+
548
+ **Component Status:**
549
+ - `Good` - Component in good condition
550
+ - `Fair` - Component acceptable
551
+ - `Warning` - Component needs attention soon
552
+ - `Critical` - Component requires immediate attention
553
+
554
+ ---
555
+
556
+ ## Performance Tips
557
+
558
+ ### For Faster Results:
559
+ - Use `method: "ga"` (Genetic Algorithm)
560
+ - Reduce `population_size` (e.g., 30)
561
+ - Reduce `generations` (e.g., 50)
562
+ - Test with fewer trainsets first
563
+
564
+ ### For Best Quality:
565
+ - Use `method: "ensemble"` (runs multiple algorithms)
566
+ - Increase `population_size` (e.g., 100)
567
+ - Increase `generations` (e.g., 200)
568
+ - Use `method: "cmaes"` for single-method optimization
569
+
570
+ ### Recommended Configurations:
571
+
572
+ **Quick Testing (< 1 second):**
573
+ ```json
574
+ {
575
+ "method": "ga",
576
+ "config": {
577
+ "population_size": 20,
578
+ "generations": 30
579
+ }
580
+ }
581
+ ```
582
+
583
+ **Production Use (2-5 seconds):**
584
+ ```json
585
+ {
586
+ "method": "ga",
587
+ "config": {
588
+ "population_size": 50,
589
+ "generations": 100
590
+ }
591
+ }
592
+ ```
593
+
594
+ **High Quality (10-30 seconds):**
595
+ ```json
596
+ {
597
+ "method": "ensemble",
598
+ "config": {
599
+ "population_size": 100,
600
+ "generations": 200
601
+ }
602
+ }
603
+ ```
604
+
605
+ ---
606
+
607
+ ## Rate Limits
608
+
609
+ Currently, no rate limits are enforced. Implement rate limiting for production use.
610
+
611
+ ---
612
+
613
+ ## Support
614
+
615
+ For issues or questions:
616
+ - Check the interactive documentation: http://localhost:8001/docs
617
+ - Run the test suite: `python api/test_greedyoptim_api.py`
618
+ - Review validation errors carefully - they indicate exactly what's wrong
619
+
620
+ ---
621
+
622
+ ## Changelog
623
+
624
+ ### Version 2.0.0 (2025-11-09)
625
+ - Initial release of GreedyOptim API
626
+ - Support for multiple optimization algorithms
627
+ - Custom data input support
628
+ - Validation and synthetic data generation
629
+ - Method comparison capabilities