Logistics (kadi.market.logistics)¶
The Logistics class models real logistics friction across Beninese trade corridors: transport costs, checkpoint harassment fees, and merchantable quality degradation of agricultural produce.
Since v1.2.0, it optionally integrates weather forecasts to dynamically adjust the road coefficient (gamma_route) and quality loss based on expected rain probability.
It is used internally by Market and accessible via market.logistics. It can also be instantiated directly.
Direct Importing¶
Initialization¶
from kadi.market import Logistics
# Without weather integration (V1 behavior)
logistics = Logistics()
# With weather integration (dynamic cost adjustment based on rain forecast)
import kadi as kd
weather = kd.Weather(lat=9.3, lon=2.3, name="Parakou")
logistics = Logistics(weather=weather)
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
cache_file |
str |
None |
Path to JSON distance cache file. Default: ~/.kadi/osrm_cache.json |
weather |
Weather |
None |
Weather session for climate cost adjustments. If None, no adjustment (V1 behavior) |
Public Attributes:
| Attribute | Type | Description |
|---|---|---|
weather |
Weather |
Injected weather session (or None) |
cache_file |
str |
Distance cache file path |
cache |
dict |
In-memory cache dictionary with keys 'coords' and 'distances' |
Methods¶
transfer_cost(origine, destination, prix_carburant, crop)¶
Calculates total transfer cost from an origin city to a destination city.
Formula:
C_transfer = C_info
+ Distance * (gamma_effective * P_fuel / 100 + mu_checkpoints)
+ C_quality(crop, distance, rain)
Where:
- C_info = fixed information search cost (phone calls, local travel), configurable in config.py (default: 5,000 XOF)
- gamma_effective = gamma_route * (1 + alpha_rain * prob_rain): weather surcharge multiplier if a weather session is available
- mu_checkpoints = average checkpoint harassment fee per km (default: 15 XOF/km)
- C_quality = variable merchantable quality loss per crop type and weather condition
import kadi as kd
weather = kd.Weather(lat=9.3, lon=2.3, name="Parakou")
market = kd.Market(lat=9.3, lon=2.3, location="Parakou", weather=weather)
# Transfer cost with weather integration
cost = market.logistics.transfer_cost(
origine="Parakou",
destination="Cotonou",
crop="maize",
)
print(f"Total cost : {cost['total_cost_cfa']:,.0f} XOF")
print(f"Rain forecast : {cost['prob_pluie'] * 100:.0f}%")
print(f"Effective gamma : {cost['gamma_effectif']:.4f}")
# Breakdown details
d = cost["details"]
print(f" Distance : {d['distance_km']:.1f} km")
print(f" Search cost : {d['search_costs']:,.0f} XOF")
print(f" Transport cost : {d['transport_costs']:,.0f} XOF")
print(f" Quality loss : {d['quality_loss']:,.0f} XOF")
print(f" Fuel price used : {d['fuel_price_used']:.0f} XOF/liter")
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
origine |
str |
required | Departure city (e.g. 'Parakou') |
destination |
str |
required | Arrival city (e.g. 'Cotonou') |
prix_carburant |
float |
None |
Fuel price in XOF per liter. If None, fetched automatically |
crop |
str |
None |
Transported crop code for quality loss calculation. If None, uses default factor |
Returns: dict
| Key | Type | Description |
|---|---|---|
total_cost_cfa |
float |
Total transfer cost in XOF |
prob_pluie |
float |
Rain probability used (0.0 if no weather session) |
gamma_effectif |
float |
Effective road coefficient applied |
details |
dict |
Breakdown dictionary of each cost component |
Keys in details:
| Key | Description |
|---|---|
distance_km |
Road distance in km |
search_costs |
Fixed information search cost (XOF) |
transport_costs |
Distance-based transport cost (fuel + checkpoints) (XOF) |
quality_loss |
Merchantable quality loss value (XOF) |
fuel_price_used |
Fuel price applied (XOF/liter) |
gamma_route_base |
Base road coefficient before weather adjustment |
gamma_effectif |
Final road coefficient after weather adjustment |
prob_pluie |
Rain probability used |
crop |
Crop code ('_default' if unspecified) |
Quality Loss Factors by Crop (XOF/km/tonne):
| Crop | Factor | Crop | Factor |
|---|---|---|---|
maize, sorghum, millet |
5.0 | cowpea, soybean |
7.0 |
rice |
6.0 | yam |
12.0 |
cassava |
10.0 | tomato |
25.0 |
onion |
20.0 | (default) | 8.0 |
Under rainy conditions, quality loss increases according to: C_quality = factor * distance_km * (1 + beta_rain * prob_rain), where beta_rain is configurable in config.py (default: 0.5).
distance(origine, destination)¶
Retrieves road distance between two Beninese cities.
Cascade Strategy:
- Local cache (result from previous call, persisted in JSON file)
- Nominatim geocoding (OpenStreetMap) + OSRM routing
- Haversine fallback (great-circle distance multiplied by 1.3 tortuosity factor) if OSRM is unavailable
- Default fallback of 100 km if geocoding fails
d = market.logistics.distance("Parakou", "Cotonou")
print(f"Road distance : {d:.1f} km")
# Result automatically cached
d2 = market.logistics.distance("Cotonou", "Parakou") # Returned from cache
Parameters:
| Name | Type | Description |
|---|---|---|
origine |
str |
Departure city name |
destination |
str |
Arrival city name |
Returns: float - Estimated distance in kilometers.
The result is automatically cached in memory for the current session and saved to cache_file for future sessions.
Weather Integration¶
When a weather instance is provided during initialization, transfer cost calculation is automatically adjusted:
gamma_route: base coefficient (configurable inconfig.py, default: 1.2)alpha_rain: weather surcharge intensity (default: 0.25)prob_rain: tomorrow's rain probability, fetched viaweather.rain_prob(days=1)
Rain probability is fetched once per session (cached) to prevent redundant weather API calls.
Example:
With prob_rain=0.8 and alpha=0.25, the road coefficient increases from 1.2 to 1.2 * (1 + 0.25 * 0.8) = 1.44, representing a 20% surge in transport costs.
Fuel Price Retrieval Strategy¶
The transfer_cost() method automatically retrieves fuel price using the following priority order:
| Priority | Source |
|---|---|
| 1 | BENIN_FUEL_PRICE environment variable |
| 2 | In-memory session cache (one query per session) |
| 3 | config/fuel_prices.json file hosted on GitHub |
| 4 | Fallback value from config.py (default: 680 XOF/liter) |
Deprecated Methods¶
| Legacy Method | Replaced By | Since |
|---|---|---|
calculate_transfer_cost(origine, destination) |
transfer_cost(origine, destination) |
v1.2.0 |
get_distance(origine, destination) |
distance(origine, destination) |
v1.2.0 |
Deprecated Class¶
| Legacy Class | Replaced By | Since |
|---|---|---|
MarketLogistics |
Logistics |
v1.2.0 |
Complete Example¶
import kadi as kd
weather = kd.Weather(lat=9.3, lon=2.3, name="Parakou")
market = kd.Market(lat=9.3, lon=2.3, location="Parakou", weather=weather)
# Compare transfer costs for two crops (tomato being highly perishable)
crops = ["maize", "tomato"]
for crop in crops:
cost = market.logistics.transfer_cost("Parakou", "Cotonou", crop=crop)
print(
f"{crop:8s} -> {cost['total_cost_cfa']:,.0f} XOF "
f"(quality loss: {cost['details']['quality_loss']:,.0f} XOF)"
)
# Distance only
d = market.logistics.distance("Abomey", "Cotonou")
print(f"Abomey - Cotonou : {d:.1f} km")
Logistics ¶
Classe modélisant les frictions logistiques réelles au Bénin : coûts de transport, tracasseries aux postes de contrôle, et dégradation de la qualité des marchandises.
Phase 4 - Intégration météo
Si une session weather est fourni à l'initialisation, le calcul des coûts de transfert utilise la probabilité de pluie du lendemain pour ajuster gamma_route (état des routes) et la perte de qualité. En l'absence de la session weather, le comportement est identique à la V1.
Source code in kadi/market/logistics.py
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 | |
__init__ ¶
Initialise le module logistique.
Charge le cache persistant des coordonnées GPS et des distances routières pour éviter des appels réseau redondants.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_file
|
str
|
Chemin vers le fichier de cache JSON.
Si None, utilise |
None
|
weather
|
Weather
|
Session météo (kadi.weather.Weather) pour ajuster les coûts selon la météo prévue. Si None, pas d'ajustement climatique. |
None
|
Source code in kadi/market/logistics.py
__getattr__ ¶
Intercepte les accès aux anciens noms de méthodes publiques.
Délègue vers le nouveau nom et émet un DeprecationWarning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Nom de l'attribut ou méthode demandé. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
callable |
La méthode correspondante sous son nouveau nom. |
Raises:
| Type | Description |
|---|---|
AttributeError
|
Si le nom n'est ni nouveau ni ancien. |
Source code in kadi/market/logistics.py
distance ¶
Récupère la distance routière réelle entre deux villes béninoises.
Stratégie en cascade : 1. Cache local (résultat d'un appel précédent) 2. Géocodage Nominatim + routage OSRM 3. Fallback Haversine (vol d'oiseau * 1.3) si OSRM échoue 4. Valeur par défaut 100 km si le géocodage échoue
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
origine
|
str
|
Nom de la ville de départ (ex: 'Parakou'). |
required |
destination
|
str
|
Nom de la ville d'arrivée (ex: 'Cotonou'). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Distance estimée en kilomètres. |
Source code in kadi/market/logistics.py
transfer_cost ¶
transfer_cost(origine: str, destination: str, prix_carburant: float = None, crop: str = None) -> dict
Calcule le coût total de transfert d'un point A vers un point B.
Phase 4 - Intégration météo
Si une session weather a été fourni à l'initialisation, le calcul ajuste automatiquement : - gamma_route selon la probabilité de pluie prévue demain. - La perte de qualité selon la culture et la météo.
Formule
C_transfer = C_info + Distance * (gamma_effectif * P_carburant / 100 + mu_checkpoints) + C_qualite(culture, distance, pluie)
Ou : - C_info = coût fixe de recherche d'informations (appels, déplacements) - gamma_effectif = gamma_route * (1 + alpha_pluie * prob_pluie) - P_carburant = prix du litre d'essence en XOF - mu_checkpoints = coût moyen des tracasseries par km - C_qualite = perte de valeur marchande (variable par culture et météo)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
origine
|
str
|
Ville de départ (ex: 'Parakou'). |
required |
destination
|
str
|
Ville de destination (ex: 'Cotonou'). |
required |
prix_carburant
|
float
|
Prix du litre d'essence en XOF. Si None, récupéré automatiquement depuis les sources configurées. |
None
|
crop
|
str
|
Code de la culture transportée (ex: 'maize'). Influence la perte de qualité. Si None, utilise le facteur par défaut. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Dictionnaire contenant le coût total et le détail par poste : - 'total_cost_cfa' : coût total du transfert en XOF - 'details' : sous-dictionnaire avec chaque composante - 'prob_pluie' : probabilité de pluie utilisée (0 si pas de météo) - 'gamma_effectif' : gamma_route réellement appliqué |
Source code in kadi/market/logistics.py
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 | |