« Consommation des avions » : différence entre les versions

De ESCR
Aller à la navigation Aller à la recherche
Aucun résumé des modifications
Aucun résumé des modifications
 
Ligne 156 : Ligne 156 :
== Démonstration ==
== Démonstration ==
[[Fichier:MALTI results screenshot.png|center|results|width=50]]
[[Fichier:MALTI results screenshot.png|center|results|width=50]]
Code python de cette vue :
<syntaxhighlight lang="python">
from flask import Flask, render_template, request
from SPARQLWrapper import SPARQLWrapper, JSON
import pandas as pd
import plotly as py
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
from base64 import b64encode
import matplotlib.pyplot as plt
import os
app = Flask(__name__)
app.static_folder = 'static'
########################################
## this function retrieves the airplanes
## data from wikidata, through SPARQL
########################################
def get_results():
sparql = SPARQLWrapper("https://query.wikidata.org/sparql",
  agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11")
sparql.setQuery("""
    PREFIX bd: <http://www.bigdata.com/rdf#>
PREFIX wikibase: <http://wikiba.se/ontology#>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX wd: <http://www.wikidata.org/entity/>
select  ?avion ?avionLabel ?countryLabel ?firstFlightDate ?eventsLabel ?avionDescription ?image
where {
    ?avion wdt:P31 wd:Q11436.
#          wd:Q478798 wd:Q11436.
    ?avion wdt:P17 ?country.
#    ?avion wdt:P580 ?events.
          optional {
            ?avion wdt:P18 ?image.
            ?avion wdt:P793 ?events.
            ?avion wdt:P606 ?firstFlightDate.
          }
          # Doc : https://www.mediawiki.org/wiki/Wikidata_query_service/User_Manual#Label_service
# SELECT ?variableLabel ?variableAltLabel  ?variableDescription
SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en,fr" .
}
}
LIMIT 1000""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
results = results["results"]["bindings"]
return results
#################################################################
## aggregates the data to get produced airpalnes count by country
#################################################################
def get_counts():
results = get_results()
columns = ["avion", "avionLabel", "countryLabel", "firstFlightDate", "eventsLabel", "avionDescription", "image"]
data = pd.DataFrame(columns=columns, index=range(len(results)))
for i, result in enumerate(results):
for col in columns:
if col in result.keys():
data.loc[i, col] = result[col]['value']
agg_data = data.groupby(["countryLabel"]).size().reset_index(name='count').sort_values(['count'], ascending=False)
return data, agg_data
##################
## draw the map ##
##################
def plot_map(image_name="produced_aircrafts_counts.png"):
raw_data, agg_data = get_counts()
data = dict(
type='choropleth',
colorscale='Jet',
locations=agg_data['countryLabel'],
locationmode="country names",
z=agg_data['count'],
text=agg_data['countryLabel'],
colorbar={'title': 'produced airplanes'},
)
layout = dict(
title='number of aircraft produced per country',
geo=dict(showframe=False, projection={'type': 'mercator'})
)
chmap = go.Figure(data=[data], layout=layout)
chmap.to_image(format="png", engine="kaleido")
chmap.write_image(image_name)
return raw_data, agg_data
###########################################
###########    MAIN FUNCTION    ###########
###########################################
@app.route("/")
def home():
image_name = "produced_aircrafts_counts.png"
data, agg_data = plot_map("static/photos/"+image_name)
data = data.drop(["image"], axis=1)
# return render_template("index.html", l={"map": plot_map()})
return render_template("index.html", data=agg_data, image_name = image_name, results_count= len(data),
  agg_tables=[agg_data.to_html(classes='data')], agg_titles=agg_data.columns.values,
  data_tables=[data.to_html(classes='data')], data_titles=data.columns.values)
</syntaxhighlight >

Version actuelle datée du 21 juin 2021 à 05:47

Cette page sert à afficher le nombre d'avions produits par chaque pays.

Objectif

Aujourd'hui, les constructeurs d'avions ne cessent de produire de nouveaux types d'avions (Boeing,Airbus ...), ces derniers peuvent varier selon la taille, le but (commercial, indistruel ...) et leur consommations. Cependant, cela impacte notre environnement écologique.

Le but principal de cette application est de montrer les pays qui ont produis le plus d'avions.

Définition de votre graphe de connaissances

Schema

Diagramme de classes ou modèle RDF (comme vue en cours)

Schéma RDF

Vocabulaire

Base

BASE <https://data.escr.fr/wiki/Consommation_des_avions#>

Préfixes

PREFIX ex: <http://www.example.org/>
PREFIX bd: <http://www.bigdata.com/rdf#> 
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX wikibase: <http://wikiba.se/ontology#> 
PREFIX wdt: <http://www.wikidata.org/prop/direct/> 
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
prefix xsd: <http://www.w3.org/2001/XMLSchema#>

Classes

Aircraft
<Aircraft> rdf:type rdfs:Class .
Airplane
<Airplane> rdf:type rdfs:Class .
<Airplane> rdfs:subClassOf <Aircraft>.
Engine
<Engine> rdf:type rdfs:Class .
<Engine> rdfs:subClassOf <Airplane>.

Propriétés

country
<country> rdf:type rdf:Property.
  • Cette propriété définit le pays de fabrication de l'avion.
poweredBy
<poweredBy> rdf:type rdf:Property;
            rdfs:domain <Engine>.
  • Cette propriété définit le moteur de l'avion.
consumption
<consumption> rdf:type rdf:Property.
  • Cette propriété définit la consommation du moteur de l'avion.

Exemple d'un jeu de données

wd:Q2107964 <consumption> "22.1"^^xsd:decimal .

Requêtes

https://linkedwiki.com/query/List_of_airplains_Demo A retester lundi :

BASE <https://data.escr.fr/wiki/Consommation_des_avions#>

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> 
PREFIX bd: <http://www.bigdata.com/rdf#> 
PREFIX wikibase: <http://wikiba.se/ontology#> 
PREFIX wdt: <http://www.wikidata.org/prop/direct/> 
PREFIX wd: <http://www.wikidata.org/entity/>

select ?avion  ?imageAvion ?imageMotor 
		?avionLabel ?countryLabel ?avionDescription
where {
  ?motor <consumption> ?consommation .
  
    SERVICE <https://query.wikidata.org/sparql> {
       ?avion wdt:P31/wdt:P279* wd:Q15056993 ;
              wdt:P516 ?motor .
      
      OPTIONAL {
			?avion rdfs:label ?avionLabel .
        	FILTER (langMatches(lang(?avionLabel), "en"))	
      }
      OPTIONAL {
			?avion rdfs:label ?avionDescription .
        	FILTER (langMatches(lang(?avionDescription), "en"))	
      }

      OPTIONAL {
			?avion wdt:P18 ?imageAvion .
        }
      OPTIONAL {
			?avion wdt:P495 ?country .
			?country rdfs:label ?countryLabel .
        	FILTER (langMatches(lang(?countryLabel), "en"))	
        }
      OPTIONAL {
        	?motor  wdt:P176 ?manufacturer  .
        }
        OPTIONAL {
	  		?motor  wdt:P18 ?imageMotor .
        }
    }
} 
LIMIT 100
# colstyle=col1_img_max-width:150px;col2_img_max-width:150px

Vérification que le vocabulaire est bien chargé :

Démonstration

width=50

Code python de cette vue :

from flask import Flask, render_template, request
from SPARQLWrapper import SPARQLWrapper, JSON
import pandas as pd
import plotly as py
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
from base64 import b64encode
import matplotlib.pyplot as plt
import os


app = Flask(__name__)
app.static_folder = 'static'


########################################
## this function retrieves the airplanes 
## data from wikidata, through SPARQL
########################################
def get_results():
	sparql = SPARQLWrapper("https://query.wikidata.org/sparql",
						   agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11")

	sparql.setQuery("""
	    PREFIX bd: <http://www.bigdata.com/rdf#> 
	PREFIX wikibase: <http://wikiba.se/ontology#> 
	PREFIX wdt: <http://www.wikidata.org/prop/direct/> 
	PREFIX wd: <http://www.wikidata.org/entity/>

	select  ?avion ?avionLabel ?countryLabel ?firstFlightDate ?eventsLabel ?avionDescription ?image
	where {
	    ?avion wdt:P31 wd:Q11436.
	#           wd:Q478798 wd:Q11436.
	    ?avion wdt:P17 ?country.
	#    ?avion wdt:P580 ?events.
	           optional {
	             ?avion wdt:P18 ?image.
	             ?avion wdt:P793 ?events.
	             ?avion wdt:P606 ?firstFlightDate.
	           }
	           # Doc : https://www.mediawiki.org/wiki/Wikidata_query_service/User_Manual#Label_service
	# SELECT ?variableLabel ?variableAltLabel  ?variableDescription
	SERVICE wikibase:label {
	     bd:serviceParam wikibase:language "en,fr" .
	}
	} 
	LIMIT 1000""")

	sparql.setReturnFormat(JSON)
	results = sparql.query().convert()
	results = results["results"]["bindings"]

	return results


#################################################################
## aggregates the data to get produced airpalnes count by country
#################################################################
def get_counts():
	results = get_results()
	columns = ["avion", "avionLabel", "countryLabel", "firstFlightDate", "eventsLabel", "avionDescription", "image"]
	data = pd.DataFrame(columns=columns, index=range(len(results)))

	for i, result in enumerate(results):
		for col in columns:
			if col in result.keys():
				data.loc[i, col] = result[col]['value']

	agg_data = data.groupby(["countryLabel"]).size().reset_index(name='count').sort_values(['count'], ascending=False)
	return data, agg_data



##################
## draw the map ##
##################
def plot_map(image_name="produced_aircrafts_counts.png"):
	raw_data, agg_data = get_counts()
	data = dict(
		type='choropleth',
		colorscale='Jet',
		locations=agg_data['countryLabel'],
		locationmode="country names",
		z=agg_data['count'],
		text=agg_data['countryLabel'],
		colorbar={'title': 'produced airplanes'},
	)

	layout = dict(
		title='number of aircraft produced per country',
		geo=dict(showframe=False, projection={'type': 'mercator'})
	)
	chmap = go.Figure(data=[data], layout=layout)
	chmap.to_image(format="png", engine="kaleido")
	chmap.write_image(image_name)

	return raw_data, agg_data



###########################################
###########    MAIN FUNCTION    ###########
###########################################
@app.route("/")
def home():
	image_name = "produced_aircrafts_counts.png"
	data, agg_data = plot_map("static/photos/"+image_name)
	data = data.drop(["image"], axis=1)

	# return render_template("index.html", l={"map": plot_map()})
	return render_template("index.html", data=agg_data, image_name = image_name, results_count= len(data),
						   agg_tables=[agg_data.to_html(classes='data')], agg_titles=agg_data.columns.values,
						   data_tables=[data.to_html(classes='data')], data_titles=data.columns.values)