Skip to content

Commit efa6569

Browse files
committed
Ajoute exemple barycentres
1 parent ffe71a5 commit efa6569

File tree

1 file changed

+201
-8
lines changed

1 file changed

+201
-8
lines changed

content/manipulation/04c_API_TP.qmd

Lines changed: 201 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -135,16 +135,21 @@ An API is intended to serve as an intermediary between a client and a server. Th
135135
The first mode (access via a browser) is primarily used when a web interface allows a user to make choices in order to return results corresponding to those selections. Let’s revisit the example of the geolocation API that we will use in this chapter. Imagine a web interface that offers the user two choices: a postal code and an address. These inputs will be injected into the query, and the server will respond with the appropriate geolocation.
136136
:::
137137

138-
::::: {.content-visible when-format="ipynb"}
139138

140-
:::: {.content-visible when-profile="fr"}
139+
::::: {.content-visible when-profile="fr"}
140+
141+
:::: {.content-visible when-format="ipynb"}
141142

142143
::: {.important}
143144
Une explication interactive est disponible sur [le site du cours](https://pythonds.linogaliana.fr/content/manipulation/04c_API_TP.html).
144145
:::
145146

146147
::::
147148

149+
:::::
150+
151+
::::: {.content-visible when-format="ipynb"}
152+
148153
:::: {.content-visible when-profile="en"}
149154

150155
::: {.important}
@@ -153,7 +158,7 @@ An interactive explanation is available on [the course website](https://pythonds
153158

154159
::::
155160

156-
::::
161+
:::::
157162

158163
:::: {.content-visible when-format="html"}
159164

@@ -236,6 +241,7 @@ Si on veut un beau rendu, comme la carte ci-dessus, il faudra que le navigateur
236241
If a beautiful display is desired, like the map above, the web browser will need to reprocess this output, which is typically done using `Javascript`, the programming language embedded in web browsers.
237242
:::
238243

244+
::::
239245

240246
::: {.content-visible when-profile="fr"}
241247
## Comment faire avec `Python` ?
@@ -1386,15 +1392,15 @@ One of the objectives of the [3rd-year production deployment course](https://ens
13861392
# Exercices supplémentaires
13871393

13881394
::: {.exercise}
1389-
## Exercice bonus
1395+
## Exercice bonus 1: et si on ajoutait des informations sur la valeur ajoutée des lycées ?
13901396

13911397
Dans notre exemple sur les écoles, se restreindre aux lycées et ajouter les informations sur la valeur ajoutée des lycées disponibles [ici](https://data.education.gouv.fr/explore/dataset/fr-en-indicateurs-de-resultat-des-lycees-denseignement-general-et-technologique/table/?sort=-annee).
13921398
:::
13931399

13941400
::::
13951401

13961402
:::: {.content-visible when-profile="en"}
1397-
# Additional Exercises
1403+
# Additional Exercises: et si on ajoutait des informations sur la valeur ajoutée des lycées ?
13981404

13991405
::: {.exercise}
14001406
## Bonus Exercise
@@ -1404,14 +1410,201 @@ In our example on schools, limit the scope to high schools and add information o
14041410

14051411
::::
14061412

1413+
:::: {.content-visible when-profile="fr"}
1414+
1415+
::: {.exercise}
1416+
## Exercice bonus 2: on sort où ce soir ?
1417+
1418+
Trouver un lieu commun où se retrouver entre amis est toujours l'objet d'âpres négociations: et si on laissait guider par la géographie ?
1419+
1420+
1. Créer un `DataFrame` enregistrant une série d'adresses et de codes postaux comme l'exemple ci-dessous
1421+
2. Adapter le code de l'exercice sur l'API BAN, avec l'appui de la documentation, pour géolocaliser ces adresses
1422+
3. En supposant que vos données géolocalisées se nomment `adresses_geocoded`, utiliser le code proposé pour transformer celles-ci en polygone
1423+
4. Calculer le centroid et représenter sur une carte interactive `Folium` comme précédemment
1424+
1425+
Vous aviez oublié qu'il y avait un couple dans le groupe... Tenir compte de la variable `poids` pour calculer le barycentre et trouver où vous retrouver ce soir.
1426+
1427+
<details>
1428+
1429+
<summary>
1430+
Créer le polygone à partir des géolocalisations
1431+
</summary>
1432+
1433+
```{.python}
1434+
from shapely.geometry import Polygon
1435+
coordinates = list(zip(adresses_geocoded['longitude'], adresses_geocoded['latitude']))
1436+
polygon = Polygon(coordinates)
1437+
1438+
polygon = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[polygon])
1439+
polygon
1440+
```
1441+
</details>
1442+
1443+
:::
1444+
1445+
::::
1446+
1447+
:::: {.content-visible when-profile="en"}
1448+
1449+
::: {.exercise}
1450+
## Bonus Exercise 2: Where are we going out tonight?
1451+
1452+
Finding a common place to meet friends is always a subject of tough negotiations. What if we let geography guide us?
14071453

1454+
1. Create a `DataFrame` recording a series of addresses and postal codes, like the example below.
1455+
2. Adapt the code from the exercise on the BAN API, using its documentation, to geolocate these addresses.
1456+
3. Assuming your geolocated data is named `adresses_geocoded`, use the proposed code to transform them into a polygon.
1457+
4. Calculate the centroid and display it on an interactive `Folium` map as before.
14081458

1459+
You forgot there’s a couple in the group... Take into account the `poids` variable to calculate the barycenter and find out where to meet tonight.
14091460

1461+
<details>
1462+
<summary>
1463+
Create the polygon from the geolocations
1464+
</summary>
1465+
```{.python}
1466+
from shapely.geometry import Polygon
1467+
coordinates = list(zip(adresses_geocoded['longitude'], adresses_geocoded['latitude']))
1468+
polygon = Polygon(coordinates)
1469+
1470+
polygon = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[polygon])
1471+
polygon
1472+
```
1473+
</details>
1474+
1475+
:::
1476+
1477+
::::
14101478

1479+
::: {.content-visible when-profile="fr"}
1480+
Le DataFrame d'exemple:
1481+
:::
1482+
1483+
::: {.content-visible when-profile="en"}
1484+
The example DataFrame:
1485+
:::
1486+
1487+
```{python}
1488+
#| echo: true
1489+
adresses_text = pd.DataFrame(
1490+
{
1491+
"adresse": [
1492+
"10 Rue de Rivoli",
1493+
"15 Boulevard Saint-Michel",
1494+
"8 Rue Saint-Honoré",
1495+
"20 Avenue des Champs-Élysées",
1496+
"Place de la Bastille",
1497+
],
1498+
"cp": ["75004", "75005", "75001", "75008", "75011"],
1499+
"poids": [2, 1, 1, 1, 1]
1500+
})
1501+
adresses_text
1502+
```
1503+
1504+
```{python}
1505+
import pathlib
1506+
output_path = pathlib.Path("data/output")
1507+
output_path.mkdir(parents=True, exist_ok=True)
1508+
csv_file = output_path / "bpe_before_geoloc.csv"
1509+
1510+
adresses_text.loc[:, ["adresse", "poids", "cp"]].to_csv(csv_file, index=False)
1511+
1512+
params = {
1513+
"columns": ["adresse"],
1514+
"postcode": "cp",
1515+
"result_columns": ["result_score", "latitude", "longitude"],
1516+
}
1517+
1518+
response = requests.post(
1519+
"https://api-adresse.data.gouv.fr/search/csv/",
1520+
data=params,
1521+
files={"data": open(csv_file, "rb")},
1522+
)
1523+
```
1524+
1525+
```{python}
1526+
adresses_geocoded = pd.read_csv(io.StringIO(response.text))
1527+
adresses_geocoded
1528+
```
1529+
1530+
::: {.content-visible when-profile="fr"}
1531+
La géolocalisation obtenue pour cet exemple
1532+
:::
1533+
1534+
::: {.content-visible when-profile="en"}
1535+
The geolocation obtained for this example
1536+
:::
1537+
1538+
1539+
```{python}
1540+
from shapely.geometry import Polygon
1541+
coordinates = list(zip(adresses_geocoded['longitude'], adresses_geocoded['latitude']))
1542+
polygon = Polygon(coordinates)
1543+
1544+
polygon = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[polygon])
1545+
```
1546+
1547+
```{python}
1548+
#| output: false
1549+
import folium
1550+
1551+
gdf_points = gpd.GeoDataFrame(
1552+
adresses_geocoded,
1553+
geometry=gpd.points_from_xy(adresses_geocoded.longitude, adresses_geocoded.latitude), crs="EPSG:4326"
1554+
)
1555+
1556+
total_weight = adresses_geocoded['poids'].sum()
1557+
barycenter_x = (adresses_geocoded['longitude'] * adresses_geocoded['poids']).sum() / total_weight
1558+
barycenter_y = (adresses_geocoded['latitude'] * adresses_geocoded['poids']).sum() / total_weight
1559+
1560+
# Affichage des coordonnées du barycentre
1561+
barycenter = (barycenter_x, barycenter_y)
1562+
barycenter
1563+
1564+
# Calculate the centroid of the polygon
1565+
polygon_centroid = polygon.centroid
1566+
1567+
# Initialize a Folium map centered on the centroid
1568+
map_center = [polygon_centroid.y, polygon_centroid.x]
1569+
m = folium.Map(location=map_center, zoom_start=13)
1570+
1571+
# Add the polygon to the map
1572+
folium.GeoJson(polygon, name="Polygon").add_to(m)
1573+
1574+
# Add the points to the map
1575+
for _, row in gdf_points.iterrows():
1576+
folium.Marker(
1577+
location=[row.geometry.y, row.geometry.x],
1578+
popup=row['adresse'],
1579+
).add_to(m)
1580+
1581+
# Add the centroid in red
1582+
folium.Marker(
1583+
location=[barycenter_y, barycenter_x],
1584+
popup="Barycentre",
1585+
icon=folium.Icon(color="red")
1586+
).add_to(m)
1587+
1588+
# Met à jour le centroïde pour qu'il soit vert
1589+
folium.Marker(
1590+
location=[polygon.centroid.y, polygon.centroid.x],
1591+
popup="Centroid",
1592+
icon=folium.Icon(color="green")
1593+
).add_to(m)
1594+
```
1595+
1596+
::: {.content-visible when-profile="fr"}
1597+
Voici la carte obtenue sur le jeu d'exemple. On sera peut-être plus au sec avec le barycentre qu'avec le centroid.
1598+
:::
1599+
1600+
::: {.content-visible when-profile="en"}
1601+
Here is the map obtained from the example dataset. We might stay drier with the barycenter than with the centroid.
1602+
:::
1603+
1604+
```{python}
1605+
m
1606+
```
14111607

1412-
<!--------
1413-
## Ouverture avec les API de code pour consommer des modèles (exemple avec hf)?
1414-
-------->
14151608

14161609
<!----------
14171610
API interactive example

0 commit comments

Comments
 (0)