Initial simplification

This commit is contained in:
Guille Gutierrez 2023-01-23 12:29:41 -05:00
parent fda986dc87
commit d4e444e3e7
8 changed files with 38 additions and 228 deletions

View File

@ -1,2 +1,4 @@
# Gamification Service
# CERC API
Services

View File

@ -5,37 +5,28 @@ Copyright © 2021 Project Author name guillermo.gutierrezmorote@concordia.ca
Project Collaborator name peteryefi@gmail.com
"""
import datetime
import flask
import yaml
from flasgger import LazyJSONEncoder, Swagger
from flask import Response, jsonify
from flask_restful import Api
from hub_api.city_info import CityInfo, City
from hub_api.geometry import Geometry
from hub_api.greenery_catalog import GreeneryCatalogEntries
from hub_api.greenery_catalog import GreeneryCatalogEntry
from hub_api.greenery_catalog import GreeneryCatalogNames
from hub_api.construction_catalog import ConstructionCatalogEntries
from hub_api.construction_catalog import ConstructionCatalogEntry
from hub_api.construction_catalog import ConstructionCatalogNames
from hub_api.usage_catalog import UsageCatalogEntries
from hub_api.usage_catalog import UsageCatalogEntry
from hub_api.usage_catalog import UsageCatalogNames
from hub_api.heat_pump import HeatPump
from hub_api.lca import MaterialLCACatalog
from hub_api.lca import MaterialLCACalculations
from hub_api.construction import Construction
from hub_api.usage import Usage
from hub_api.energy_demand import EnergyDemand
from flask_swagger import swagger
import hub_api.helpers.session_helper as sh
from hub_api.construction_catalog import ConstructionCatalogEntry, ConstructionCatalogEntries, ConstructionCatalogNames
from hub_api.greenery_catalog import GreeneryCatalogEntry, GreeneryCatalogEntries, GreeneryCatalogNames
from hub_api.session import SessionStart, SessionEnd, KeepSessionAlive
from hub_api.uptime import Uptime
from hub_api.greenery import Greenery
from hub_api.usage_catalog import UsageCatalogEntry, UsageCatalogEntries, UsageCatalogNames
from hub_api.user import User, UserLogin
from flasgger import LazyJSONEncoder, Swagger
app = flask.Flask('gamification')
app.json_encoder = LazyJSONEncoder
sh.begin_time = datetime.datetime.now()
app = flask.Flask('cerc_api')
app.json_provider_class = LazyJSONEncoder
api = Api(app)
with open("hub_api/docs/openapi-specs.yml", "r") as stream:
swagger_config = {
"headers": [],
@ -52,33 +43,37 @@ with open("hub_api/docs/openapi-specs.yml", "r") as stream:
"openapi": "3.0.0"
}
try:
Swagger(app, template=yaml.safe_load(stream), config=swagger_config)
sh.swagger_data = Swagger(app, template=yaml.safe_load(stream), config=swagger_config)
except yaml.YAMLError as exc:
print(exc)
api.add_resource(Uptime, '/v1.4/uptime')
api.add_resource(Geometry, '/v1.4/geometry')
# Catalogs.
api.add_resource(GreeneryCatalogEntry, '/v1.4/greenery-catalog/entry')
api.add_resource(GreeneryCatalogEntries, '/v1.4/greenery-catalog/entries')
api.add_resource(GreeneryCatalogNames, '/v1.4/greenery-catalog/names')
api.add_resource(ConstructionCatalogEntry, '/v1.4/construction-catalog/entry')
api.add_resource(ConstructionCatalogEntries, '/v1.4/construction-catalog/entries')
api.add_resource(ConstructionCatalogNames, '/v1.4/construction-catalog/names')
api.add_resource(Construction, '/v1.4/construction/<int:city_id>')
api.add_resource(UsageCatalogEntry, '/v1.4/usage-catalog/entry')
api.add_resource(UsageCatalogEntries, '/v1.4/usage-catalog/entries')
api.add_resource(UsageCatalogNames, '/v1.4/usage-catalog/names')
api.add_resource(Usage, '/v1.4/usage')
api.add_resource(EnergyDemand, '/v1.4/energy-demand/<int:city_id>')
# api.add_resource(LCA, '/v1.4/lca')
api.add_resource(MaterialLCACatalog, '/v1.4/material_lca_catalog/entries/<int:city_id>')
api.add_resource(MaterialLCACalculations, '/v1.4/material_lca_catalog/calculations/<int:city_id>')
api.add_resource(HeatPump, '/v1.4/heat-pump/<int:city_id>')
# Session
api.add_resource(User, '/v1.4/user')
api.add_resource(UserLogin, '/v1.4/user/login')
api.add_resource(SessionStart, '/v1.4/session/start')
api.add_resource(SessionEnd, '/v1.4/session/end')
api.add_resource(KeepSessionAlive, '/v1.4/session/keep_alive')
api.add_resource(CityInfo, '/v1.4/city/<int:city_id>')
api.add_resource(City, '/v1.4/city')
api.add_resource(Greenery, '/v1.4/greenery')
@app.route("/v1.4/spec")
def spec():
return jsonify(sh.swagger_data.config)
@app.route("/")
def home():
return Response(headers={'Access-Control-Allow-Origin': '*'})
app.run(port=15789, host="0.0.0.0", debug=True)

View File

@ -1,62 +0,0 @@
"""
Main
SPDX - License - Identifier: LGPL - 3.0 - or -later
Copyright © 2021 Project Author name guillermo.gutierrezmorote@concordia.ca
Project Collaborator name peteryefi@gmail.com
"""
from catalog_factories.construction_catalog_factory import ConstructionCatalogFactory
from catalog_factories.greenery_catalog_factory import GreeneryCatalogFactory
from catalog_factories.usage_catalog_factory import UsageCatalogFactory
from imports.construction_factory import ConstructionFactory
from imports.geometry_factory import GeometryFactory
from imports.life_cycle_assessment_factory import LifeCycleAssessment
# from imports.schedules_factory import SchedulesFactory
from imports.usage_factory import UsageFactory
from imports.weather_factory import WeatherFactory
from flask import Response
import hub_api.helpers.session_helper as sh
import datetime
from pathlib import Path
from bootstrap import app
sh.begin_time = datetime.datetime.now()
# initialize catalogs
sh.greenery_catalog = GreeneryCatalogFactory('nrel').catalog
sh.construction_catalog = ConstructionCatalogFactory('nrel').catalog
sh.usage_catalog = UsageCatalogFactory('comnet').catalog
# Enrich the city
data_path = (Path(__file__).parent / 'data').resolve()
rihno_path = (Path(data_path / 'dompark.3dm')).resolve()
city = GeometryFactory('rhino', rihno_path).city
for building in city.buildings:
# Rihno files have no information about the function or the year of construction
building.year_of_construction = 1995
building.function = 'industry'
building.human_readable_name = "Dompark"
ConstructionFactory('nrel', city).enrich()
UsageFactory('comnet', city).enrich()
# SchedulesFactory('comnet', city).enrich()
LifeCycleAssessment('material', city).enrich()
LifeCycleAssessment('machine', city).enrich()
LifeCycleAssessment('fuel', city).enrich()
LifeCycleAssessment('vehicle', city).enrich()
montreal_weather_file = (Path(__file__).parent / './data/CAN_PQ_Montreal.Intl.AP.716270_CWEC.epw').resolve()
city.climate_file = (data_path / f'{city.climate_reference_city}.cli').resolve()
WeatherFactory('epw', city, file_name=montreal_weather_file).enrich()
# Rihno files have no information about the building location
city.name = 'Montreal'
city.climate_reference_city = 'Montreal'
@app.route("/")
def home():
return Response(headers={'Access-Control-Allow-Origin': '*'})
app.run(port=15789, host="0.0.0.0", debug=False)

View File

@ -1,6 +1,6 @@
info:
title: Gamification Swagger - OpenAPI 3.0
description: NextGen Cities Institute Gamification API
title: CERC API Swagger - OpenAPI 3.0
description: NextGen Cities Institute API
termsOfService: http://swagger.io/terms/
contact:
email: peteryefi@gmail.com

0
hub_api/docs/uptime.yml Normal file
View File

View File

@ -8,6 +8,7 @@ import datetime
sessions = []
begin_time = None
swagger_data = None
city = None
greenery_catalog = None
construction_catalog = None

View File

@ -1,128 +0,0 @@
"""
LCA
SPDX - License - Identifier: LGPL - 3.0 - or -later
Copyright © 2021 Project Author name Atiya
Code contributors: Peter Yefi peteryefi@gmail.com
"""
import json
from flask import Response
from flask_restful import Resource
from lca_calculations import LcaCalculations
from itertools import groupby
from operator import itemgetter
from hub_api.helpers.auth import role_required
from hub_api.config import Config
from persistence.models import UserRoles
class MaterialLCACatalog(Resource, Config):
def __init__(self):
super().__init__()
@staticmethod
def get_lca_value(city, nrel_id = None):
nrel_material = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "14", "15", "16", "18", "20", "21",
"22", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114"]
lca_material = ["12", "32", "21", "25", "11", "20", "40", "27", "29", "28", "19", "40", "41", "25", "32", "32", "32", "21", "41",
"21", "11", "33", "28", "11", "40", "1", "28", "41", "0", "0", "0", "0", "0", ]
keys = ['nrel_material_id', 'lca_material_id']
material_mapping = [dict(zip(keys, i)) for i in zip(nrel_material, lca_material)]
if nrel_id is None:
materials_lca = {"material_lca_catalog": []}
for mat in material_mapping:
if mat["nrel_material_id"] not in ("110", "111", "112", "113", "114"):
for material in city.lca_materials:
if(int(mat["lca_material_id"]) == material.id):
material_lca_catalog = {}
material_lca_catalog['nrel_material_id'] = mat["nrel_material_id"]
material_lca_catalog['embodied_carbon'] = material.embodied_carbon
mat_end_of_life = LcaCalculations(city).end_life_carbon(material.type)
material_lca_catalog['end_of_life_carbon'] = mat_end_of_life
materials_lca["material_lca_catalog"].append(material_lca_catalog)
else:
material_lca_catalog = {}
material_lca_catalog['nrel_material_id'] = mat["nrel_material_id"]
material_lca_catalog['embodied_carbon'] = 0.0
material_lca_catalog['end_of_life_carbon'] = 0.0
materials_lca["material_lca_catalog"].append(material_lca_catalog)
return materials_lca
else:
for mat in material_mapping:
if mat["nrel_material_id"] == str(nrel_id):
for material in city.lca_materials:
if (material.id == int(mat["lca_material_id"])):
return material.embodied_carbon, material.id, material.type, material.name, material.density
# return material.embodied_carbon
@role_required([UserRoles.Admin.value, UserRoles.Hub_Reader.value])
def get(self, city_id):
city = self.get_city(city_id)
try:
return Response(json.dumps(self.get_lca_value(city)), status=200)
except ValueError:
response = {'err_msg': f'No Catalog Available'}
return Response(json.dumps(response), status=400)
class MaterialLCACalculations(Resource, Config):
"""
LCA class
"""
def __init__(self):
super().__init__()
@role_required([UserRoles.Admin.value, UserRoles.Hub_Reader.value])
def get(self, city_id):
"""
Auto-method for processing the lca request
:return: lca demand
"""
city = self.get_city(city_id)
materials_lca = {'Wall': [], 'Ground': [], 'Roof': []}
for building in city.buildings:
for internal_zone in building.internal_zones:
for thermal_zone in internal_zone.thermal_zones:
for thermal_boundary in thermal_zone.thermal_boundaries:
for i, layer in enumerate(thermal_boundary.layers):
material_layers_lca = {}
if layer.material.no_mass == False:
embodied_carbon, mat_id, mat_type, mat_name, mat_density = MaterialLCACatalog.get_lca_value(city, layer.material.id)
material_layers_lca['layer_name'] = f'Layer {i+1}'
material_layers_lca['nrel_material_id'] = layer.material.id
material_layers_lca['lca_material_id'] = mat_id
material_layers_lca['embodied_carbon'] = (layer.thickness * thermal_boundary.opaque_area) * mat_density * embodied_carbon
mat_end_of_life = LcaCalculations(city).end_life_carbon(mat_type)
material_end_of_life = mat_end_of_life * (layer.thickness * thermal_boundary.opaque_area) * mat_density
material_layers_lca['end_of_life_per_layer'] = material_end_of_life
materials_lca[thermal_boundary.type].append(material_layers_lca)
else:
material_layers_lca['layer_name'] = f'Layer {i+1}'
material_layers_lca['nrel_material_id'] = layer.material.id
material_layers_lca['lca_material_id'] = mat_id
material_layers_lca['embodied_carbon'] = (layer.thickness * thermal_boundary.opaque_area) * mat_density * embodied_carbon
material_layers_lca['end_of_life_per_layer'] = 0.0
materials_lca[thermal_boundary.type].append(material_layers_lca)
materials_embodied_carbon = {'Wall': [], 'Ground': [], 'Roof': []}
for key, value in materials_lca.items():
boundary_layers = sorted(value, key=itemgetter('layer_name'))
for b_layer, layer_properties in groupby(boundary_layers, key=itemgetter('layer_name')):
sum_embodied = 0.0
sum_end_of_life = 0.0
total_embodied_carbon = {}
for k in layer_properties:
sum_embodied += k["embodied_carbon"]
sum_end_of_life += k["end_of_life_per_layer"]
total_embodied_carbon['layer_name'] = b_layer
total_embodied_carbon['embodied_carbon'] = sum_embodied
total_embodied_carbon['end_of_life_carbon'] = sum_end_of_life
materials_embodied_carbon[key].append(total_embodied_carbon)
return Response(json.dumps(materials_embodied_carbon), status=200)

View File

@ -6,12 +6,14 @@ Copyright © 2022 Project Author name guillermo.gutierrezmorote@concordia.ca
import datetime
import json
from flasgger import swag_from
from flask import Response
from flask_restful import Resource
import hub_api.helpers.session_helper as sh
@swag_from('docs/uptime.yml')
class Uptime(Resource):
def __init__(self):
pass