diagram_ph/README.md

535 lines
12 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# API Diagramme PH - Projet Complet
> API REST pour la génération de diagrammes Pression-Enthalpie (PH) et calculs thermodynamiques frigorifiques avancés
[![Python](https://img.shields.io/badge/Python-3.12+-blue.svg)](https://www.python.org/)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.109+-green.svg)](https://fastapi.tiangolo.com/)
[![Docker](https://img.shields.io/badge/Docker-Ready-blue.svg)](https://www.docker.com/)
[![AWS](https://img.shields.io/badge/AWS-Elastic%20Beanstalk-orange.svg)](https://aws.amazon.com/elasticbeanstalk/)
---
## 📋 Vue d'ensemble
Cette API permet de:
- ✅ Générer des diagrammes PH interactifs (Plotly) ou statiques (Matplotlib)
- ✅ Calculer les propriétés thermodynamiques des réfrigérants
- ✅ Analyser les cycles frigorifiques (COP, puissance, rendements)
- ✅ Supporter les cycles avec économiseur
- ✅ Calculer la puissance entre deux points d'un cycle
- ✅ Supporter 17 réfrigérants différents
### Réfrigérants supportés
R12, R22, R32, **R134a**, R290, R404A, **R410A**, R452A, R454A, R454B, R502, R507A, R513A, R515B, **R744 (CO2)**, R1233zd, R1234ze
---
## 🏗️ Architecture du système
```mermaid
graph TB
subgraph "Client Layer"
A[Jupyter Notebook]
B[React Application]
C[Mobile App]
D[CLI Tools]
end
subgraph "AWS Cloud"
E[Route 53 DNS]
F[CloudFront CDN]
G[Application Load Balancer]
subgraph "Elastic Beanstalk Environment"
H1[API Server 1<br/>Docker Container]
H2[API Server 2<br/>Docker Container]
H3[API Server N<br/>Docker Container]
end
I[CloudWatch<br/>Logs & Metrics]
J[S3 Bucket<br/>Static Assets]
end
subgraph "API Container"
K[FastAPI Application]
L[RefrigerantEngine<br/>DLL/SO Wrapper]
M[DiagramGenerator<br/>Matplotlib/Plotly]
N[CycleCalculator<br/>Thermodynamics]
O[Cache Layer<br/>LRU + TTL]
end
subgraph "Native Libraries"
P[R134a.so]
Q[R410A.so]
R[refifc.so]
S[Other refrigerants...]
end
A & B & C & D --> E
E --> F
F --> G
G --> H1 & H2 & H3
H1 & H2 & H3 --> I
H1 & H2 & H3 -.-> J
H1 --> K
K --> L & M & N & O
L --> P & Q & R & S
style A fill:#e1f5ff
style B fill:#e1f5ff
style C fill:#e1f5ff
style D fill:#e1f5ff
style G fill:#ff9999
style H1 fill:#99ff99
style H2 fill:#99ff99
style H3 fill:#99ff99
style K fill:#ffcc99
style L fill:#ffff99
style M fill:#ffff99
style N fill:#ffff99
```
---
## 📁 Structure du projet
```
diagram-ph-api/
├── 📄 API_SPECIFICATION.md # Spécifications complètes des endpoints
├── 📄 ARCHITECTURE.md # Architecture technique détaillée
├── 📄 DEPLOYMENT.md # Guide de déploiement AWS
├── 📄 IMPLEMENTATION_PLAN.md # Plan d'implémentation par phases
├── 📄 README.md # Ce fichier
├── app/ # Code source de l'API
│ ├── main.py # Point d'entrée FastAPI
│ ├── config.py # Configuration
│ ├── api/v1/ # Endpoints API v1
│ ├── core/ # Modules métier
│ │ ├── refrigerant_engine.py
│ │ ├── diagram_generator.py
│ │ ├── cycle_calculator.py
│ │ └── economizer.py
│ ├── models/ # Modèles Pydantic
│ ├── services/ # Business logic
│ └── utils/ # Utilitaires
├── libs/ # Bibliothèques natives
│ ├── dll/ # DLL Windows
│ └── so/ # Shared Objects Linux
├── tests/ # Tests automatisés
├── docker/ # Configuration Docker
├── deployment/ # Scripts et config AWS
└── docs/ # Documentation
```
---
## 🚀 Quick Start
### Prérequis
- Python 3.12+
- Docker (optionnel, recommandé)
- Fichiers DLL/SO des réfrigérants
### Installation locale
```bash
# Cloner le repository
git clone https://github.com/votre-org/diagram-ph-api.git
cd diagram-ph-api
# Créer environnement virtuel
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Installer dépendances
pip install -r requirements.txt
# Copier et configurer .env
cp .env.example .env
# Lancer l'API
uvicorn app.main:app --reload --port 8000
```
### Avec Docker
```bash
# Build et lancement
docker-compose -f docker/docker-compose.yml up --build
# API disponible sur http://localhost:8000
# Documentation sur http://localhost:8000/docs
```
---
## 📚 Documentation
### Endpoints principaux
| Endpoint | Méthode | Description |
|----------|---------|-------------|
| `/api/v1/health` | GET | Vérification santé de l'API |
| `/api/v1/refrigerants` | GET | Liste des réfrigérants disponibles |
| `/api/v1/diagram/generate` | POST | Génération diagramme PH |
| `/api/v1/calculations/cycle` | POST | Calculs cycle frigorifique |
| `/api/v1/calculations/power` | POST | Calcul puissance entre 2 points |
| `/api/v1/properties/calculate` | POST | Propriétés à un point |
### Exemple d'utilisation
#### Python
```python
import requests
# Générer un diagramme PH
response = requests.post(
"http://localhost:8000/api/v1/diagram/generate",
json={
"refrigerant": "R134a",
"output_format": "plotly_json",
"points": [
{
"type": "PT",
"pressure": 500000,
"temperature": 5,
"label": "Évaporateur",
"order": 1
},
{
"type": "PT",
"pressure": 1500000,
"temperature": 80,
"label": "Compresseur",
"order": 2
}
],
"diagram_options": {
"show_isotherms": True,
"isotherm_step": 10
}
}
)
data = response.json()
print(f"Success: {data['success']}")
# Utiliser data['data']['plotly_figure'] avec Plotly
```
#### JavaScript/React
```javascript
const response = await fetch('http://localhost:8000/api/v1/diagram/generate', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
refrigerant: 'R134a',
output_format: 'plotly_json',
points: [
{type: 'PT', pressure: 500000, temperature: 5, order: 1}
]
})
});
const data = await response.json();
// Afficher avec Plotly.react(divId, data.data.plotly_figure)
```
#### cURL
```bash
curl -X POST http://localhost:8000/api/v1/diagram/generate \
-H "Content-Type: application/json" \
-d '{
"refrigerant": "R134a",
"output_format": "matplotlib_png",
"points": [
{"type": "PT", "pressure": 500000, "temperature": 5}
]
}'
```
---
## 🧪 Tests
```bash
# Installer dépendances de test
pip install -r requirements-dev.txt
# Lancer tous les tests
pytest
# Avec couverture
pytest --cov=app --cov-report=html
# Tests d'intégration uniquement
pytest tests/test_api/
# Tests unitaires uniquement
pytest tests/test_core/
```
---
## 🐳 Déploiement Docker
### Build image production
```bash
docker build -f docker/Dockerfile -t diagram-ph-api:latest .
```
### Push vers AWS ECR
```bash
# Login ECR
aws ecr get-login-password --region eu-west-1 | \
docker login --username AWS --password-stdin \
123456789012.dkr.ecr.eu-west-1.amazonaws.com
# Tag et push
docker tag diagram-ph-api:latest \
123456789012.dkr.ecr.eu-west-1.amazonaws.com/diagram-ph-api:latest
docker push 123456789012.dkr.ecr.eu-west-1.amazonaws.com/diagram-ph-api:latest
```
---
## ☁️ Déploiement AWS Elastic Beanstalk
### Préparation (une seule fois)
```bash
# Installer EB CLI
pip install awsebcli
# Initialiser EB
eb init -p docker -r eu-west-1 diagram-ph-api
# Créer environnement
eb create diagram-ph-api-prod \
--instance-type t3.medium \
--scale 2
```
### Déploiement
```bash
# Déploiement automatique avec script
chmod +x deployment/scripts/deploy.sh
./deployment/scripts/deploy.sh
# Vérifier le statut
eb status
# Voir les logs
eb logs --stream
```
### Rollback
```bash
chmod +x deployment/scripts/rollback.sh
./deployment/scripts/rollback.sh
```
---
## 🎯 Fonctionnalités Frigorifiques
### Calculs supportés
#### 1. Coefficient de Performance (COP)
```
COP_froid = Q_évap / W_comp
COP_chaud = Q_cond / W_comp
```
#### 2. Puissances
```
Q_évap = ṁ × (h_sortie_évap - h_entrée_évap)
Q_cond = ṁ × (h_entrée_cond - h_sortie_cond)
W_comp = ṁ × (h_sortie_comp - h_entrée_comp)
```
#### 3. Rendements
- **Isentropique**: η_is = (h_sortie_isentropique - h_entrée) / (h_sortie_réel - h_entrée)
- **Volumétrique**: η_vol = Volume_aspiré_réel / Volume_balayé
- **Mécanique**: η_méca = Puissance_utile / Puissance_absorbée
#### 4. Cycle avec économiseur
Amélioration typique: **5-15% de COP en plus**
Principe:
- Sous-refroidissement du liquide avant détente principale
- Injection de vapeur flash au compresseur (pression intermédiaire)
- Réduction de la quantité de liquide à évaporer
---
## 📊 Performance
### Objectifs
| Métrique | Cible | Status |
|----------|-------|--------|
| Latence P50 | < 200ms | |
| Latence P95 | < 500ms | |
| Latence P99 | < 1000ms | |
| Throughput | 100 req/s/instance | |
| Disponibilité | > 99% | 🔄 |
| Taux d'erreur | < 0.1% | 🔄 |
### Optimisations
- **Cache multi-niveaux**: LRU + TTL pour propriétés thermodynamiques
- **Pré-calcul**: Courbes de saturation au démarrage
- **Compression**: Gzip automatique pour réponses volumineuses
- **Parallélisation**: Asyncio pour I/O
---
## 💰 Coûts AWS estimés
### Configuration Production Standard
| Service | Configuration | Coût/mois |
|---------|---------------|-----------|
| EC2 (2x t3.medium) | 2 vCPU, 4 GB RAM | ~$60 |
| Application Load Balancer | | ~$20 |
| Data Transfer | 100 GB | ~$9 |
| CloudWatch | Logs + Métriques | ~$5 |
| **TOTAL** | | **~$94/mois** |
---
## 🔒 Sécurité
- HTTPS obligatoire (certificat SSL via AWS)
- Rate limiting (100 req/minute par IP)
- CORS configuré
- Validation stricte des inputs (Pydantic)
- Logs d'audit complets
- Pas d'eval() ou exec() sur inputs utilisateur
---
## 📈 Monitoring
### Métriques CloudWatch
- Latence des requêtes API
- Taux d'erreur par endpoint
- Utilisation CPU/RAM
- Nombre de requêtes par réfrigérant
- Cache hit/miss ratio
### Logs structurés
Format JSON pour analyse automatisée:
```json
{
"timestamp": "2025-10-18T12:30:00Z",
"level": "INFO",
"message": "Diagram generated",
"refrigerant": "R134a",
"duration_ms": 245,
"output_format": "plotly_json"
}
```
---
## 🤝 Contribution
### Processus
1. Fork le projet
2. Créer une branche feature (`git checkout -b feature/amazing-feature`)
3. Commit les changements (`git commit -m 'Add amazing feature'`)
4. Push vers la branche (`git push origin feature/amazing-feature`)
5. Ouvrir une Pull Request
### Standards de code
```bash
# Formatage
black app/ tests/
# Linting
ruff check app/ tests/
# Type checking
mypy app/
```
---
## 📝 Licence
Ce projet est sous licence MIT. Voir le fichier `LICENSE` pour plus de détails.
---
## 👥 Auteurs
- Équipe HVAC Engineering
- Contact: api-support@diagramph.com
---
## 🙏 Remerciements
- FastAPI pour le framework web performant
- Plotly et Matplotlib pour la visualisation
- AWS pour l'infrastructure cloud
- La communauté Python pour les bibliothèques
---
## 📞 Support
- 📧 Email: support@diagramph.com
- 📖 Documentation: https://docs.diagramph.com
- 🐛 Issues: https://github.com/votre-org/diagram-ph-api/issues
- 💬 Discord: https://discord.gg/diagramph
---
## 🗺️ Roadmap
### Version 1.1 (Q1 2026)
- [ ] Support de réfrigérants supplémentaires
- [ ] Calculs de cycles multi-étagés
- [ ] Export PDF des diagrammes
- [ ] API GraphQL en parallèle de REST
### Version 1.2 (Q2 2026)
- [ ] Machine learning pour optimisation de cycles
- [ ] Comparaison automatique de réfrigérants
- [ ] Calculs de dimensionnement d'équipements
- [ ] Application mobile native
### Version 2.0 (Q3 2026)
- [ ] Simulation dynamique de cycles
- [ ] Intégration BIM/CAD
- [ ] Marketplace de cycles optimisés
- [ ] Certification énergétique automatique
---
**Dernière mise à jour**: 18 octobre 2025
**Version**: 1.0.0
**Status**: 🚀 Prêt pour implémentation