diagram_ph/README.md

451 lines
10 KiB
Markdown
Raw Permalink 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]
# API Diagramme PH - Project Overview (English)
This repository contains a FastAPI-based REST API for generating Pressure-Enthalpy (PH) diagrams
and performing advanced refrigeration thermodynamic calculations.
For the full French documentation, see: `README_fr.md` (converted from the original README).
Badges
- Python 3.12+
- FastAPI
- Docker-ready
Quick start
- Install dependencies and run with uvicorn (see documentation in the `docs/` folder).
Repository structure (short)
- `app/` : application code
- `libs/` : native libraries (dll/ and so/)
- `scripts/` : helper scripts
- `docs/` : extra documentation
If you need the original French README, open `README_fr.md`.
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