File size: 5,737 Bytes
110eb15
 
 
 
 
 
 
2eb0f5c
 
 
 
 
 
110eb15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44cdbab
110eb15
44cdbab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110eb15
 
 
 
 
 
44cdbab
110eb15
 
 
 
 
 
44cdbab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110eb15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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
# Land Redistribution Algorithm Tester

Test land subdivision and redistribution algorithms with FastAPI backend and Streamlit frontend.

## Features

- **Algorithm Implementation**: 100% equivalent logic from `algo.ipynb`
  - **Stage 1: Grid Optimization**: Uses NSGA-II (Genetic Algorithm) to find the optimal grid orientation and spacing.
- **Stage 2: Subdivision**: Uses OR-Tools (Constraint Programming) to subdivide blocks into individual lots, optimizing for target dimensions.
- **Stage 3: Infrastructure**: Generates technical networks (electricity/water MST) and drainage plans.
- **Zoning**: Automatically classifies lands into Residential, Service (Operations/Parking), and Wastewater Treatment (XLNT).
- **Visualization**: Interactive maps (Folium) and static notebook-style architectural plots (Matplotlib).
- **DXF Support**: Import site boundaries from DXF files and export results.ing and visualization
- **No Database**: In-memory processing for algorithm testing

## Project Structure

```
algorithms/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ main.py           # FastAPI app entry point
β”‚   β”œβ”€β”€ models.py         # Pydantic models
β”‚   β”œβ”€β”€ algorithm.py      # Core algorithm implementation
β”‚   β”œβ”€β”€ routes.py         # API endpoints
β”‚   └── requirements.txt
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ app.py           # Streamlit frontend
β”‚   └── requirements.txt
β”œβ”€β”€ .env.example
└── README.md
```

## Quick Start

### Option 1: Docker Compose (Recommended)

Run both backend and frontend with a single command:

```bash
cd algorithms
make build  # Build Docker images
make up     # Start services
```

Services will be available at:
- **Backend API**: http://localhost:8000
- **Frontend UI**: http://localhost:8501
- **API Docs**: http://localhost:8000/docs

Stop services:
```bash
make down
```

### Option 2: Manual Installation

#### Backend

```bash
cd algorithms/backend
pip install -r requirements.txt
```

#### Frontend

```bash
cd algorithms/frontend
pip install -r requirements.txt
```

## Deployment

### Production Deployment

For deploying to production environments:

- **Backend**: Deploy to [Hugging Face Spaces](https://huggingface.co/spaces) using Docker
- **Frontend**: Deploy to [Streamlit Cloud](https://streamlit.io/cloud) or any hosting service

πŸ“– **See [DEPLOYMENT.md](DEPLOYMENT.md) for detailed deployment instructions**

### Environment Variables

Create a `.env` file (copy from `.env.production`):

**Backend**:
```bash
API_HOST=0.0.0.0
API_PORT=7860
CORS_ORIGINS=*
LOG_LEVEL=INFO
```

**Frontend**:
```bash
API_URL=http://localhost:8000  # Development
# API_URL=https://your-space.hf.space  # Production
```

## Running the Application

### Start Backend Server

```bash
cd algorithms/backend
uvicorn main:app --reload --port 8000
```

The API will be available at:
- API: http://localhost:8000
- Interactive docs: http://localhost:8000/docs
- Alternative docs: http://localhost:8000/redoc

### Start Frontend Application

In a new terminal:

```bash
cd algorithms/frontend
streamlit run app.py
```

The Streamlit app will open in your browser at http://localhost:8501

## Usage

1. **Configure Parameters** (in sidebar):
   - Grid spacing range (20-30m)
   - Rotation angle range (0-90Β°)
   - Lot width constraints (5-8m)
   - Population size and generations for NSGA-II

2. **Input Land Plots**:
   - Use sample rectangular plot
   - Upload GeoJSON file
   - Enter coordinates manually

3. **Run Optimization**:
   - Click "Run Full Pipeline"
   - Wait for results (typically 30-60 seconds)

4. **View Results**:
   - Summary statistics (blocks, lots, parks)
   - Stage-by-stage visualizations
   - Download GeoJSON or JSON results

## API Endpoints

### `POST /api/optimize`
Run complete optimization pipeline (all stages)

**Request**:
```json
{
  "config": {
    "spacing_min": 20.0,
    "spacing_max": 30.0,
    "angle_min": 0.0,
    "angle_max": 90.0,
    "min_lot_width": 5.0,
    "max_lot_width": 8.0,
    "target_lot_width": 6.0,
    "road_width": 6.0,
    "block_depth": 50.0,
    "population_size": 50,
    "generations": 100
  },
  "land_plots": [{
    "type": "Polygon",
    "coordinates": [[[0, 0], [100, 0], [100, 100], [0, 100], [0, 0]]],
    "properties": {}
  }]
}
```

**Response**: Results with stages, metrics, and final GeoJSON layout

### `POST /api/stage1`
Run only grid optimization stage

### `GET /health`
Health check endpoint

## Algorithm Details

### Stage 1: Grid Optimization (NSGA-II)
- Multi-objective genetic algorithm
- Objectives:
  1. Maximize residential area
  2. Minimize fragmented blocks
- Uses DEAP library for evolutionary computation

### Stage 2: Block Subdivision (OR-Tools)
- Constraint programming for optimal lot widths
- Minimizes deviation from target width
- Respects min/max constraints
- Classifies blocks as residential or parks

## Example GeoJSON

```json
{
  "type": "Polygon",
  "coordinates": [
    [[0, 0], [100, 0], [100, 100], [0, 100], [0, 0]]
  ],
  "properties": {"name": "Sample Plot"}
}
```

## Dependencies

### Backend
- FastAPI 0.104.1
- Shapely 2.0.2
- DEAP 1.4.1 (genetic algorithms)
- OR-Tools 9.8.3296 (constraint programming)
- NumPy 1.26.2

### Frontend
- Streamlit 1.29.0
- Plotly 5.18.0 (interactive charts)
- Requests 2.31.0

## Development

To modify the algorithm logic, edit `backend/algorithm.py`. The implementation is designed to match the notebook exactly.

## Troubleshooting

**Backend won't start**: Make sure port 8000 is not in use
```bash
lsof -i :8000
```

**Frontend can't connect**: Verify backend is running and API_URL is correct

**Optimization takes too long**: Reduce `generations` or `population_size` in the configuration

## License

MIT