From 4ab6cfb8bf491edfcc634932d8d6c38458e16b83 Mon Sep 17 00:00:00 2001
From: Phil Elson
Date: Thu, 26 Aug 2021 11:13:36 +0200
Subject: [PATCH] Refactor the weather data production, restoring as much of
the old test behaviour as possible to minimise the changes
---
README.md | 25 +--
cara/apps/calculator/model_generator.py | 35 ++-
cara/apps/calculator/static/js/form.js | 13 +-
.../templates/base/calculator.report.html.j2 | 6 +-
.../templates/calculator.form.html.j2 | 8 +-
cara/apps/expert.py | 4 +-
cara/data.py | 93 --------
cara/data/__init__.py | 51 +++++
cara/data/weather.py | 114 ++++++++++
.../apps/calculator/test_model_generator.py | 210 ++++++++----------
cara/tests/data/__init__.py | 0
cara/tests/data/test_weather.py | 11 +
cara/tests/models/test_piecewiseconstant.py | 2 +-
cara/tests/test_known_quantities.py | 131 ++++++-----
cara/tests/test_monte_carlo_full_models.py | 48 ++--
15 files changed, 410 insertions(+), 341 deletions(-)
delete mode 100644 cara/data.py
create mode 100644 cara/data/__init__.py
create mode 100644 cara/data/weather.py
create mode 100644 cara/tests/data/__init__.py
create mode 100644 cara/tests/data/test_weather.py
diff --git a/README.md b/README.md
index 1194fec3..7b3949b9 100644
--- a/README.md
+++ b/README.md
@@ -85,26 +85,20 @@ This will start a local version of CARA, which can be visited at http://localhos
## Development guide
-### Running the COVID calculator app in development mode
+The CARA repository makes use of Git's Large File Storage (LFS) feature.
+You will need a working installation of git-lfs in order to run CARA in development mode.
+See https://git-lfs.github.com/ for installation instructions.
-Download Git Large File Storage (LFS) - **macOS**:
+### Installing CARA in editable mode
```
-brew install git-LFS
-```
-
-Download Git Large File Storage (LFS) - **Linux**:
-
-```
-apt-get install git-lfs
-```
-
-Install dependencies:
-
-```
-git lfs install
git lfs pull # Fetch the data from LFS
pip install -e . # At the root of the repository
+```
+
+### Running the COVID calculator app in development mode
+
+```
python -m cara.apps.calculator
```
@@ -123,7 +117,6 @@ python -m cara.apps.calculator --prefix=/mycalc
### Running the CARA Expert-App app in development mode
```
-pip install -e . # At the root of the repository
voila cara/apps/expert/cara.ipynb --port=8080
```
diff --git a/cara/apps/calculator/model_generator.py b/cara/apps/calculator/model_generator.py
index 013756a6..69701a30 100644
--- a/cara/apps/calculator/model_generator.py
+++ b/cara/apps/calculator/model_generator.py
@@ -9,6 +9,7 @@ import numpy as np
from cara import models
from cara import data
+import cara.data.weather
import cara.monte_carlo as mc
from .. import calculator
from cara.monte_carlo.data import activity_distributions, virus_distributions
@@ -20,8 +21,6 @@ LOG = logging.getLogger(__name__)
minutes_since_midnight = typing.NewType('minutes_since_midnight', int)
-
-
# Used to declare when an attribute of a class must have a value provided, and
# there should be no default value used.
_NO_DEFAULT = object()
@@ -53,10 +52,9 @@ class FormData:
infected_lunch_start: minutes_since_midnight #Used if infected_dont_have_breaks_with_exposed
infected_people: int
infected_start: minutes_since_midnight
- location: str
- location_coordinates: str
- weather_station_location: str
- weather_station_ref: str
+ location_name: str
+ location_latitude: float
+ location_longitude: float
mask_type: str
mask_wearing_option: str
mechanical_ventilation_type: str
@@ -107,10 +105,9 @@ class FormData:
'infected_lunch_start': '12:30',
'infected_people': _NO_DEFAULT,
'infected_start': '08:30',
- 'location': _NO_DEFAULT,
- 'location_coordinates': _NO_DEFAULT,
- 'weather_station_location':'GENEVA COINTRIN',
- 'weather_station_ref': '067000-99999',
+ 'location_latitude': 46.20833,
+ 'location_longitude': 6.14275,
+ 'location_name': 'Geneva',
'mask_type': 'Type I',
'mask_wearing_option': 'mask_off',
'mechanical_ventilation_type': 'not-applicable',
@@ -269,14 +266,12 @@ class FormData:
month = datetime_object.month
# set location
- self.weather_station_location = data.location_to_weather_stn(self.location_coordinates)[1]
- data.local_tempatures = data.location_celcius_per_hour(self.location_coordinates)
- print(data.local_tempatures)
+ wx_station = self.nearest_weather_station()
+ temp_profile = cara.data.weather.mean_hourly_temperatures(wx_station[0], month)
inside_temp = models.PiecewiseConstant((0, 24), (293,))
- outside_temp = data.Temperatures[str(month)]
-
-
+ # Interpolate the temperature to every 6 minutes (60/10).
+ outside_temp = cara.data.weather.hourly_to_piecewise(temp_profile).refine(10)
ventilation: models.Ventilation
if self.window_type == 'window_sliding':
@@ -318,6 +313,12 @@ class FormData:
else:
return models.MultipleVentilation((ventilation, infiltration_ventilation))
+ def nearest_weather_station(self) -> cara.data.weather.WxStationRecordType:
+ wx_station = cara.data.weather.nearest_wx_station(
+ longitude=self.location_longitude, latitude=self.location_latitude
+ )
+ return wx_station
+
def mask(self) -> models.Mask:
# Initializes the mask type if mask wearing is "continuous", otherwise instantiates the mask attribute as
# the "No mask"-mask
@@ -621,8 +622,6 @@ def baseline_raw_form_data():
'infected_lunch_start': '12:30',
'infected_people': '1',
'infected_start': '09:00',
- 'location': 'Geneva',
- 'location_coordinates': '46.2044, 6.1432',
'mask_type': 'Type I',
'mask_wearing_option': 'mask_off',
'mechanical_ventilation_type': '',
diff --git a/cara/apps/calculator/static/js/form.js b/cara/apps/calculator/static/js/form.js
index 40334e5b..70755549 100644
--- a/cara/apps/calculator/static/js/form.js
+++ b/cara/apps/calculator/static/js/form.js
@@ -566,8 +566,8 @@ $(document).ready(function() {
id: candidate.address,
text: candidate.address,
country: candidate.attributes.country,
- latitude: String(candidate.location.y),
- longitude: String(candidate.location.x),
+ latitude: candidate.location.y,
+ longitude: candidate.location.x,
}
}),
pagination: {
@@ -602,8 +602,13 @@ function formatlocation(location) {
}
function formatLocationSelection(location) {
- if (location.latitude != null && location.latitude != null)
- $(document.getElementById("coordinates_input").value = (location.latitude + ',' + location.longitude));
+ console.log(location);
+ if (location.latitude != null && location.latitude != null) {
+ console.log('setting!');
+ console.log($('input[name="location_latitude"]'));
+ $('input[name="location_latitude"]').val(location.latitude);
+ $('input[name="location_longitude"]').val(location.longitude);
+ }
return location.text;
}
diff --git a/cara/apps/calculator/templates/base/calculator.report.html.j2 b/cara/apps/calculator/templates/base/calculator.report.html.j2
index 46e397a0..781a241c 100644
--- a/cara/apps/calculator/templates/base/calculator.report.html.j2
+++ b/cara/apps/calculator/templates/base/calculator.report.html.j2
@@ -53,9 +53,9 @@
Room Volume: {{ model.concentration_model.room.volume }} m³
Room Central Heating: {{ "On" if form.room_heating_option else "Off" }}
- Geographic Location: {{ form.location }}
- {% if form.ventilation_type == "natural_ventilation"%}
- Nearest weather station: {{ form.weather_station_location }}
+ Geographic Location: {{ form.location_name }}
+ {% if form.ventilation_type == "natural_ventilation" %}
+ Nearest weather station: {{ form.nearest_weather_station()[1].strip().title() }}
{% endif %}
diff --git a/cara/apps/calculator/templates/calculator.form.html.j2 b/cara/apps/calculator/templates/calculator.form.html.j2
index b39a54d4..d5cb4bc1 100644
--- a/cara/apps/calculator/templates/calculator.form.html.j2
+++ b/cara/apps/calculator/templates/calculator.form.html.j2
@@ -107,11 +107,11 @@ v{{ calculator_version }} Please sen
-
-
-
-
+
+
+
+
diff --git a/cara/apps/expert.py b/cara/apps/expert.py
index 5a9273ef..664f97b3 100644
--- a/cara/apps/expert.py
+++ b/cara/apps/expert.py
@@ -360,10 +360,10 @@ class ModelWidgets(View):
def _build_month(self, node) -> WidgetGroup:
- month_choice = widgets.Select(options=list(data.Temperatures.keys()), value='1')
+ month_choice = widgets.Select(options=list(data.GenevaTemperatures.keys()), value='Jan')
def on_month_change(change):
- node.outside_temp = data.Temperatures[change['new']]
+ node.outside_temp = data.GenevaTemperatures[change['new']]
month_choice.observe(on_month_change, names=['value'])
return WidgetGroup(
diff --git a/cara/data.py b/cara/data.py
deleted file mode 100644
index 956a906a..00000000
--- a/cara/data.py
+++ /dev/null
@@ -1,93 +0,0 @@
-import numpy as np
-from cara import models
-import json
-import urllib.request
-from pathlib import Path
-from scipy.spatial import cKDTree
-import os
-import typing
-
-weather_debug = False
-
-
-def location_to_weather_stn(location_loc):
- # expects a tuple (lat, long)
- # returns: weather station ID, weather station name, weather station lat, long
- search_coords = location_loc.split(',')
- lat = []
- long = []
- station_array = []
- fixed_delimits = [0, 12, 13, 44, 51, 60, 69, 90, 91]
- station_file = Path(__file__).parent / 'data' / 'cara_weather_stations.txt'
-
- for line in station_file.open('rt'):
- start_end_positions = zip(fixed_delimits[:-1], fixed_delimits[1:])
- split_vals = [line[start:end] for start, end in start_end_positions]
- station_location = [split_vals[0],
- split_vals[2], split_vals[3], split_vals[4]]
- station_array.append(station_location)
- lat.append(split_vals[3])
- long.append(split_vals[4])
-
- tree = cKDTree(np.c_[lat, long])
- dd, ii = tree.query(search_coords, k=[1])
-
- return (station_array[ii[0]][0], station_array[ii[0]][1], station_array[ii[0]][2], station_array[ii[0]][3])
-
-
-def location_celcius_per_hour(location: object) -> typing.Dict[str, typing.List[float]]:
- # expects a tuple (lat, long)
- # returns a json format set of weather data
- w_station = location_to_weather_stn(location)
- with open(Path(__file__).parent / 'data' / 'global_weather_set.json', "r") as json_file:
- weather_dict = json.load(json_file)
- Location_hourly_temperatures_celsius_per_hour = weather_dict[w_station[0]]
- if weather_debug:
- print(location)
- print("weather station name: ", w_station[1])
- print("weather station ref: ", w_station[0])
- print("weather station location: ", w_station[2], " ", w_station[3])
- print(Location_hourly_temperatures_celsius_per_hour)
- return Location_hourly_temperatures_celsius_per_hour
-
-
-# initialise with Geneva, change if location is different.
-local_tempatures = {
- '1': [0.2, -0.3, -0.5, -0.9, -1.1, -1.4, -1.5, -1.5, -1.1, 0.1, 1.5,
- 2.8, 3.8, 4.4, 4.5, 4.4, 4.4, 3.9, 3.1, 2.7, 2.2, 1.7, 1.5, 1.1],
- '2': [0.9, 0.3, 0.0, -0.5, -0.7, -1.1, -1.2, -1.1, -0.7, 0.8, 2.5,
- 4.2, 5.4, 6.2, 6.3, 6.2, 6.1, 5.5, 4.5, 4.1, 3.5, 2.8, 2.5, 2.0],
- '3': [4.2, 3.5, 3.1, 2.5, 2.1, 1.6, 1.5, 1.6, 2.2, 4.0, 6.3, 8.4,
- 10.0, 11.1, 11.2, 11.1, 11.0, 10.2, 8.9, 8.3, 7.5, 6.7, 6.3, 5.6],
- '4': [7.4, 6.7, 6.2, 5.5, 5.2, 4.7, 4.5, 4.6, 5.3, 7.2, 9.6, 11.9,
- 13.7, 14.8, 14.9, 14.8, 14.7, 13.8, 12.4, 11.8, 10.9, 10.1, 9.6, 8.9],
- '5': [11.8, 11.1, 10.6, 9.9, 9.5, 8.9, 8.8, 8.9, 9.6, 11.6, 14.2, 16.6,
- 18.4, 19.6, 19.7, 19.6, 19.4, 18.6, 17.1, 16.5, 15.6, 14.6, 14.2, 13.4],
- '6': [15.2, 14.4, 13.9, 13.2, 12.7, 12.2, 12.0, 12.1, 12.8, 15.0, 17.7,
- 20.2, 22.1, 23.3, 23.5, 23.4, 23.2, 22.3, 20.8, 20.1, 19.1, 18.2, 17.7, 16.9],
- '7': [17.6, 16.7, 16.1, 15.3, 14.9, 14.3, 14.1, 14.2, 15.0, 17.3, 20.2,
- 23.0, 25.0, 26.3, 26.5, 26.4, 26.2, 25.2, 23.6, 22.8, 21.8, 20.8, 20.2, 19.4],
- '8': [17.1, 16.2, 15.7, 14.9, 14.5, 13.9, 13.7, 13.8, 14.6, 16.9, 19.7,
- 22.4, 24.4, 25.6, 25.8, 25.7, 25.5, 24.5, 22.9, 22.2, 21.2, 20.2, 19.7, 18.9],
- '9': [13.4, 12.7, 12.2, 11.5, 11.2, 10.7, 10.5, 10.6, 11.3, 13.2, 15.6,
- 17.9, 19.6, 20.8, 20.9, 20.8, 20.7, 19.8, 18.4, 17.8, 16.9, 16.1, 15.6, 14.9],
- '10': [9.4, 8.8, 8.5, 7.9, 7.6, 7.2, 7.1, 7.2, 7.7, 9.3, 11.2, 13.0,
- 14.4, 15.3, 15.4, 15.3, 15.2, 14.5, 13.4, 12.9, 12.2, 11.6, 11.2, 10.6],
- '11': [4.0, 3.6, 3.3, 2.9, 2.6, 2.3, 2.2, 2.2, 2.7, 3.9, 5.5, 6.9, 8.0,
- 8.7, 8.8, 8.7, 8.7, 8.1, 7.2, 6.8, 6.3, 5.7, 5.5, 5.0],
- '12': [1.4, 1.0, 0.8, 0.4, 0.2, -0.0, -0.1, -0.1, 0.3, 1.3, 2.6, 3.8,
- 4.7, 5.2, 5.3, 5.2, 5.2, 4.7, 4.0, 3.7, 3.2, 2.8, 2.6, 2.2]
-}
-
-
-# Geneva hourly temperatures as piecewise constant function (in Kelvin)
-Temperatures_hourly = {
- month: models.PiecewiseConstant(tuple(np.arange(25.)),
- tuple(273.15+np.array(temperatures)))
- for month, temperatures in local_tempatures.items()
-}
-# same temperatures on a finer temperature mesh
-Temperatures = {
- month: Temperatures_hourly[month].refine(refine_factor=10)
- for month, temperatures in local_tempatures.items()
-}
diff --git a/cara/data/__init__.py b/cara/data/__init__.py
new file mode 100644
index 00000000..353992e6
--- /dev/null
+++ b/cara/data/__init__.py
@@ -0,0 +1,51 @@
+import numpy as np
+from cara import models
+
+# TODO: The values in this module to be removed and instead use the cara.data.weather functionality.
+
+# average temperature of each month, hour per hour (from midnight to 11 pm)
+Geneva_hourly_temperatures_celsius_per_hour = {
+ 'Jan': [0.2, -0.3, -0.5, -0.9, -1.1, -1.4, -1.5, -1.5, -1.1, 0.1, 1.5,
+ 2.8, 3.8, 4.4, 4.5, 4.4, 4.4, 3.9, 3.1, 2.7, 2.2, 1.7, 1.5, 1.1],
+ 'Feb': [0.9, 0.3, 0.0, -0.5, -0.7, -1.1, -1.2, -1.1, -0.7, 0.8, 2.5,
+ 4.2, 5.4, 6.2, 6.3, 6.2, 6.1, 5.5, 4.5, 4.1, 3.5, 2.8, 2.5, 2.0],
+ 'Mar': [4.2, 3.5, 3.1, 2.5, 2.1, 1.6, 1.5, 1.6, 2.2, 4.0, 6.3, 8.4,
+ 10.0, 11.1, 11.2, 11.1, 11.0, 10.2, 8.9, 8.3, 7.5, 6.7, 6.3, 5.6],
+ 'Apr': [7.4, 6.7, 6.2, 5.5, 5.2, 4.7, 4.5, 4.6, 5.3, 7.2, 9.6, 11.9,
+ 13.7, 14.8, 14.9, 14.8, 14.7, 13.8, 12.4, 11.8, 10.9, 10.1, 9.6, 8.9],
+ 'May': [11.8, 11.1, 10.6, 9.9, 9.5, 8.9, 8.8, 8.9, 9.6, 11.6, 14.2, 16.6,
+ 18.4, 19.6, 19.7, 19.6, 19.4, 18.6, 17.1, 16.5, 15.6, 14.6, 14.2, 13.4],
+ 'Jun': [15.2, 14.4, 13.9, 13.2, 12.7, 12.2, 12.0, 12.1, 12.8, 15.0, 17.7,
+ 20.2, 22.1, 23.3, 23.5, 23.4, 23.2, 22.3, 20.8, 20.1, 19.1, 18.2, 17.7, 16.9],
+ 'Jul': [17.6, 16.7, 16.1, 15.3, 14.9, 14.3, 14.1, 14.2, 15.0, 17.3, 20.2,
+ 23.0, 25.0, 26.3, 26.5, 26.4, 26.2, 25.2, 23.6, 22.8, 21.8, 20.8, 20.2, 19.4],
+ 'Aug': [17.1, 16.2, 15.7, 14.9, 14.5, 13.9, 13.7, 13.8, 14.6, 16.9, 19.7,
+ 22.4, 24.4, 25.6, 25.8, 25.7, 25.5, 24.5, 22.9, 22.2, 21.2, 20.2, 19.7, 18.9],
+ 'Sep': [13.4, 12.7, 12.2, 11.5, 11.2, 10.7, 10.5, 10.6, 11.3, 13.2, 15.6,
+ 17.9, 19.6, 20.8, 20.9, 20.8, 20.7, 19.8, 18.4, 17.8, 16.9, 16.1, 15.6, 14.9],
+ 'Oct': [9.4, 8.8, 8.5, 7.9, 7.6, 7.2, 7.1, 7.2, 7.7, 9.3, 11.2, 13.0,
+ 14.4, 15.3, 15.4, 15.3, 15.2, 14.5, 13.4, 12.9, 12.2, 11.6, 11.2, 10.6],
+ 'Nov': [4.0, 3.6, 3.3, 2.9, 2.6, 2.3, 2.2, 2.2, 2.7, 3.9, 5.5, 6.9, 8.0,
+ 8.7, 8.8, 8.7, 8.7, 8.1, 7.2, 6.8, 6.3, 5.7, 5.5, 5.0],
+ 'Dec': [1.4, 1.0, 0.8, 0.4, 0.2, -0.0, -0.1, -0.1, 0.3, 1.3, 2.6, 3.8,
+ 4.7, 5.2, 5.3, 5.2, 5.2, 4.7, 4.0, 3.7, 3.2, 2.8, 2.6, 2.2]
+ }
+
+
+# Geneva hourly temperatures as piecewise constant function (in Kelvin).
+GenevaTemperatures_hourly = {
+ month: models.PiecewiseConstant(
+ # NOTE: It is important that the time type is float, not np.float, in
+ # order to allow hashability (for caching).
+ tuple(float(time) for time in range(25)),
+ tuple(273.15 + np.array(temperatures)),
+ )
+ for month, temperatures in Geneva_hourly_temperatures_celsius_per_hour.items()
+}
+
+
+# Same temperatures on a finer temperature mesh (every 6 minutes).
+GenevaTemperatures = {
+ month: GenevaTemperatures_hourly[month].refine(refine_factor=10)
+ for month, temperatures in Geneva_hourly_temperatures_celsius_per_hour.items()
+}
diff --git a/cara/data/weather.py b/cara/data/weather.py
new file mode 100644
index 00000000..37ecde76
--- /dev/null
+++ b/cara/data/weather.py
@@ -0,0 +1,114 @@
+import functools
+import json
+from pathlib import Path
+import typing
+
+import numpy as np
+from scipy.spatial import cKDTree
+
+from cara import models
+
+
+weather_debug = False
+
+DATA_LOCATION = Path(__file__).absolute().parent
+
+
+WxStationIdType = str
+MonthType = str
+# HourlyTempType - 24 temperatures, one for each hour of the day (the average for the given month).
+HourlyTempType = typing.List[float]
+
+
+@functools.lru_cache()
+def wx_data() -> typing.Dict[WxStationIdType, typing.Dict[MonthType, HourlyTempType]]:
+ """
+ Load the weather data (temperature in kelvin).
+
+ The data is structured by station location, and for each station location, by month.
+
+ """
+ with (DATA_LOCATION / 'global_weather_set.json').open("r") as json_file:
+ data = json.load(json_file)
+
+ for station in list(data.keys()):
+ for month in list(data[station].keys()):
+ data[station][month] = tuple(273.15 + np.array(data[station][month]))
+ return data
+
+
+WxStationRecordType = typing.Tuple[WxStationIdType, str, float, float]
+
+
+@functools.lru_cache()
+def wx_station_data() -> typing.Dict[WxStationIdType, WxStationRecordType]:
+ """
+ Return a dictionary of ``station-id: station records``, where station records
+ are of the form ``(station-id, station-name, station-latitude, station-longitude)``.
+
+ The stations returned are guaranteed to have valid weather data.
+
+ """
+ weather_data = wx_data()
+ station_data = {}
+ fixed_delimits = [0, 12, 13, 44, 51, 60, 69, 90, 91]
+ station_file = DATA_LOCATION / 'hadisd_station_fullinfo_v311_202001p.txt'
+
+ for line in station_file.open('rt'):
+ start_end_positions = zip(fixed_delimits[:-1], fixed_delimits[1:])
+ split_vals = [line[start:end] for start, end in start_end_positions]
+ station_location = (
+ split_vals[0], split_vals[2], float(split_vals[3]), float(split_vals[4]),
+ )
+ # We only consider stations with weather data, don't include the rest.
+ if split_vals[0] in weather_data:
+ station_data[split_vals[0]] = station_location
+ return station_data
+
+
+@functools.lru_cache()
+def _wx_station_kdtree() -> cKDTree:
+ """Build a kd-tree of wx station longitude & latitudes (note the coordinate order)"""
+ station_data = wx_station_data().values()
+ coords = np.array([(stn_record[3], stn_record[2]) for stn_record in station_data])
+ return cKDTree(coords)
+
+
+def mean_hourly_temperatures(wx_station: str, month: int) -> HourlyTempType:
+ """
+ Return the mean monthly temperature for the given weather station and month.
+
+ Returns
+ -------
+
+ temperatures: List[24 floats]
+ A list containing 24 temperature values, one for each hour, in kelvin.
+ Index 0 of the result corresponds to hour 00:00-01:00, and index 23 (the last) to 23:00-00:00.
+
+ """
+ return wx_data()[wx_station][str(month)]
+
+
+def hourly_to_piecewise(hourly_data: HourlyTempType) -> models.PiecewiseConstant:
+ """
+ Transform a list of 24 floats into a :class:`cara.models.PiecewiseConstant`.
+
+ """
+ pc = models.PiecewiseConstant(
+ # NOTE: It is important that the time type is float, not np.float, in
+ # order to allow hashability (for caching).
+ tuple(float(time) for time in range(25)),
+ tuple(hourly_data),
+ )
+ return pc
+
+
+def nearest_wx_station(*, longitude: float, latitude: float) -> WxStationRecordType:
+ """
+ Given a latitude & longitude, return the nearest station with valid weather data.
+
+ """
+ ktree = _wx_station_kdtree()
+ station_data = list(wx_station_data().values())
+ dd, ii = ktree.query((longitude, latitude), k=[1])
+ return station_data[ii[0]]
diff --git a/cara/tests/apps/calculator/test_model_generator.py b/cara/tests/apps/calculator/test_model_generator.py
index 98a12438..82ab2279 100644
--- a/cara/tests/apps/calculator/test_model_generator.py
+++ b/cara/tests/apps/calculator/test_model_generator.py
@@ -1,16 +1,14 @@
import dataclasses
+import typing
-import pytest
import numpy as np
import numpy.testing as npt
-from pathlib import Path
-import json
+import pytest
from cara.apps.calculator import model_generator
from cara.apps.calculator.model_generator import _hours2timestring
from cara.apps.calculator.model_generator import minutes_since_midnight
from cara import models
-from cara import data
def test_model_from_dict(baseline_form_data):
@@ -35,13 +33,6 @@ def test_blend_expiration():
def test_ventilation_slidingwindow(baseline_form: model_generator.FormData):
- room = models.Room(75)
- window = models.SlidingWindow(
- active=models.PeriodicInterval(period=120, duration=10),
- inside_temp=models.PiecewiseConstant((0, 24), (293,)),
- outside_temp=data.Temperatures['12'],
- window_height=1.6, opening_length=0.6,
- )
baseline_form.ventilation_type = 'natural_ventilation'
baseline_form.windows_duration = 10
baseline_form.windows_frequency = 120
@@ -51,19 +42,28 @@ def test_ventilation_slidingwindow(baseline_form: model_generator.FormData):
baseline_form.window_height = 1.6
baseline_form.opening_distance = 0.6
- ts = np.linspace(8, 16, 100)
- np.testing.assert_allclose([window.air_exchange(room, t)+0.25 for t in ts],
- [baseline_form.ventilation().air_exchange(room, t) for t in ts])
+ baseline_vent = baseline_form.ventilation()
+ assert isinstance(baseline_vent, models.MultipleVentilation)
+ baseline_window = baseline_vent.ventilations[0]
+ assert isinstance(baseline_window, models.SlidingWindow)
+
+ window = models.SlidingWindow(
+ active=models.PeriodicInterval(period=120, duration=10),
+ inside_temp=models.PiecewiseConstant((0, 24), (293,)),
+ outside_temp=baseline_window.outside_temp,
+ window_height=1.6, opening_length=0.6,
+ )
+
+ ach = models.AirChange(
+ active=models.PeriodicInterval(period=120, duration=120),
+ air_exch=0.25,
+ )
+ ventilation = models.MultipleVentilation((window, ach))
+
+ assert ventilation == baseline_vent
def test_ventilation_hingedwindow(baseline_form: model_generator.FormData):
- room = models.Room(75)
- window = models.HingedWindow(
- active=models.PeriodicInterval(period=120, duration=10),
- inside_temp=models.PiecewiseConstant((0, 24), (293,)),
- outside_temp=data.Temperatures['12'],
- window_height=1.6, window_width=1., opening_length=0.6,
- )
baseline_form.ventilation_type = 'natural_ventilation'
baseline_form.windows_duration = 10
baseline_form.windows_frequency = 120
@@ -74,9 +74,24 @@ def test_ventilation_hingedwindow(baseline_form: model_generator.FormData):
baseline_form.window_width = 1.
baseline_form.opening_distance = 0.6
- ts = np.linspace(8, 16, 100)
- np.testing.assert_allclose([window.air_exchange(room, t)+0.25 for t in ts],
- [baseline_form.ventilation().air_exchange(room, t) for t in ts])
+ baseline_vent = baseline_form.ventilation()
+ assert isinstance(baseline_vent, models.MultipleVentilation)
+ baseline_window = baseline_vent.ventilations[0]
+ assert isinstance(baseline_window, models.HingedWindow)
+
+ window = models.HingedWindow(
+ active=models.PeriodicInterval(period=120, duration=10),
+ inside_temp=models.PiecewiseConstant((0, 24), (293,)),
+ outside_temp=baseline_window.outside_temp,
+ window_height=1.6, window_width=1., opening_length=0.6,
+ )
+ ach = models.AirChange(
+ active=models.PeriodicInterval(period=120, duration=120),
+ air_exch=0.25,
+ )
+ ventilation = models.MultipleVentilation((window, ach))
+
+ assert ventilation == baseline_vent
def test_ventilation_mechanical(baseline_form: model_generator.FormData):
@@ -110,19 +125,6 @@ def test_ventilation_airchanges(baseline_form: model_generator.FormData):
def test_ventilation_window_hepa(baseline_form: model_generator.FormData):
- room = models.Room(75)
- window = models.SlidingWindow(
- active=models.PeriodicInterval(period=120, duration=10),
- inside_temp=models.PiecewiseConstant((0, 24), (293,)),
- outside_temp=data.Temperatures['12'],
- window_height=1.6, opening_length=0.6,
- )
- hepa = models.HEPAFilter(
- active=models.PeriodicInterval(period=120, duration=120),
- q_air_mech=250.,
- )
- ventilation = models.MultipleVentilation((window, hepa))
-
baseline_form.ventilation_type = 'natural_ventilation'
baseline_form.windows_duration = 10
baseline_form.windows_frequency = 120
@@ -132,9 +134,29 @@ def test_ventilation_window_hepa(baseline_form: model_generator.FormData):
baseline_form.opening_distance = 0.6
baseline_form.hepa_option = True
- ts = np.linspace(9, 17, 100)
- np.testing.assert_allclose([ventilation.air_exchange(room, t)+0.25 for t in ts],
- [baseline_form.ventilation().air_exchange(room, t) for t in ts])
+ baseline_vent = baseline_form.ventilation()
+ assert isinstance(baseline_vent, models.MultipleVentilation)
+ baseline_window = baseline_vent.ventilations[0]
+ assert isinstance(baseline_window, models.SlidingWindow)
+
+ # Now build the equivalent ventilation instance directly, and compare.
+ window = models.SlidingWindow(
+ active=models.PeriodicInterval(period=120, duration=10),
+ inside_temp=models.PiecewiseConstant((0, 24), (293,)),
+ outside_temp=baseline_window.outside_temp,
+ window_height=1.6, opening_length=0.6,
+ )
+ hepa = models.HEPAFilter(
+ active=models.PeriodicInterval(period=120, duration=120),
+ q_air_mech=250.,
+ )
+ ach = models.AirChange(
+ active=models.PeriodicInterval(period=120, duration=120),
+ air_exch=0.25,
+ )
+ ventilation = models.MultipleVentilation((window, hepa, ach))
+
+ assert ventilation == baseline_vent
def present_times(interval: models.Interval) -> models.BoundarySequence_t:
@@ -163,8 +185,7 @@ def test_exposed_present_intervals(baseline_form: model_generator.FormData):
baseline_form.exposed_finish = minutes_since_midnight(17 * 60)
baseline_form.exposed_lunch_start = minutes_since_midnight(12 * 60 + 30)
baseline_form.exposed_lunch_finish = minutes_since_midnight(13 * 60 + 30)
- correct = ((9, 10+37/60), (10+52/60, 12.5),
- (13.5, 15+7/60), (15+22/60, 17.0))
+ correct = ((9, 10+37/60), (10+52/60, 12.5), (13.5, 15+7/60), (15+22/60, 17.0))
assert present_times(baseline_form.exposed_present_interval()) == correct
@@ -172,50 +193,37 @@ def test_present_intervals_common_breaks(baseline_form: model_generator.FormData
baseline_form.infected_dont_have_breaks_with_exposed = False
baseline_form.infected_coffee_duration = baseline_form.exposed_coffee_duration = 15
baseline_form.infected_coffee_break_option = baseline_form.exposed_coffee_break_option = 'coffee_break_2'
- baseline_form.exposed_lunch_start = baseline_form.infected_lunch_start = minutes_since_midnight(
- 12 * 60 + 30)
- baseline_form.exposed_lunch_finish = baseline_form.infected_lunch_finish = minutes_since_midnight(
- 13 * 60 + 30)
+ baseline_form.exposed_lunch_start = baseline_form.infected_lunch_start = minutes_since_midnight(12 * 60 + 30)
+ baseline_form.exposed_lunch_finish = baseline_form.infected_lunch_finish = minutes_since_midnight(13 * 60 + 30)
baseline_form.exposed_start = minutes_since_midnight(9 * 60)
baseline_form.exposed_finish = minutes_since_midnight(17 * 60)
baseline_form.infected_start = minutes_since_midnight(9 * 60)
baseline_form.infected_finish = minutes_since_midnight(16 * 60)
- correct_exposed = ((9, 10+37/60), (10+52/60, 12.5),
- (13.5, 15+7/60), (15+22/60, 17.0))
- correct_infected = ((9, 10+37/60), (10+52/60, 12.5),
- (13.5, 15+7/60), (15+22/60, 16.0))
- assert present_times(
- baseline_form.exposed_present_interval()) == correct_exposed
- assert present_times(
- baseline_form.infected_present_interval()) == correct_infected
+ correct_exposed = ((9, 10+37/60), (10+52/60, 12.5), (13.5, 15+7/60), (15+22/60, 17.0))
+ correct_infected = ((9, 10+37/60), (10+52/60, 12.5), (13.5, 15+7/60), (15+22/60, 16.0))
+ assert present_times(baseline_form.exposed_present_interval()) == correct_exposed
+ assert present_times(baseline_form.infected_present_interval()) == correct_infected
def test_present_intervals_split_breaks(baseline_form: model_generator.FormData):
baseline_form.infected_dont_have_breaks_with_exposed = True
baseline_form.infected_coffee_duration = baseline_form.exposed_coffee_duration = 15
baseline_form.infected_coffee_break_option = baseline_form.exposed_coffee_break_option = 'coffee_break_2'
- baseline_form.infected_lunch_start = baseline_form.exposed_lunch_start = minutes_since_midnight(
- 12 * 60 + 30)
- baseline_form.infected_lunch_finish = baseline_form.exposed_lunch_finish = minutes_since_midnight(
- 13 * 60 + 30)
+ baseline_form.infected_lunch_start = baseline_form.exposed_lunch_start = minutes_since_midnight(12 * 60 + 30)
+ baseline_form.infected_lunch_finish = baseline_form.exposed_lunch_finish = minutes_since_midnight(13 * 60 + 30)
baseline_form.exposed_start = minutes_since_midnight(9 * 60)
baseline_form.exposed_finish = minutes_since_midnight(17 * 60)
baseline_form.infected_start = minutes_since_midnight(9 * 60)
baseline_form.infected_finish = minutes_since_midnight(16 * 60)
- correct_exposed = ((9, 10+37/60), (10+52/60, 12.5),
- (13.5, 15+7/60), (15+22/60, 17.0))
- correct_infected = ((9, 10+37/60), (10+52/60, 12.5),
- (13.5, 14+37/60), (14+52/60, 16.0))
- assert present_times(
- baseline_form.exposed_present_interval()) == correct_exposed
- assert present_times(
- baseline_form.infected_present_interval()) == correct_infected
+ correct_exposed = ((9, 10+37/60), (10+52/60, 12.5), (13.5, 15+7/60), (15+22/60, 17.0))
+ correct_infected = ((9, 10+37/60), (10+52/60, 12.5), (13.5, 14+37/60), (14+52/60, 16.0))
+ assert present_times(baseline_form.exposed_present_interval()) == correct_exposed
+ assert present_times(baseline_form.infected_present_interval()) == correct_infected
def test_exposed_present_intervals_starting_with_lunch(baseline_form: model_generator.FormData):
baseline_form.exposed_coffee_break_option = 'coffee_break_0'
- baseline_form.exposed_start = baseline_form.exposed_lunch_start = minutes_since_midnight(
- 13 * 60)
+ baseline_form.exposed_start = baseline_form.exposed_lunch_start = minutes_since_midnight(13 * 60)
baseline_form.exposed_finish = minutes_since_midnight(18 * 60)
baseline_form.exposed_lunch_finish = minutes_since_midnight(14 * 60)
correct = ((14.0, 18.0), )
@@ -225,8 +233,7 @@ def test_exposed_present_intervals_starting_with_lunch(baseline_form: model_gene
def test_exposed_present_intervals_ending_with_lunch(baseline_form: model_generator.FormData):
baseline_form.exposed_coffee_break_option = 'coffee_break_0'
baseline_form.exposed_start = minutes_since_midnight(11 * 60)
- baseline_form.exposed_finish = baseline_form.exposed_lunch_start = minutes_since_midnight(
- 13 * 60)
+ baseline_form.exposed_finish = baseline_form.exposed_lunch_start = minutes_since_midnight(13 * 60)
baseline_form.exposed_lunch_finish = minutes_since_midnight(14 * 60)
correct = ((11.0, 13.0),)
assert present_times(baseline_form.exposed_present_interval()) == correct
@@ -308,8 +315,7 @@ def breaks_every_25_mins_for_20_mins(baseline_form: model_generator.FormData):
baseline_form.exposed_lunch_finish = time2mins("12:15")
baseline_form.exposed_lunch_option = True
- breaks = baseline_form.exposed_coffee_break_times(
- ) + baseline_form.exposed_lunch_break_times()
+ breaks = baseline_form.exposed_coffee_break_times() + baseline_form.exposed_lunch_break_times()
interval = baseline_form.present_interval(
baseline_form.exposed_start, baseline_form.exposed_finish, breaks=breaks,
)
@@ -326,8 +332,7 @@ def breaks_every_25_mins_for_20_mins(baseline_form: model_generator.FormData):
def test_present_after_two_breaks_for_small_interval(breaks_every_25_mins_for_20_mins):
- breaks = breaks_every_25_mins_for_20_mins.exposed_coffee_break_times(
- ) + breaks_every_25_mins_for_20_mins.exposed_lunch_break_times()
+ breaks = breaks_every_25_mins_for_20_mins.exposed_coffee_break_times() + breaks_every_25_mins_for_20_mins.exposed_lunch_break_times()
# The first two breaks start at 10:25 and 11:10.
interval = breaks_every_25_mins_for_20_mins.present_interval(
time2mins("11:35"), time2mins("11:40"), breaks=breaks,
@@ -337,8 +342,7 @@ def test_present_after_two_breaks_for_small_interval(breaks_every_25_mins_for_20
def test_present_only_during_second_break(breaks_every_25_mins_for_20_mins):
- breaks = breaks_every_25_mins_for_20_mins.exposed_coffee_break_times(
- ) + breaks_every_25_mins_for_20_mins.exposed_lunch_break_times()
+ breaks = breaks_every_25_mins_for_20_mins.exposed_coffee_break_times() + breaks_every_25_mins_for_20_mins.exposed_lunch_break_times()
# The first two breaks start at 10:25 and 11:10.
interval = breaks_every_25_mins_for_20_mins.present_interval(
time2mins("11:15"), time2mins("11:20"), breaks=breaks
@@ -366,10 +370,8 @@ def test_no_breaks(baseline_form: model_generator.FormData):
baseline_form.infected_finish = minutes_since_midnight(15 * 60)
exposed_correct = ((9, 17),)
infected_correct = ((10, 15),)
- assert present_times(
- baseline_form.exposed_present_interval()) == exposed_correct
- assert present_times(
- baseline_form.infected_present_interval()) == infected_correct
+ assert present_times(baseline_form.exposed_present_interval()) == exposed_correct
+ assert present_times(baseline_form.infected_present_interval()) == infected_correct
def test_coffee_lunch_breaks(baseline_form: model_generator.FormData):
@@ -381,8 +383,7 @@ def test_coffee_lunch_breaks(baseline_form: model_generator.FormData):
baseline_form.exposed_lunch_finish = minutes_since_midnight(13 * 60 + 30)
correct = ((9, 9+50/60), (10+20/60, 11+10/60), (11+40/60, 12+30/60),
(13+30/60, 14+40/60), (15+10/60, 16+20/60), (16+50/60, 18))
- np.testing.assert_allclose(present_times(
- baseline_form.exposed_present_interval()), correct, rtol=1e-14)
+ np.testing.assert_allclose(present_times(baseline_form.exposed_present_interval()), correct, rtol=1e-14)
def test_coffee_lunch_breaks_unbalance(baseline_form: model_generator.FormData):
@@ -393,8 +394,7 @@ def test_coffee_lunch_breaks_unbalance(baseline_form: model_generator.FormData):
baseline_form.exposed_lunch_start = minutes_since_midnight(12 * 60 + 30)
baseline_form.exposed_lunch_finish = minutes_since_midnight(13 * 60 + 30)
correct = ((9, 9+50/60), (10+20/60, 11+10/60), (11+40/60, 12+30/60))
- np.testing.assert_allclose(present_times(
- baseline_form.exposed_present_interval()), correct, rtol=1e-14)
+ np.testing.assert_allclose(present_times(baseline_form.exposed_present_interval()), correct, rtol=1e-14)
def test_coffee_breaks(baseline_form: model_generator.FormData):
@@ -403,10 +403,8 @@ def test_coffee_breaks(baseline_form: model_generator.FormData):
baseline_form.exposed_start = minutes_since_midnight(9 * 60)
baseline_form.exposed_finish = minutes_since_midnight(10 * 60)
baseline_form.exposed_lunch_option = False
- correct = ((9, 9+4/60), (9+14/60, 9+18/60), (9+28/60, 9+32/60),
- (9+42/60, 9+46/60), (9+56/60, 10))
- np.testing.assert_allclose(present_times(
- baseline_form.exposed_present_interval()), correct, rtol=1e-14)
+ correct = ((9, 9+4/60), (9+14/60, 9+18/60), (9+28/60, 9+32/60), (9+42/60, 9+46/60), (9+56/60, 10))
+ np.testing.assert_allclose(present_times(baseline_form.exposed_present_interval()), correct, rtol=1e-14)
def test_key_validation(baseline_form_data):
@@ -439,8 +437,7 @@ def test_key_validation_mech_ventilation_type_na(baseline_form_data):
def test_default_types():
# Validate that FormData._DEFAULTS are complete and of the correct type.
# Validate that we have the right types and matching attributes to the DEFAULTS.
- fields = {field.name: field for field in dataclasses.fields(
- model_generator.FormData)}
+ fields = {field.name: field for field in dataclasses.fields(model_generator.FormData)}
for field, value in model_generator.FormData._DEFAULTS.items():
if field not in fields:
raise ValueError(f"Unmatched default {field}")
@@ -454,12 +451,10 @@ def test_default_types():
continue
if field in model_generator._CAST_RULES_FORM_ARG_TO_NATIVE:
- value = model_generator._CAST_RULES_FORM_ARG_TO_NATIVE[field](
- value)
+ value = model_generator._CAST_RULES_FORM_ARG_TO_NATIVE[field](value)
if not isinstance(value, field_type):
- raise TypeError(
- f'{field} has type {field_type}, got {type(value)}')
+ raise TypeError(f'{field} has type {field_type}, got {type(value)}')
for field in fields.values():
assert field.name in model_generator.FormData._DEFAULTS, f"No default set for field name {field.name}"
@@ -471,28 +466,5 @@ def test_form_to_dict(baseline_form):
assert 1 < len(stripped) < len(full)
assert 'exposed_coffee_break_option' in stripped
# If we set the value to the default one, it should no longer turn up in the dictionary.
- baseline_form.exposed_coffee_break_option = model_generator.FormData._DEFAULTS[
- 'exposed_coffee_break_option']
- assert 'exposed_coffee_break_option' not in baseline_form.to_dict(
- baseline_form, strip_defaults=True)
-
-
-def test_weather_stations():
- fixed_delimits = [0, 12, 13, 44, 51, 60, 69, 90, 91]
-
- station_file = Path(__file__).parent.parent.parent.parent / 'data' / \
- 'hadisd_station_fullinfo_v311_202001p.txt'
-
- with open(Path(__file__).parent.parent.parent.parent / 'data' / 'global_weather_set.json', "r") as json_file:
- weather_dict = json.load(json_file)
-
- for line in station_file.open('rt'):
- start_end_positions = zip(fixed_delimits[:-1], fixed_delimits[1:])
- split_vals = [line[start:end] for start, end in start_end_positions]
-
- station_id = split_vals[0]
- # Check if weather station exists
- temp_dict = weather_dict[station_id]
-
- for month in range(1, 13):
- assert not np.any(np.isnan(temp_dict[str(month)]))
+ baseline_form.exposed_coffee_break_option = model_generator.FormData._DEFAULTS['exposed_coffee_break_option']
+ assert 'exposed_coffee_break_option' not in baseline_form.to_dict(baseline_form, strip_defaults=True)
diff --git a/cara/tests/data/__init__.py b/cara/tests/data/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/cara/tests/data/test_weather.py b/cara/tests/data/test_weather.py
new file mode 100644
index 00000000..b0f75611
--- /dev/null
+++ b/cara/tests/data/test_weather.py
@@ -0,0 +1,11 @@
+import cara.data.weather as wx
+
+
+def test_nearest_wx_station():
+ melbourne_lat, melbourne_lon = -37.81739, 144.96751
+ station_rec = wx.nearest_wx_station(longitude=melbourne_lon, latitude=melbourne_lat)
+
+ station_name = station_rec[1].strip()
+ # Note: For Melbourne, the nearest station is 'MELBOURNE REGIONAL OFFICE',
+ # but the nearest location with suitable wx data is 'MELBOURNE ESSENDON'
+ assert station_name == 'MELBOURNE ESSENDON'
diff --git a/cara/tests/models/test_piecewiseconstant.py b/cara/tests/models/test_piecewiseconstant.py
index 1f90a5a9..a0ba14f0 100644
--- a/cara/tests/models/test_piecewiseconstant.py
+++ b/cara/tests/models/test_piecewiseconstant.py
@@ -81,5 +81,5 @@ def test_piecewiseconstant_vs_interval(time):
def test_piecewiseconstant_transition_times():
- outside_temp = data.Temperatures['1']
+ outside_temp = data.GenevaTemperatures['Jan']
assert set(outside_temp.transition_times) == outside_temp.interval().transition_times()
diff --git a/cara/tests/test_known_quantities.py b/cara/tests/test_known_quantities.py
index 6f67b834..89c0268d 100644
--- a/cara/tests/test_known_quantities.py
+++ b/cara/tests/test_known_quantities.py
@@ -9,7 +9,7 @@ import cara.data as data
def test_no_mask_superspeading_emission_rate(baseline_model):
expected_rate = 48500.
npt.assert_allclose(
- [baseline_model.infected.emission_rate(t) for t in [0, 1, 4, 4.5, 5, 8, 9]],
+ [baseline_model.infected.emission_rate(float(t)) for t in [0, 1, 4, 4.5, 5, 8, 9]],
[0, expected_rate, expected_rate, 0, 0, expected_rate, 0],
rtol=1e-12
)
@@ -19,8 +19,8 @@ def test_no_mask_superspeading_emission_rate(baseline_model):
def baseline_periodic_window():
return models.SlidingWindow(
active=models.PeriodicInterval(period=120, duration=15),
- inside_temp=models.PiecewiseConstant((0,24),(293,)),
- outside_temp=models.PiecewiseConstant((0,24),(283,)),
+ inside_temp=models.PiecewiseConstant((0., 24.), (293,)),
+ outside_temp=models.PiecewiseConstant((0., 24.), (283,)),
window_height=1.6, opening_length=0.6,
)
@@ -41,7 +41,7 @@ def baseline_periodic_hepa():
def test_concentrations(baseline_model):
# expected concentrations were computed analytically
ts = [0, 4, 5, 7, 10]
- concentrations = [baseline_model.concentration(t) for t in ts]
+ concentrations = [baseline_model.concentration(float(t)) for t in ts]
npt.assert_allclose(
concentrations,
[0.000000e+00, 20.805628, 6.602814e-13, 20.805628, 2.09545e-26],
@@ -55,7 +55,7 @@ def test_smooth_concentrations(baseline_model):
dx = 0.002
dy_limit = 0.2 # Anything more than this (in relative) is a bit steep.
ts = np.arange(0, 10, dx)
- concentrations = [baseline_model.concentration(t) for t in ts]
+ concentrations = [baseline_model.concentration(float(t)) for t in ts]
assert np.abs(np.diff(concentrations)).max()/np.mean(concentrations) < dy_limit
@@ -69,7 +69,7 @@ def build_model(interval_duration):
infected=models.InfectedPopulation(
number=1,
virus=models.Virus.types['SARS_CoV_2'],
- presence=models.SpecificInterval(((0, 4), (5, 8))),
+ presence=models.SpecificInterval(((0., 4.), (5., 8.))),
mask=models.Mask.types['No mask'],
activity=models.Activity.types['Light activity'],
expiration=models.Expiration.types['Superspreading event'],
@@ -78,7 +78,7 @@ def build_model(interval_duration):
return model
-def test_concentrations_startup(baseline_model):
+def test_concentrations_startup():
# The concentrations should be the same until the beginning of the
# first time that the ventilation is disabled.
m1 = build_model(interval_duration=120)
@@ -183,28 +183,38 @@ def test_multiple_ventilation_HEPA_HVAC_AirChange(volume, expected_value):
],
)
def test_windowopening(time, expected_value):
- tempOutside = models.PiecewiseConstant((0,10,24),(273.15,283.15))
- tempInside = models.PiecewiseConstant((0,24),(293.15,))
- w = models.SlidingWindow(active=models.SpecificInterval([(0,24)]),
- inside_temp=tempInside,outside_temp=tempOutside,
- window_height=1.,opening_length=0.6)
- npt.assert_allclose(w.air_exchange(models.Room(volume=68),time),
- expected_value,rtol=1e-5)
+ tempOutside = models.PiecewiseConstant((0., 10., 24.),(273.15, 283.15))
+ tempInside = models.PiecewiseConstant((0., 24.), (293.15,))
+ w = models.SlidingWindow(
+ active=models.SpecificInterval([(0., 24.)]),
+ inside_temp=tempInside,outside_temp=tempOutside,
+ window_height=1., opening_length=0.6,
+ )
+ npt.assert_allclose(
+ w.air_exchange(models.Room(volume=68), time), expected_value, rtol=1e-5
+ )
-def build_hourly_dependent_model(month, intervals_open=((7.5, 8.5),),
- intervals_presence_infected=((0, 4), (5, 7.5)),
- artificial_refinement=False,
- temperatures=data.Temperatures_hourly):
+def build_hourly_dependent_model(
+ month,
+ intervals_open=((7.5, 8.5),),
+ intervals_presence_infected=((0., 4.), (5., 7.5)),
+ artificial_refinement=False,
+ temperatures=data.GenevaTemperatures_hourly
+):
if artificial_refinement:
# 5-fold increase of number of times, WITHOUT interpolation
# (hence transparent for the results)
refine_factor = 2
- times_refined = tuple(np.linspace(0.,24,
- refine_factor*len(temperatures[month].values)+1))
- temperatures_refined = tuple(np.hstack([[v]*refine_factor
- for v in temperatures[month].values]))
- outside_temp = models.PiecewiseConstant(times_refined,temperatures_refined)
+ times_refined = tuple(
+ float(t) for t in np.linspace(
+ 0., 24, refine_factor * len(temperatures[month].values) + 1
+ )
+ )
+ temperatures_refined = tuple(np.hstack(
+ [[v] * refine_factor for v in temperatures[month].values]
+ ))
+ outside_temp = models.PiecewiseConstant(times_refined, temperatures_refined)
else:
outside_temp = temperatures[month]
@@ -212,7 +222,7 @@ def build_hourly_dependent_model(month, intervals_open=((7.5, 8.5),),
room=models.Room(volume=75),
ventilation=models.SlidingWindow(
active=models.SpecificInterval(intervals_open),
- inside_temp=models.PiecewiseConstant((0,24),(293,)),
+ inside_temp=models.PiecewiseConstant((0., 24.), (293, )),
outside_temp=outside_temp,
window_height=1.6, opening_length=0.6,
),
@@ -233,14 +243,14 @@ def build_constant_temp_model(outside_temp, intervals_open=((7.5, 8.5),)):
room=models.Room(volume=75),
ventilation=models.SlidingWindow(
active=models.SpecificInterval(intervals_open),
- inside_temp=models.PiecewiseConstant((0,24),(293,)),
- outside_temp=models.PiecewiseConstant((0,24),(outside_temp,)),
+ inside_temp=models.PiecewiseConstant((0., 24.), (293,)),
+ outside_temp=models.PiecewiseConstant((0., 24.), (outside_temp,)),
window_height=1.6, opening_length=0.6,
),
infected=models.InfectedPopulation(
number=1,
virus=models.Virus.types['SARS_CoV_2'],
- presence=models.SpecificInterval(((0, 4), (5, 7.5))),
+ presence=models.SpecificInterval(((0., 4.), (5., 7.5))),
mask=models.Mask.types['No mask'],
activity=models.Activity.types['Light activity'],
expiration=models.Expiration.types['Superspreading event'],
@@ -253,21 +263,22 @@ def build_hourly_dependent_model_multipleventilation(month, intervals_open=((7.5
vent = models.MultipleVentilation((
models.SlidingWindow(
active=models.SpecificInterval(intervals_open),
- inside_temp=models.PiecewiseConstant((0,24),(293,)),
- outside_temp=data.Temperatures[month],
+ inside_temp=models.PiecewiseConstant((0., 24.), (293,)),
+ outside_temp=data.GenevaTemperatures[month],
window_height=1.6, opening_length=0.6,
),
models.HEPAFilter(
- active=models.SpecificInterval(((0,24),)),
- q_air_mech=500.,
- )))
+ active=models.SpecificInterval(((0., 24.),)),
+ q_air_mech=500.,
+ ),
+ ))
model = models.ConcentrationModel(
room=models.Room(volume=75),
ventilation=vent,
infected=models.InfectedPopulation(
number=1,
virus=models.Virus.types['SARS_CoV_2'],
- presence=models.SpecificInterval(((0, 4), (5, 7.5))),
+ presence=models.SpecificInterval(((0., 4.), (5., 7.5))),
mask=models.Mask.types['No mask'],
activity=models.Activity.types['Light activity'],
expiration=models.Expiration.types['Superspreading event'],
@@ -278,7 +289,7 @@ def build_hourly_dependent_model_multipleventilation(month, intervals_open=((7.5
@pytest.mark.parametrize(
"month, temperatures",
- data.local_tempatures.items(),
+ data.Geneva_hourly_temperatures_celsius_per_hour.items(),
)
@pytest.mark.parametrize(
"time",
@@ -288,12 +299,12 @@ def test_concentrations_hourly_dep_temp_vs_constant(month, temperatures, time):
# The concentrations should be the same up to 8 AM (time when the
# temperature changes DURING the window opening).
m1 = build_hourly_dependent_model(month)
- m2 = build_constant_temp_model(temperatures[7]+273.15)
+ m2 = build_constant_temp_model(temperatures[7] + 273.15)
npt.assert_allclose(m1.concentration(time), m2.concentration(time), rtol=1e-5)
@pytest.mark.parametrize(
"month, temperatures",
- data.local_tempatures.items(),
+ data.Geneva_hourly_temperatures_celsius_per_hour.items(),
)
@pytest.mark.parametrize(
"time",
@@ -301,20 +312,23 @@ def test_concentrations_hourly_dep_temp_vs_constant(month, temperatures, time):
)
def test_concentrations_hourly_dep_temp_startup(month, temperatures, time):
# The concentrations should be the zero up to the first presence time
- # of an infecter person.
- m = build_hourly_dependent_model(month,((0.,0.5),(1,1.5),(4,4.5),(7.5,8)),
- ((8,12.),))
+ # of an infected person.
+ m = build_hourly_dependent_model(
+ month,
+ ((0., 0.5), (1., 1.5), (4., 4.5), (7.5, 8), ),
+ ((8., 12.), ),
+ )
assert m.concentration(time) == 0.
def test_concentrations_hourly_dep_multipleventilation():
- m = build_hourly_dependent_model_multipleventilation('1')
+ m = build_hourly_dependent_model_multipleventilation('Jan')
m.concentration(12.)
@pytest.mark.parametrize(
"month_temp_item",
- data.local_tempatures.items(),
+ data.Geneva_hourly_temperatures_celsius_per_hour.items(),
)
@pytest.mark.parametrize(
"time",
@@ -323,19 +337,22 @@ def test_concentrations_hourly_dep_multipleventilation():
def test_concentrations_hourly_dep_adding_artificial_transitions(month_temp_item, time):
month, temperatures = month_temp_item
# Adding a second opening inside the first one should not change anything
- m1 = build_hourly_dependent_model(month,intervals_open=((7.5, 8.5),))
- m2 = build_hourly_dependent_model(month,intervals_open=((7.5, 8.5),(8.,8.1)))
+ m1 = build_hourly_dependent_model(month, intervals_open=((7.5, 8.5), ))
+ m2 = build_hourly_dependent_model(month, intervals_open=((7.5, 8.5), (8., 8.1), ))
npt.assert_allclose(m1.concentration(time), m2.concentration(time), rtol=1e-5)
@pytest.mark.parametrize(
"time",
- list(np.random.random_sample(10)*24.)+list(np.arange(0,24.5,0.5)),
+ (
+ [float(t) for t in np.random.random_sample(10) * 24.] # type: ignore
+ + [float(t) for t in np.arange(0, 24.5, 0.5)]
+ ),
)
def test_concentrations_refine_times(time):
- month = '1'
- m1 = build_hourly_dependent_model(month,intervals_open=((0, 24),))
- m2 = build_hourly_dependent_model(month,intervals_open=((0, 24),),
+ month = 'Jan'
+ m1 = build_hourly_dependent_model(month, intervals_open=((0., 24.),))
+ m2 = build_hourly_dependent_model(month, intervals_open=((0., 24.),),
artificial_refinement=True)
npt.assert_allclose(m1.concentration(time), m2.concentration(time), rtol=1e-8)
@@ -350,7 +367,7 @@ def build_exposure_model(concentration_model):
activity=infected.activity,
mask=infected.mask,
),
- fraction_deposited = 1.,
+ fraction_deposited=1.,
)
@@ -359,16 +376,16 @@ def build_exposure_model(concentration_model):
@pytest.mark.parametrize(
"month, expected_exposure",
[
- ['1', 496.5427],
- ['6', 1898.1354],
+ ['Jan', 496.5427],
+ ['Jun', 1898.1354],
],
)
def test_exposure_hourly_dep(month,expected_exposure):
m = build_exposure_model(
build_hourly_dependent_model(
month,
- intervals_open=((0,24),),
- intervals_presence_infected=((8, 12), (13, 17))
+ intervals_open=((0., 24.), ),
+ intervals_presence_infected=((8., 12.), (13., 17.))
)
)
exposure = m.exposure()
@@ -380,17 +397,17 @@ def test_exposure_hourly_dep(month,expected_exposure):
@pytest.mark.parametrize(
"month, expected_exposure",
[
- ['1', 499.6921],
- ['6', 2007.59925],
+ ['Jan', 499.6921],
+ ['Jun', 2007.59925],
],
)
def test_exposure_hourly_dep_refined(month,expected_exposure):
m = build_exposure_model(
build_hourly_dependent_model(
month,
- intervals_open=((0, 24),),
- intervals_presence_infected=((8, 12), (13, 17)),
- temperatures=data.Temperatures,
+ intervals_open=((0., 24.),),
+ intervals_presence_infected=((8., 12.), (13., 17.)),
+ temperatures=data.GenevaTemperatures,
)
)
exposure = m.exposure()
diff --git a/cara/tests/test_monte_carlo_full_models.py b/cara/tests/test_monte_carlo_full_models.py
index 8776cb13..5cf88198 100644
--- a/cara/tests/test_monte_carlo_full_models.py
+++ b/cara/tests/test_monte_carlo_full_models.py
@@ -26,12 +26,12 @@ def shared_office_mc():
(
models.SlidingWindow(
active=models.PeriodicInterval(period=120, duration=10),
- inside_temp=models.PiecewiseConstant((0, 24), (293,)),
- outside_temp=models.PiecewiseConstant((0, 24), (283,)),
+ inside_temp=models.PiecewiseConstant((0., 24.), (293,)),
+ outside_temp=models.PiecewiseConstant((0., 24.), (283,)),
window_height=1.6, opening_length=0.6,
),
models.AirChange(
- active=models.SpecificInterval(((0,24),)),
+ active=models.SpecificInterval(((0., 24.), )),
air_exch=0.25,
),
),
@@ -39,7 +39,7 @@ def shared_office_mc():
infected=mc.InfectedPopulation(
number=1,
virus=virus_distributions['SARS_CoV_2_B117'],
- presence=mc.SpecificInterval(((0, 2), (2.1, 4), (5, 7), (7.1, 9))),
+ presence=mc.SpecificInterval(((0., 2.), (2.1, 4.), (5., 7.), (7.1, 9.))),
mask=models.Mask(η_inhale=0.3),
activity=activity_distributions['Seated'],
expiration=models.MultipleExpiration(
@@ -70,12 +70,12 @@ def classroom_mc():
(
models.SlidingWindow(
active=models.PeriodicInterval(period=120, duration=10),
- inside_temp=models.PiecewiseConstant((0, 24), (293,)),
- outside_temp=models.PiecewiseConstant((0, 24), (283,)),
+ inside_temp=models.PiecewiseConstant((0., 24.), (293,)),
+ outside_temp=models.PiecewiseConstant((0., 24.), (283,)),
window_height=1.6, opening_length=0.6,
),
models.AirChange(
- active=models.SpecificInterval(((0,24),)),
+ active=models.SpecificInterval(((0., 24.),)),
air_exch=0.25,
),
),
@@ -83,7 +83,7 @@ def classroom_mc():
infected=mc.InfectedPopulation(
number=1,
virus=virus_distributions['SARS_CoV_2_B117'],
- presence=mc.SpecificInterval(((0, 2), (2.5, 4), (5, 7), (7.5, 9))),
+ presence=mc.SpecificInterval(((0., 2.), (2.5, 4.), (5., 7.), (7.5, 9.))),
mask=models.Mask.types['No mask'],
activity=activity_distributions['Light activity'],
expiration=models.Expiration.types['Talking'],
@@ -108,13 +108,13 @@ def ski_cabin_mc():
concentration_mc = mc.ConcentrationModel(
room=models.Room(volume=10, humidity=0.5),
ventilation=models.AirChange(
- active=models.SpecificInterval(((0,24),)),
+ active=models.SpecificInterval(((0., 24.),)),
air_exch=0,
),
infected=mc.InfectedPopulation(
number=1,
virus=virus_distributions['SARS_CoV_2_B117'],
- presence=mc.SpecificInterval(((0, 1/3),)),
+ presence=mc.SpecificInterval(((0., 1/3),)),
mask=models.Mask(η_inhale=0.3),
activity=activity_distributions['Moderate activity'],
expiration=models.Expiration.types['Talking'],
@@ -141,13 +141,13 @@ def gym_mc():
concentration_mc = mc.ConcentrationModel(
room=models.Room(volume=300, humidity=0.5),
ventilation=models.AirChange(
- active=models.SpecificInterval(((0,24),)),
+ active=models.SpecificInterval(((0., 24.),)),
air_exch=6,
),
infected=mc.InfectedPopulation(
number=2,
virus=virus_distributions['SARS_CoV_2_B117'],
- presence=mc.SpecificInterval(((0, 1),)),
+ presence=mc.SpecificInterval(((0., 1.),)),
mask=models.Mask.types["No mask"],
activity=activity_distributions['Heavy exercise'],
expiration=models.Expiration.types['Breathing'],
@@ -173,13 +173,13 @@ def waiting_room_mc():
concentration_mc = mc.ConcentrationModel(
room=models.Room(volume=100, humidity=0.5),
ventilation=models.AirChange(
- active=models.SpecificInterval(((0,24),)),
+ active=models.SpecificInterval(((0., 24.),)),
air_exch=0.25,
),
infected=mc.InfectedPopulation(
number=1,
virus=virus_distributions['SARS_CoV_2_B117'],
- presence=mc.SpecificInterval(((0, 2),)),
+ presence=mc.SpecificInterval(((0., 2.),)),
mask=models.Mask.types["No mask"],
activity=activity_distributions['Seated'],
expiration=models.MultipleExpiration(
@@ -215,7 +215,7 @@ def skagit_chorale_mc():
infected=mc.InfectedPopulation(
number=1,
virus=virus_distributions['SARS_CoV_2'],
- presence=mc.SpecificInterval(((0, 2.5),)),
+ presence=mc.SpecificInterval(((0., 2.5),)),
mask=models.Mask.types["No mask"],
activity=activity_distributions['Light activity'],
expiration=models.Expiration((5., 5., 5.)),
@@ -261,10 +261,10 @@ def test_report_models(mc_model, expected_pi, expected_new_cases,
@pytest.mark.parametrize(
"mask_type, month, expected_pi, expected_dose, expected_ER",
[
- ["No mask", "7", 30.0, 405.84, 3894],
- ["Type I", "7", 10.2, 73.38, 702],
- ["FFP2", "7", 4.0, 73.38, 702],
- ["Type I", "2", 4.25, 21.42, 702],
+ ["No mask", "Jul", 30.0, 405.84, 3894],
+ ["Type I", "Jul", 10.2, 73.38, 702],
+ ["FFP2", "Jul", 4.0, 73.38, 702],
+ ["Type I", "Feb", 4.25, 21.42, 702],
],
)
def test_small_shared_office_Geneva(mask_type, month, expected_pi,
@@ -274,13 +274,13 @@ def test_small_shared_office_Geneva(mask_type, month, expected_pi,
ventilation=models.MultipleVentilation(
(
models.SlidingWindow(
- active=models.SpecificInterval(((0,24),)),
- inside_temp=models.PiecewiseConstant((0, 24), (293,)),
- outside_temp=data.Temperatures[month],
+ active=models.SpecificInterval(((0., 24.),)),
+ inside_temp=models.PiecewiseConstant((0., 24.), (293,)),
+ outside_temp=data.GenevaTemperatures[month],
window_height=1.5, opening_length=0.2,
),
models.AirChange(
- active=models.SpecificInterval(((0,24),)),
+ active=models.SpecificInterval(((0., 24.),)),
air_exch=0.25,
),
),
@@ -288,7 +288,7 @@ def test_small_shared_office_Geneva(mask_type, month, expected_pi,
infected=mc.InfectedPopulation(
number=1,
virus=virus_distributions['SARS_CoV_2_B117'],
- presence=mc.SpecificInterval(((9, 10+2/3), (10+5/6, 12.5), (13.5, 15+2/3), (15+5/6, 18))),
+ presence=mc.SpecificInterval(((9., 10+2/3), (10+5/6, 12.5), (13.5, 15+2/3), (15+5/6, 18.))),
mask=models.Mask.types[mask_type],
activity=activity_distributions['Seated'],
expiration=models.MultipleExpiration(