{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":61461,"databundleVersionId":6756046,"sourceType":"competition"},{"sourceId":7042004,"sourceType":"datasetVersion","datasetId":4051694}],"dockerImageVersionId":30558,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Campus Smart Room Booking System - UniReserve Tech\n\n## Group Members\n1. ALVIS GWA KAI JIE (A0252564A)\n2. CHONG YING TONG (A0223329J)\n3. ERIC POH WEI KIAT (A0253176A)\n4. FERANDRA TIODORA (A0271283E)\n5. RYAN CHIA ZHI HAO (A0253439Y)\n6. TIO YU KUN (A0253254J)\n\n## Table of Content\n* [1. Introduction](#Introduction)\n* [2. Overview](#Overview)\n* [3. Analysis on Dataset](#Analysis)\n    * [3.1 Reading Data](#Read_data)\n    * [3.2 Data Pre-processing](#Data_pre-processing)\n    * [3.3 Analysis with visual representation](#visual_rep)\n* [4. Interpretation basaed on Dataset Analysis](#Interpretation)\n* [5. UniReserve Tech Application](#App)\n* [6. Conclusion](#Conclusion)\n* [7. References](#References)","metadata":{}},{"cell_type":"markdown","source":"<a id=\"Introduction\"></a>\n# 1. Introduction\n","metadata":{}},{"cell_type":"code","source":"from IPython.display import Image, display\n\n# Specify the path to your image\nimage_path = \"/kaggle/input/appphoto/logo.png\"\n\n# Display the image\ndisplay(Image(filename=image_path))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-11-24T11:28:12.682676Z","iopub.execute_input":"2023-11-24T11:28:12.683163Z","iopub.status.idle":"2023-11-24T11:28:12.741994Z","shell.execute_reply.started":"2023-11-24T11:28:12.683128Z","shell.execute_reply":"2023-11-24T11:28:12.740864Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n<u>**Company Background, Mission and Vision**</u><br>\n<p style=\"text-align: justify;\">UniReserve Tech is on a mission to improve the university experience by bringing intelligence and efficiency to campus spaces. We envision smart and sustainable campuses that serve as optimal hubs for learning, collaboration, and productivity. This commitment underlines our dedication to transforming educational environments.</p><br><br>\n    \n<u>**The Problem at Hand: Underutilized Rooms and Low Productivity**</u><br>\n<p style=\"text-align: justify;\">The underutilization of rooms and the resulting decrease in productivity stem from a multifaceted problem exacerbated by environmental and urbanization factors. In recent years, the global issue of climate change has taken center stage, impacting regions like Singapore, situated on the equator, with a discernible rise in temperatures due to its tropical climate. The urbanization trend in Singapore has further contributed to this thermal discomfort, evidenced by a temperature increase of 0.25 degrees Celsius every decade over a 60-year period. Despite these challenges, government schools across the island have refrained from adopting air-conditioning solutions due to their exorbitant costs. Consequently, classrooms continue to depend on natural ventilation and mechanical fans, resulting in lower thermal comfort levels. Studies have shown a correlation between insufficient ventilation, unfavorable heat conditions, and a decline in pupils' learning performance.</p><br><br>\n<p style=\"text-align: justify;\">Understanding the relationship between thermal control and classroom productivity is essential. Research indicates that increasing the rate of air exchange in a place can reduce dissatisfaction with temperature conditions. Furthermore, there is an established inverse relationship between thermal comfort in classrooms and students' performance on psychological tests measuring response time and vigilance. Insufficient ventilation rates in classrooms have been shown to significantly impair concentration and attentiveness, emphasizing the critical role of thermal conditions in learning environments.</p><br><br>\n<p style=\"text-align: justify;\">This challenge is not unique to Singapore but resonates globally within university settings. The underutilization of spaces in universities represents a shared obstacle that diminishes productivity as students and staff seek alternative environments. Acknowledging this pervasive issue inhibiting the full potential of educational institutions, our proposed room booking solution emerges as a strategic response. Beyond optimizing spatial use, our solution is tailored to elevate the overall campus experience. By addressing the global and local challenges impacting thermal comfort and spatial efficiency, our approach aims to create an environment where every room serves as a catalyst for enhanced learning, collaboration, and productivity.</p><br><br>\n\n<u>**Thermal Comfort Regulation in Singapore SS 553-(incl Amd 2):2016 Code of Practice**</u><br>\n<p style=\"text-align: justify;\">The regulation of thermal comfort in Singapore is governed by SS 553-(incl Amd 2):2016, which establishes an acceptance limit of 24 to 25 degrees. This range aligns with ASHRAE standards (23 - 25.5 degrees) but factors in Singapore's hot and humid climate, allowing for a slightly warmer and more humid acceptable range. Recognizing these standards is crucial as they directly influence the design and operation of air conditioning and mechanical ventilation systems in buildings, impacting the overall thermal conditions experienced by occupants.</p><br><br>\n\n<u>**Revolutionizing Room Booking: Enhancing the Campus Experience**</u><br>\n<p style=\"text-align: justify;\">Our proposed solution represents a paradigm shift in room reservation, integrating considerations for thermal comfort and noise levels through the application of AI and machine learning. Beyond booking facilitation, our system actively engages with the built environment. By harnessing data from the Cozie Apple platform, we gain insights into air temperature, relative humidity, and noise, enabling the prediction and control of room conditions. The result is an optimized environment aligned with users' preferences and needs.</p><br><br>\n\n<u>**Purpose of the Study**</u><br>\n<p style=\"text-align: justify;\">This Kaggle notebook serves as a comprehensive guide to the development, implementation, and impact assessment of our innovative room reservation system. From detailed data cleaning and visualization to model training intricacies, each step reflects our commitment to transparency and excellence. The purpose extends beyond technical details; it is about reshaping the future of university campuses, fostering a culture of productivity, and creating an environment where every room serves as a catalyst for success. \n</p>","metadata":{}},{"cell_type":"markdown","source":"<a id=\"Overview\"></a>\n# 2. Overview\n<p style=\"text-align: justify;\">The primary challenge identified at the National University of Singapore (NUS) campus is the underutilization of certain spaces, leading to overcrowding in popular study areas and an inefficient use of available space. To address this, data collected through the Cozie app is being analyzed to determine the ideal thermal conditions for optimal study environments for students. This analysis aims to enhance thermal comfort, a key factor in creating conducive study spaces. The insights gained from this data will be integrated into a new app, designed to revolutionize the space booking system at NUS. This innovative approach will not only improve thermal comfort for students but also optimize the usage of campus spaces, ensuring a more balanced and effective allocation of study areas.</p>\n","metadata":{}},{"cell_type":"markdown","source":"<table>\n    <tr>\n        <th>Prediction</th>\n        <th colspan=\"2\">Judgement</th>\n        <th>Action</th>\n    </tr>\n    <tr>\n        <td>Predict the air temperature that will be thermal comfortable within University occupant </td>\n        <td colspan=\"2\">Determine whether the temperature should adjust based on the outdoor air temperature or based on maximum occupancy load in the theater. Factors requiring human judgment to refine predictions and optimize outcomes include:<br>\n1. The Building Material<br>\n2. The Clothing Insulation of room occupiers<br>\n3. The current ASHRAE recommended temperature against BCA green mark requirement<br>\n4. The design of the installed air con in the room.\n5. Human             \n</td>\n        <td>System actions include facilitating proper room bookings, providing suggestions, controlling real-time adjustments, and interfacing with the building management system to optimize air conditioning based on bookings.</td>\n    <td></td> \n    </tr>\n    <tr>\n        <th>Input</th>\n        <th>Training</th>\n        <th>Feedback</th>\n        <th>Outcome</th>\n    </tr>\n    <tr>\n        <td>The desired outcome is a 20% increase in space utilization</td>\n        <td>Air Temeprature<br>Humidity<br>Location</td>\n        <td>Air Temeprature<br>Humidity<br>Location</td>\n        <td>Updating every semester on room occupancy rates. Mitigating actions include adjusting air conditioning design based on feedback to optimize supply and return in rooms.</td>\n    </tr>\n</table>","metadata":{}},{"cell_type":"markdown","source":"<u>**Data collection Process**</u><br>\n<p style=\"text-align: justify;\">To facilitate the data collection process, we have recruited 48 volunteers, consisting of both students and faculty staff, to gather data around NUS. </p>\n\n<p style=\"text-align: justify;\">Of our 48 volunteers, half of them are male and the other half are female. Furthermore, 40 of our volunteers are students and the rest are faculty staff. Out of our 40 student volunteers, 21 of them are staying on campus and the remaining 19 will commute daily to and fro campus.</p>\n\n<p style=\"text-align: justify;\">As mentioned above, we will primarily be using the Cozie application on the Apple Smartwatch to gather and consolidate the data. The 4 different variables we will be looking at for the purposes of this experiment will be:\n1. Air temperature\n2. Humidity\n3. Location, which is split into office, class, or on transportation\n4. The latitude and longitude of the participant is also recorded at this stage.\n    \n\n<p style=\"text-align: justify;\">For the purposes of this experiment, we will only be honing in on the data collected by the participants when they are in the vicinity of NUS . The main data collection method we will employ is to get our research participants to do a short survey on the Cozie application at random intervals, or until the participant changes their location. </p>\n    \n<p style=\"text-align: justify;\">These participants will carry out their routine university activities, such as going for lectures or studying/doing work in a classroom or office, while simultaneously gathering experimental data to investigate the impact of the collected variables on the participant’s productivity. The ultimate goal is to derive valuable information for NUS to develop a better room booking system that takes into account the user’s thermal comfort and noise comfort so as to increase overall productivity.\n</p>\n\n    \n<u>**Interpretation of data**</u><br>\n<p style=\"text-align: justify;\">\n    In order to interpret our collected data, we will be extracting the data into an excel file which we will then proceed to upload onto the Kaggle platform where, using the Pandas, Matplotlib and Seaborn libraries, we will generate useful graphs such as line graphs, scatterplots and heatmaps, to name a few. Using these graphs, we will further determine if there are any correlations between the variables and the participant’s recorded level of productivity.</p>\n    \n<p style=\"text-align: justify;\">Examples of correlations can be the higher the recorded air temperature, the lower the recorded productivity. From this simple hypothetical observation, we will be able to infer that the hotter a room is, due to the lack of proper ventilation or air conditioning, the occupant’s productivity will be lower as well due to an inability to focus.</p>\n    \n<p style=\"text-align: justify;\">Another example of a possible correlation can be for locations that are recorded as outdoors based on the latitude and longitude, the higher the recorded noise level, and therefore, the lower the recorded level of productivity due to the presence of distractions that prevent the participant from concentrating.</p>\n\n<u>**Prediction**</u><br>\n<p style=\"text-align: justify;\">\n    We are looking to predict the ideal level of thermal comfort for individuals to make use of the underutilized spaces on campus by using a multitude of data collected around school campus such as thermal comfort and humidity<br>\n    </p>\n\n<u>**Judgement**</u><br>\n<p style=\"text-align: justify;\">\n    Thermal comfort and humidity are significant determiners in creating a comfortable campus for students to study at. However, a multitude of other factors may contribute to the underutilization of spaces around the campus. These factors extend beyond environmental considerations to include practical elements that influence the decision to use or avoid particular spaces. For instance, the level of equipment and amenities available for studying is crucial. Take, for example, the spaces like ER4 and ER5 in SDE, which are equipped with chairs and tables for studying. Despite these amenities, the absence of power sockets can deter individuals from utilizing these spaces, particularly when dealing with a dying laptop or tablet. These are precisely the kind of nuanced factors that demand careful consideration when evaluating the feasibility of advancing our revolutionized booking solution. <br><br>\n    In the assessment of spaces, it is vital to acknowledge the diverse needs and preferences of students and faculty. Beyond the physical attributes of a space, factors like lighting, acoustics, and overall ambiance contribute significantly to the perceived comfort and usability. Additionally, understanding the preferences of the university community regarding collaborative or quiet spaces is essential for creating an inclusive and effective room reservation system. By factoring in these varied elements, our booking solution can better align with the dynamic requirements of users, thereby enhancing its overall effectiveness in optimizing campus spaces.\n    </p>\n\n<u>**Action**</u><br>\n<p style=\"text-align: justify;\">\n    Our innovative room reservation system engages in several strategic actions to ensure the efficient utilization of university spaces and the enhancement of the overall campus experience. Firstly, the system facilitates proper room bookings by employing advanced algorithms that match users with their preferred spaces. Much like popular e-commerce platforms offering tailored recommendations, our system suggests suitable spaces, taking into account various user preferences, such as ambient conditions, amenities, and spatial requirements.<br><br>\nBeyond mere facilitation, our system actively controls the environment based on predictive analytics. It interfaces with the building management system to optimize the usage of resources, such as turning on air conditioning half an hour early if a room is booked for a lecture. This proactive approach not only contributes to the comfort of occupants but also aligns with sustainability goals by optimizing energy usage.<br><br>\nMoreover, the system is designed to seamlessly link with the Cozie Apple platform, providing real-time data on air temperature, relative humidity, and noise levels. By harnessing this data, the system continuously adapts to changing environmental conditions, ensuring that room conditions remain aligned with users' preferences and needs.</p>\n\n<u>**Outcome**</u><br>\n<p style=\"text-align: justify;\">\n    The objective is to determine the optimal interior air temperature for University areas, namely within the designated time slots that have been booked by the end user. Consequently, the university administration can analyze the occupancy rate and the specific types of usage, such as tutorials, lectures, or discussion rooms, that are commonly used.  Furthermore, it can provide recommendations on user booking behaviors for selecting the appropriate room type, as well as utilize the obtained data for design and space planning purposes.  With all the recommendations and analysis to get, we are able to increase the booking by 20% to suit the end user suitability to use the facilities. </p>\n\n<u>**Input**</u><br>\n<p style=\"text-align: justify;\">\n    The input data for the predicate algorithm include location, air temperature, and relative humidity. Firstly, the input of the location is necessary as it enables us to concentrate on a more precise area, based on the information provided to us. In this case, we are using the areas of NUS for this study. Next, the air temperature will be measured using a weather station to accurately record the variations in temperature throughout the day. Additionally, the humidity level will be checked to ensure compliance with the SS553:2016 standard, which requires a humidity level below 70% in the room where the mechanical ventilation system is present. </p>\n\n<u>**Training**</u><br>\n<p style=\"text-align: justify;\">Our primary focus during the training phase centers on NUS, where we meticulously assess the elements influencing indoor temperature and the level of comfort experienced by both students and faculty. The impact of indoor air temperature, spatial building design, and occupancy on the entire environment is the primary focus of our evaluation. \"(Feng et al.)  This evaluation requires an understanding of how temperature and relative humidity affect people, with particular attention paid to the population density in the locations where indoor air temperatures would peak and drop. </p>\n\n<u>**Feedback**</u><br>\n<p style=\"text-align: justify;\">\n    Our research has revealed discernible patterns of behavior and objectives among the different categories of individuals who book spaces in NUS. We want to monitor these alterations on a semesterly basis in order to make appropriate adjustments to the HVAC system. In order to meet the SS553:2016 humidity criteria for air conditioning and mechanical ventilation in buildings, it is essential to ensure that the comfort and productivity of the inhabitants are not impacted in any manner. <br><br>\n    Nevertheless, we acknowledge the existence of certain subjective factors that need to be considered. The construction materials used should be dense, have strong thermal insulation, and be of a light colour (Pal et al., \"What Materials Keep Buildings Cool?\"). Furthermore, the factors to consider include the attire of individuals, the arrangement of seating in the area, and the occupants' environmental preferences throughout various activities during the day.   Moreover, it is important to assess if the present ASHRAE criterion aligns with the BCA greenmark highest standard, namely in achieving netzero energy use during the air conditioning planning and installation phase. When creating a venue that caters to a diverse group of individuals, it is crucial to consider their nuanced tastes. </p>\n\n","metadata":{}},{"cell_type":"markdown","source":"<a id=\"Analysis\"></a>\n# 3. Analysis on Dataset\n<a id=\"Read_data\"></a>\n## 3.1 Reading data","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotly.graph_objects as go\nimport math\n\nfrom math import cos, asin, sqrt, pi","metadata":{"executionInfo":{"elapsed":36755,"status":"ok","timestamp":1691039448204,"user":{"displayName":"BUDS Lab Team Member","userId":"04037643885455272587"},"user_tz":-480},"id":"IUuDaG7zh_Tv","outputId":"020ca595-e284-4ac4-83aa-b838bb0a46c3","execution":{"iopub.status.busy":"2023-11-24T11:28:12.744104Z","iopub.execute_input":"2023-11-24T11:28:12.745067Z","iopub.status.idle":"2023-11-24T11:28:12.750520Z","shell.execute_reply.started":"2023-11-24T11:28:12.745023Z","shell.execute_reply":"2023-11-24T11:28:12.749547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = pd.read_csv('/kaggle/input/IPM3211-City-Heat-Noise/5_xesh_split_ipm_train.csv', index_col=[0], keep_default_na=False, na_values=[''], parse_dates=['time', 'ws_timestamp_location', 'ws_timestamp_start'], date_format='%Y-%m-%d %H:%M:%S.%f%z')\ndf_solution = pd.read_csv('/kaggle/input/IPM3211-City-Heat-Noise/5_xesh_split_ipm_test_public.csv', index_col=[0], keep_default_na=False, na_values=[''], parse_dates=['time', 'ws_timestamp_location', 'ws_timestamp_start'], date_format='%Y-%m-%d %H:%M:%S.%f%z')\ndf_rain = pd.read_csv('/kaggle/input/IPM3211-City-Heat-Noise/3_weather_rainfall_processed.csv', parse_dates=True, index_col=[0])\ndf_temperature = pd.read_csv('/kaggle/input/IPM3211-City-Heat-Noise/3_weather_air-temperature_processed.csv', parse_dates=True, index_col=[0])\ndf_humidity = pd.read_csv('/kaggle/input/IPM3211-City-Heat-Noise/3_weather_relative-humidity_processed.csv', parse_dates=True, index_col=[0])\ndf_wind_speed = pd.read_csv('/kaggle/input/IPM3211-City-Heat-Noise/3_weather_wind-speed_processed.csv', parse_dates=True, index_col=[0])\ndf_wind_direction = pd.read_csv('/kaggle/input/IPM3211-City-Heat-Noise/3_weather_wind-direction_processed.csv', parse_dates=True, index_col=[0])\ndf_stations = pd.read_csv('/kaggle/input/IPM3211-City-Heat-Noise/3_weather_stations.csv').drop(columns=['Unnamed: 0'])","metadata":{"executionInfo":{"elapsed":10680,"status":"ok","timestamp":1691040022955,"user":{"displayName":"BUDS Lab Team Member","userId":"04037643885455272587"},"user_tz":-480},"id":"Xiq5v84MixpP","execution":{"iopub.status.busy":"2023-11-24T11:28:12.751890Z","iopub.execute_input":"2023-11-24T11:28:12.752498Z","iopub.status.idle":"2023-11-24T11:29:43.728760Z","shell.execute_reply.started":"2023-11-24T11:28:12.752467Z","shell.execute_reply":"2023-11-24T11:29:43.727413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"Data_pre-processing\"></a>\n## 3.2 Data pre-processing\n","metadata":{}},{"cell_type":"code","source":"# Survey responses only last until Jan 21, 2023, while the weather data lasts until July 3, 2023.\n# Filter out data that is beyond Jan 21, 2023\ndf_rain = df_rain[df_rain.index<'2023-01-22']\ndf_temperature = df_temperature[df_temperature.index<'2023-01-22']\ndf_humidity = df_humidity[df_humidity.index<'2023-01-22']\ndf_wind_speed = df_wind_speed[df_wind_speed.index<'2023-01-22']\ndf_wind_direction = df_wind_direction[df_wind_direction.index<'2023-01-22']\n\n# No Temperature data available before Jan 21, 2023. Hence remove the column\ndf_temperature = df_temperature.drop(columns=['S117'])\n\n# Resample data hourly due to large dataframe\n# Resample weather data\ndf_temperature_average = df_temperature.resample('60min').mean()\ndf_rain_sum = df_rain.resample('60min').sum() # note: for rain the data is aggregated with a sum instead of the mean\ndf_humidity_average = df_humidity.resample('60min').mean()\ndf_wind_speed_average = df_wind_speed.resample('60min').mean()\ndf_wind_direction_average = df_wind_direction.resample('60min').mean()\n\n# Check size of resulting dataframe\ndf_temperature_average.shape\n\n# Map watch survey questions to question ID\nws_questions = {\"q_noise_nearby\": \"Noise distractions nearby? (without earphones)\",\n                \"q_noise_kind\": \"What kind of noise?\",\n                \"q_earphones\": \"Wearing earphones?\",\n                \"q_thermal_preference\": \"Thermally, what do you prefer now?\",\n                \"q_location\": \"Where are you?\",\n                \"q_location_office\": \"What kind of office?\",\n                \"q_location_transport\": \"What kind of transport?\",\n                \"q_alone_group\": \"Alone or in a group?\",\n                \"q_activity_category_alone\": \"Category of activity? (alone)\",\n                \"q_activity_category_group\": \"Category of activity? (group)\"}\n\n# Combining all dataframe into 1\ndf_train['source']='train'\ndf_solution['source']='solution'\ndf_all = pd.concat([df_train, df_solution])\n\n# Function to resample health data at the timestamps of watch survey responses.\ndef resample_health(df, col_name, col_name_new):\n    df[col_name_new] = df[col_name].interpolate(method='nearest').bfill().ffill().mask(df['ws_survey_count'].isna())\n    return df\n\n# Resample health data\ndf_all = df_all.groupby('id_participant').apply(resample_health, col_name='ts_heart_rate', col_name_new='ws_heart_rate').reset_index(level=[0], drop=True)\ndf_all = df_all.groupby('id_participant').apply(resample_health, col_name='ts_audio_exposure_environment', col_name_new='ws_audio_exposure_environment').reset_index(level=[0], drop=True)\ndf_all = df_all.groupby('id_participant').apply(resample_health, col_name='ts_oxygen_saturation', col_name_new='ws_oxygen_saturation').reset_index(level=[0], drop=True)\ndf_all = df_all.groupby('id_participant').apply(resample_health, col_name='ts_resting_heart_rate', col_name_new='ws_resting_heart_rate').reset_index(level=[0], drop=True)\ndf_all = df_all.groupby('id_participant').apply(resample_health, col_name='ts_stand_time', col_name_new='ws_stand_time').reset_index(level=[0], drop=True)\ndf_all = df_all.groupby('id_participant').apply(resample_health, col_name='ts_step_count', col_name_new='ws_step_count').reset_index(level=[0], drop=True)\ndf_all = df_all.groupby('id_participant').apply(resample_health, col_name='ts_walking_distance', col_name_new='ws_walking_distance').reset_index(level=[0], drop=True)\n\n# Function to get weather data for a given timestamp and location from the nearest weather station\ndef get_weather_data(df_weather_data, lat, lon, timestamp):    \n    # Get timestamp with no seconds or microseconds\n    timestamp = timestamp.replace(second=0, microsecond=0)\n    \n    # Get weather data for timestamp above\n    weather_data_row = df_weather_data[df_weather_data.index == timestamp]\n\n    # If no weather data is available for timestamp above, get weather data for next minute\n    if (weather_data_row.empty):\n        timestamp = timestamp + pd.Timedelta(minutes=1)\n        weather_data_row = df_weather_data[df_weather_data.index == timestamp]\n        # If there is still no weather data available, return NaN\n        if (weather_data_row.empty):\n            return np.NaN\n\n    # Get weather station ids from weather stations with with data\n    station_ids_with_data = weather_data_row.columns[weather_data_row.count() > 0].tolist()\n\n    # Get weather stations with data\n    df_stations2 = df_stations[df_stations.id.isin(station_ids_with_data)]\n\n    # Compute distance to each weather station\n    df_stations2['distance'] = df_stations2.apply(lambda x: distance(x['latitude'], x['longitude'], lat, lon), axis=1)\n\n    # Get nearest weather station\n    station_id_nearest = df_stations2[df_stations2.distance==df_stations2.distance.min()].id.values[0]\n\n    # Retrun NaN for cases where the nearest weather station is more than 10km away\n    if df_stations2.distance.min()>10:\n        return np.NaN\n\n    # Return weather data from nearest weather station\n    return weather_data_row[station_id_nearest].values[0]\n\n# Function to compute distnace on spherical earth\ndef distance(lat1, lon1, lat2, lon2):\n    r = 6371 # km\n    p = pi / 180\n\n    a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p) * cos(lat2*p) * (1-cos((lon2-lon1)*p))/2\n    return 2 * r * asin(sqrt(a))\n\n# Apply above function to the dataset for all weather data\ndf_all['ws_rainfall'] = df_all[df_all.ws_survey_count.notna()].apply(lambda row: get_weather_data(df_rain, row['ws_latitude'], row['ws_longitude'], row.name), axis=1)\ndf_all['ws_air_temperature'] = df_all[df_all.ws_survey_count.notna()].apply(lambda row: get_weather_data(df_temperature, row['ws_latitude'], row['ws_longitude'], row.name), axis=1)\ndf_all['ws_relative_humidity'] = df_all[df_all.ws_survey_count.notna()].apply(lambda row: get_weather_data(df_humidity, row['ws_latitude'], row['ws_longitude'], row.name), axis=1)\ndf_all['ws_wind_speed'] = df_all[df_all.ws_survey_count.notna()].apply(lambda row: get_weather_data(df_wind_speed, row['ws_latitude'], row['ws_longitude'], row.name), axis=1)\ndf_all['ws_wind_direction'] = df_all[df_all.ws_survey_count.notna()].apply(lambda row: get_weather_data(df_wind_direction, row['ws_latitude'], row['ws_longitude'], row.name), axis=1)\n\n# Remove all rows that are not a watch surve response\ndf_all = df_all[df_all.ws_survey_count.notna()]\n\n# Remove some timestamp columns\ndf_all = df_all.drop(columns=['ws_timestamp_location', 'ws_timestamp_start'])\n\n# Remove columns of the original health data those are no longer needed since we are going to use the interpolated values\ndf_all = df_all.drop(columns=['ts_heart_rate',\n                              'ts_audio_exposure_environment',\n                              'ts_oxygen_saturation',\n                              'ts_resting_heart_rate',\n                              'ts_stand_time', \n                              'ts_step_count',\n                              'ts_walking_distance','q_alone_group','q_location_transport','ws_rainfall','ws_walking_distance','ws_step_count','ws_stand_time','ws_oxygen_saturation','ws_audio_exposure_environment','id_unique','Visual Complexity Mean','Visual Complexity Stdev','Visual Complexity Mean'])\n# Define the latitude and longitude ranges for filtering\nmin_lat = 1.292\nmax_lat = 1.3058\nmin_lon = 103.76\nmax_lon = 103.78\n\n# Filtering the DataFrame based on latitude and longitude ranges\ndf_all = df_all[\n    (df_all['ws_latitude'] >= min_lat) & (df_all['ws_latitude'] <= max_lat) &\n    (df_all['ws_longitude'] >= min_lon) & (df_all['ws_longitude'] <= max_lon)\n]\n\n# Data Cleaning - Break RH into categorial data\ndf_all.index = pd.to_datetime(df_all.index)\n\n# Define the bin edges\nbin_edges = [0, 50, 70, 90, 100]\n\n# Define the bin labels\nbin_labels = ['Low', 'Moderate', 'High', 'Very High']\n\n# Create a new column 'humidity_category' with the bin labels\ndf_all['humidity_category'] = pd.cut(df_all['ws_relative_humidity'], bins=bin_edges, labels=bin_labels)\n\n# Data Cleaning - Break Temperature into categorial data\n# Define the bin edges\nbin_edges = [0, 24, 26, 28, 30, 32, 34]\n\n# Define the bin labels\nbin_labels = ['<24', '24-26', '26-28', '28-30','30-32', '32-34']\n\n# Create a new column 'humidity_category' with the bin labels\ndf_all['temperature_category'] = pd.cut(df_all['ws_air_temperature'], bins=bin_edges, labels=bin_labels)\n\n# Filter out rows where q_location is either \"Transportation\" or \"Home\"\nfiltered_df = df_all.query('q_location not in [\"Transportation\", \"Indoor - Home\"]')\n","metadata":{"execution":{"iopub.status.busy":"2023-11-24T11:29:43.731279Z","iopub.execute_input":"2023-11-24T11:29:43.732251Z","iopub.status.idle":"2023-11-24T11:30:41.475411Z","shell.execute_reply.started":"2023-11-24T11:29:43.732218Z","shell.execute_reply":"2023-11-24T11:30:41.474069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"visual_rep\"></a>\n## 3.3 Analysis with visual representation","metadata":{}},{"cell_type":"code","source":"## Temperature & Thermal Preference heatmap\n# Filter relevant columns\nheatmap_data = filtered_df[['temperature_category', 'q_thermal_preference']]\n\n# Create a crosstab to get counts\nheatmap_data_cross = pd.crosstab(heatmap_data['q_thermal_preference'], heatmap_data['temperature_category'], normalize='index')\n\n# Create a square heatmap\nplt.figure(figsize=(12, 8))\nsns.heatmap(heatmap_data_cross, cmap='Reds', annot=True, fmt=\".2%\", linewidths=.5, cbar=False)\nplt.title('Proportion of Thermal Preference by Temperature Category')\nplt.xlabel('Temperature Category')\nplt.ylabel('Thermal Preference')\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-11-24T11:30:41.477163Z","iopub.execute_input":"2023-11-24T11:30:41.477530Z","iopub.status.idle":"2023-11-24T11:30:41.860744Z","shell.execute_reply.started":"2023-11-24T11:30:41.477494Z","shell.execute_reply":"2023-11-24T11:30:41.859487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<p style=\"text-align: justify;\">The data from NUS presents a compelling case for the ideal study temperature: students have voiced a strong preference for a cooler climate within the sweet spot of 28-30 degrees Celsius. This range emerges as the comfort epicenter, with nearly half of the respondents content with no temperature change and a majority seeking cooler conditions as temperatures climb. The call for warm surfaces only when the mercury dips below this favored zone. Thus, setting the campus's HVAC systems to hover around this thermal median promises an environment that's not just intellectually stimulating but also physically agreeable, creating a universally comfortable academic oasis for all. \n     <br><br>To develop an effective HVAC system for optimal thermal comfort, it is suggested to implement an adaptive system that adjusts temperatures based on real-time monitoring and user preferences. This system could offer personalized settings, accommodate varying preferences at different times of the day, and balance individual comfort with energy efficiency considerations. Continuous data collection and user feedback will be crucial for refining and improving the system over time. Furthermore, another possible suggestion is to include occupancy counter sensors in the rooms located at SDE3 so that the air conditioning systems will automatically drop to a lower temperature once it senses that there are a predetermined number of people in the room.\n</p>\n","metadata":{}},{"cell_type":"code","source":"## Location & Temperature\n# Filter relevant columns\nheatmap_data = filtered_df[['q_location', 'temperature_category']]\n\n# Create a crosstab to get counts\nheatmap_data_cross = pd.crosstab(heatmap_data['q_location'], heatmap_data['temperature_category'], margins=True, margins_name=\"Total\", normalize='index')\n\n# Create a heatmap with red color for warmer places\nplt.figure(figsize=(12, 8))\nsns.heatmap(heatmap_data_cross, cmap='Reds', annot=True, fmt=\".2%\", linewidths=.5, cbar=False)\nplt.title('Proportion of Temperature Category by Location')\nplt.xlabel('Temperature Category')\nplt.ylabel('Location')\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-11-24T11:30:41.862140Z","iopub.execute_input":"2023-11-24T11:30:41.862470Z","iopub.status.idle":"2023-11-24T11:30:42.320495Z","shell.execute_reply.started":"2023-11-24T11:30:41.862442Z","shell.execute_reply":"2023-11-24T11:30:42.319382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<p style=\"text-align: justify;\">\n    At the National University of Singapore, a comfortable and conducive study environment is paramount. Data analysis reveals a clear preference among students for a temperature range of 28-30 degrees Celsius across various indoor settings, including classrooms, offices, and miscellaneous indoor locations. To align with these findings, a multipronged approach to thermal comfort is proposed: First, a standardization of air conditioning systems to maintain temperatures within the favored range; second, the establishment of customizable temperature zones catering to individual preferences; third, the installation of smart thermostats for dynamic, occupancy-based temperature control; and fourth, the development of an interactive feedback system within a **dedicated app to monitor** and respond to student comfort levels in real time. Additionally, a campaign to guide students on personal temperature regulation practices will be launched, ensuring that every student can find their own comfort zone. These concerted efforts aim not just to optimize thermal conditions but also to bolster academic performance and enhance the overall campus experience at NUS.\n    </p>\n","metadata":{}},{"cell_type":"code","source":"import folium\nfrom folium.plugins import HeatMap\n\nmap_center = [filtered_df['ws_latitude'].mean(), filtered_df['ws_longitude'].mean()]\nmy_map = folium.Map(location=map_center, zoom_start=15)\n\n# Add markers for each data point\nfor index, row in filtered_df.iterrows():\n    folium.CircleMarker(location=[row['ws_latitude'], row['ws_longitude']], \n                       popup=row['q_location'],\n                       radius = 5,\n                       color='blue',\n                       fill=True,\n                       fill_color='blue',\n                       fill_opacity=0.6\n                      ).add_to(my_map)\n\nmy_map","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-11-24T11:30:42.322171Z","iopub.execute_input":"2023-11-24T11:30:42.322654Z","iopub.status.idle":"2023-11-24T11:30:42.878169Z","shell.execute_reply.started":"2023-11-24T11:30:42.322618Z","shell.execute_reply":"2023-11-24T11:30:42.877007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"In order to optimize our solution's efficacy, we have implemented a robust data filtering mechanism centered around the geographical location of the National University of Singapore (NUS) campus. Recognizing the unique scope of our target audience within the NUS community, this strategic approach ensures precision and relevance in delivering our services.\n\nBy honing in on specific geographic coordinates encompassing the NUS campus, we meticulously filter data points to tailor our solution to the thermal preferences of individuals within this academic community. This geographically-tailored filtration not only enhances the user experience but also optimizes the overall functionality of our solution within the designated area.\n\nOur commitment to providing a seamless and contextually relevant experience is reflected in the meticulous process of location-based data curation. As a result, users within the NUS campus can expect a solution finely tuned to their specific environment, fostering a more personalized and efficient engagement with our platform. This strategic focus on location-based filtering solidifies our dedication to meeting the unique requirements of the NUS community, setting our solution apart in its ability to address the intricacies of campus life.\n","metadata":{}},{"cell_type":"code","source":"# Set the style for seaborn\nsns.set(style=\"whitegrid\")\n\n# Filter out NaN values in columns used for the plot\ncols_for_plot = ['q_location', 'q_thermal_preference', 'ws_relative_humidity']\ndf_all_cleaned = filtered_df[cols_for_plot].dropna()\n\n# Plotting a box plot\nplt.figure(figsize=(12, 6))\nsns.boxplot(x='q_location', y='ws_relative_humidity', hue='q_thermal_preference', data=df_all_cleaned)\nplt.title('Box Plot of Relative Humidity by Location and Thermal Preference')\nplt.xlabel('Location')\nplt.ylabel('Relative Humidity (%)')\nplt.show()\n","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-11-24T11:30:42.882722Z","iopub.execute_input":"2023-11-24T11:30:42.883107Z","iopub.status.idle":"2023-11-24T11:30:43.509720Z","shell.execute_reply.started":"2023-11-24T11:30:42.883075Z","shell.execute_reply":"2023-11-24T11:30:43.508529Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<p style=\"text-align: justify;\">\n    This box plot reveals insights into students' humidity preferences at NUS, paralleled with their desired thermal settings. There's a notable variation in the humidity levels that align with students' satisfaction with current temperatures in both indoor offices and classrooms, indicating a flexible acceptance of the status quo. On the flip side, a preference for cooler temperatures tends to coincide with higher humidity, hinting that students might seek a chillier ambiance when the air feels more saturated. Outdoors, a yearning for warmth tends to match up with drier conditions, possibly reflecting a sensation of coolness in less humid air. At home, a concentrated preference for maintaining existing conditions suggests that students perceive their domestic spaces to be comfortably balanced. Recognizing the interplay between temperature and humidity is crucial for NUS to foster optimal study and living spaces. Adjusting climate controls to manage these elements could greatly improve student comfort and contentment in different campus settings.\n</p>","metadata":{}},{"cell_type":"markdown","source":"<a id=\"Interpretation\"></a>\n# 4.Interpretation based on Dataset Analysis\n<p style=\"text-align: justify;\">\n    The dataset analysis serves as a dynamic guide, enriching each phase of our system's implementation with real-world user preferences and behavior patterns, optimizing its functionality and impact within the NUS campus.\n    <br><br>The revealed preference for a temperature range of 28-30 degrees Celsius significantly shapes our action strategy. The system's recommendation algorithms, akin to popular e-commerce platforms, can precisely tailor suggestions to spaces within this comfort epicenter. Aligning recommended spaces with this specific temperature range ensures not only user satisfaction but also contributes actively to maintaining a universally comfortable academic environment.\n    <br><br>Location specificity gains heightened significance as the dataset underscores the critical role of geographically-tailored precision. Hinging on NUS as the primary location for data input ensures the system's relevance and effectiveness within the campus. Specific geographic coordinates become key data points, enhancing the accuracy of the system in responding to the distinct thermal preferences of the NUS academic community.\n    <br><br>Insights into students' temperature preferences become a crucial addition to the training phase. The training process can now dynamically adapt to user preferences specifically within the identified temperature range of 28-30 degrees Celsius. This nuanced learning mechanism ensures that the system remains finely tuned to evolving user preferences, making the training process more responsive and personalized.\n    <br><br>The dataset analysis, highlighting discernible patterns in user behavior, serves as a concrete guide for feedback-driven adjustments. Semesterly fine-tuning of the HVAC system, as indicated by the dataset, can now be precisely aligned with students' evolving preferences. This data-driven feedback loop ensures that HVAC adjustments not only comply with established criteria but also directly address real-time comfort and productivity needs, as evidenced by the dataset analysis.\n    <br><br>In essence, the dataset analysis functions as a specific and dynamic compass, enriching each phase of our system's implementation with actionable insights drawn from real-world user preferences and behavior patterns, thus optimizing its functionality and impact within the unique context of the NUS campus.</p>\n","metadata":{}},{"cell_type":"markdown","source":"### Split Data","metadata":{}},{"cell_type":"code","source":"columns_to_drop = ['humidity_category', 'temperature_category']\ndf_all = df_all.drop(columns=columns_to_drop)\n# Separate training and solution data again\ndf_train = df_all[df_all.source == 'train'].copy()\ndf_solution = df_all[df_all.source == 'solution'].copy()\n\n# ws_survey_count might contain missing values and might reset. \n# To avoid any issue we are creating a similar column ws_survey_count_2 without missing and duplicate values\ndf_train.loc[(df_train.ws_survey_count.notna()), 'ws_survey_count_2'] = df_train.loc[(df_train.ws_survey_count.notna()),].groupby('id_participant').cumcount()\n\n# Add 1 to start at 1 instead of 0\ndf_train['ws_survey_count_2'] = df_train['ws_survey_count_2']+1 \n\n# Split data into training and testing sets\ndf_test = df_train[(df_train.ws_survey_count_2>11)]\ndf_train = df_train[(df_train.ws_survey_count_2<=11)]\n\n# Drop the helper columns ws_surve_count_2 and source again\ndf_train = df_train.drop(columns=['ws_survey_count_2', 'source'])\ndf_test = df_test.drop(columns=['ws_survey_count_2', 'source'])\ndf_solution = df_solution.drop(columns=['source'])","metadata":{"execution":{"iopub.status.busy":"2023-11-24T11:30:43.511351Z","iopub.execute_input":"2023-11-24T11:30:43.512159Z","iopub.status.idle":"2023-11-24T11:30:43.561568Z","shell.execute_reply.started":"2023-11-24T11:30:43.512126Z","shell.execute_reply":"2023-11-24T11:30:43.560450Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Data Preparation","metadata":{}},{"cell_type":"code","source":"# Find columns with values that are not numeric\ncat_vars = list(df_train.select_dtypes(include=['object']).columns)\n\n# encoding categorical variables\ndict_cat = {}\n\nfor var in cat_vars:\n    print(var)\n    if var == 'id_participant': # no need to encode the participant ID\n        continue\n    # convert categorical variables into 'category' type\n    df_train[var] = df_train[var].astype('category')\n    df_test[var] = df_test[var].astype('category')\n    df_solution[var] = df_solution[var].astype('category')\n    \n    # dictionary to keep track of the variable mapping: {variable-name: {number1: string1, number2: string2, ...}\n    dict_cat[var] = dict(enumerate(df_train[var].cat.categories))\n\n    # encode variables, missing values are encoded as -1\n    df_train[var] = df_train[var].cat.codes\n    df_test[var] = df_test[var].cat.codes\n    df_solution[var] = df_solution[var].cat.codes\n\ndf_train.head()","metadata":{"execution":{"iopub.status.busy":"2023-11-24T11:30:43.563014Z","iopub.execute_input":"2023-11-24T11:30:43.563441Z","iopub.status.idle":"2023-11-24T11:30:43.625250Z","shell.execute_reply.started":"2023-11-24T11:30:43.563401Z","shell.execute_reply":"2023-11-24T11:30:43.623939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Prediction Example","metadata":{}},{"cell_type":"code","source":"print(dict_cat)","metadata":{"execution":{"iopub.status.busy":"2023-11-24T11:30:43.627163Z","iopub.execute_input":"2023-11-24T11:30:43.627597Z","iopub.status.idle":"2023-11-24T11:30:43.633720Z","shell.execute_reply.started":"2023-11-24T11:30:43.627556Z","shell.execute_reply":"2023-11-24T11:30:43.632371Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from xgboost import XGBClassifier\nfrom sklearn.metrics import accuracy_score, f1_score\n\ndf_train_thermal_preference = df_train[df_train['q_thermal_preference'] != -1]\ndf_test_thermal_preference = df_test[df_test['q_thermal_preference'] != -1]\ndf_train_thermal_preference = df_train_thermal_preference.drop(['id_participant'], axis=1)\ndf_test_thermal_preference = df_test_thermal_preference.drop(['id_participant'], axis=1)\n\nnum_class = df_train_thermal_preference['q_thermal_preference'].unique()\ndict_cat['q_thermal_preference']\n\n# Break dataframe into variables and ground truth\ny_train = df_train_thermal_preference['q_thermal_preference']\nX_train = df_train_thermal_preference.drop(['q_thermal_preference'], axis=1)\n\ny_test = df_test_thermal_preference['q_thermal_preference']\nX_test = df_test_thermal_preference.drop(['q_thermal_preference'], axis=1)\n\n\n# Initialize model\nclf = XGBClassifier(num_class=num_class, objective='multi:softmax', enable_categorical=False)\n\n# Train model\nclf.fit(X_train, y_train)\n\n# Predict and evaluate\ny_pred = clf.predict(X_test)\nprint('XGBoost model accuracy score: {0:0.4f}'. format(accuracy_score(y_test, y_pred)))\n\n# Copy test data into new dataframe\ndf_comparison = df_test.copy()\n\n# Assign test prediction to dataframe\ndf_comparison['q_thermal_preference (original)'] = y_test\ndf_comparison['q_thermal_preference (predicted)'] = y_pred\n\n# Convert labels from integers back to strings\ndf_comparison['q_thermal_preference (original)'] = df_comparison['q_thermal_preference (original)'].replace(dict_cat['q_thermal_preference'])\ndf_comparison['q_thermal_preference (predicted)'] = df_comparison['q_thermal_preference (predicted)'].replace(dict_cat['q_thermal_preference'])\n\n","metadata":{"execution":{"iopub.status.busy":"2023-11-24T11:30:43.635475Z","iopub.execute_input":"2023-11-24T11:30:43.636433Z","iopub.status.idle":"2023-11-24T11:30:43.927379Z","shell.execute_reply.started":"2023-11-24T11:30:43.636389Z","shell.execute_reply":"2023-11-24T11:30:43.926059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Predict any column","metadata":{}},{"cell_type":"code","source":"def predict_any_column(column_name, df_train, df_test, df_solution):\n    # Remove rows where the predicting variable is missing\n    df_train = df_train[df_train[column_name] != -1]\n    df_test = df_test[df_test[column_name] != -1]\n    \n    # Remove rows where the predicting variable is missing\n    df_train = df_train.drop(columns=['id_participant'])\n    df_test = df_test.drop(columns=['id_participant'])\n    df_solution = df_solution.drop(columns=['id_participant'])\n\n    # Count classes in predicting variable\n    num_class = df_train[column_name].unique()\n    \n    # Break dataframe into variables and ground truth\n    y_train = df_train[column_name]\n    X_train = df_train.drop(['q_noise_nearby', 'q_noise_kind', 'q_earphones', 'q_thermal_preference'], axis=1)\n\n    y_test = df_test[column_name]\n    X_test = df_test.drop(['q_noise_nearby', 'q_noise_kind', 'q_earphones', 'q_thermal_preference'], axis=1)\n    \n    X_solution = df_solution.drop(['q_noise_nearby', 'q_noise_kind', 'q_earphones', 'q_thermal_preference'], axis=1)\n    \n    # Initialize model\n    clf = XGBClassifier(num_class=num_class, objective='multi:softmax', enable_categorical=False)\n    \n    # Train model\n    clf.fit(X_train, y_train)\n\n    # Predict and evaluate\n    y_pred = clf.predict(X_test)\n    score = accuracy_score(y_test, y_pred)\n    print('XGBoost model accuracy score: {0:0.4f}'. format(score))\n\n    # Predict solution\n    X_solution.shape\n    y_solution = clf.predict(X_solution)\n    \n    return y_solution, score\n\n# Create an empty list to collect the scores\nscore = []\n\ndf_submission = df_solution.copy()","metadata":{"execution":{"iopub.status.busy":"2023-11-24T11:30:43.935102Z","iopub.execute_input":"2023-11-24T11:30:43.936052Z","iopub.status.idle":"2023-11-24T11:30:43.953555Z","shell.execute_reply.started":"2023-11-24T11:30:43.935988Z","shell.execute_reply":"2023-11-24T11:30:43.952556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Prediction (q_thermal_preference)","metadata":{}},{"cell_type":"code","source":"df_solution['q_thermal_preference'], this_score = predict_any_column('q_thermal_preference', df_train, df_test, df_solution)\nscore.append(this_score)","metadata":{"execution":{"iopub.status.busy":"2023-11-24T11:30:43.954746Z","iopub.execute_input":"2023-11-24T11:30:43.955269Z","iopub.status.idle":"2023-11-24T11:30:44.262648Z","shell.execute_reply.started":"2023-11-24T11:30:43.955207Z","shell.execute_reply":"2023-11-24T11:30:44.261765Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Prediction (q_noise_kind)","metadata":{}},{"cell_type":"code","source":"df_submission['q_noise_kind'], this_score  = predict_any_column('q_noise_kind', df_train, df_test, df_solution)\nscore.append(this_score)","metadata":{"execution":{"iopub.status.busy":"2023-11-24T11:30:44.264156Z","iopub.execute_input":"2023-11-24T11:30:44.264760Z","iopub.status.idle":"2023-11-24T11:30:44.635585Z","shell.execute_reply.started":"2023-11-24T11:30:44.264726Z","shell.execute_reply":"2023-11-24T11:30:44.634714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Prediction (q_noise_nearby)","metadata":{}},{"cell_type":"code","source":"df_submission['q_noise_nearby'],this_score = predict_any_column('q_noise_nearby', df_train, df_test, df_solution)\nscore.append(this_score)","metadata":{"execution":{"iopub.status.busy":"2023-11-24T11:30:44.637067Z","iopub.execute_input":"2023-11-24T11:30:44.637657Z","iopub.status.idle":"2023-11-24T11:30:44.919837Z","shell.execute_reply.started":"2023-11-24T11:30:44.637622Z","shell.execute_reply":"2023-11-24T11:30:44.918980Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Overall Score Computation","metadata":{}},{"cell_type":"code","source":"# The overall score is just the averge of the scores for each column\nscore_total = np.mean(score)\nprint('Overall accuracy score: {0:0.4f}'. format(score_total))","metadata":{"execution":{"iopub.status.busy":"2023-11-24T11:30:44.921342Z","iopub.execute_input":"2023-11-24T11:30:44.922022Z","iopub.status.idle":"2023-11-24T11:30:44.930043Z","shell.execute_reply.started":"2023-11-24T11:30:44.921989Z","shell.execute_reply":"2023-11-24T11:30:44.928847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"App\"></a>\n# 5. UniReserve Tech Application","metadata":{}},{"cell_type":"code","source":"# Specify the path to your image\nimage_path_2 = \"/kaggle/input/appphoto/Login Page.png\"\n\n# Display the image\ndisplay(Image(filename=image_path_2))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-11-24T11:30:44.931502Z","iopub.execute_input":"2023-11-24T11:30:44.932073Z","iopub.status.idle":"2023-11-24T11:30:44.947641Z","shell.execute_reply.started":"2023-11-24T11:30:44.932041Z","shell.execute_reply":"2023-11-24T11:30:44.946775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<u>**Introduction**</u><br>\n<p style=\"text-align: justify;\">\n    UniReserve Tech is a cutting-edge mobile application designed exclusively for National University of Singapore (NUS) students, aiming to enhance the study experience by simplifying the process of booking study rooms on campus. This innovative app leverages real-time data on factors like humidity, capacity, and temperature to provide students with an optimal environment for their study sessions.\n</p>","metadata":{}},{"cell_type":"code","source":"# Specify the path to your image\nimage_path_3 = \"/kaggle/input/appphoto/locations.png\"\n\n# Display the image\ndisplay(Image(filename=image_path_3))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-11-24T11:30:44.949042Z","iopub.execute_input":"2023-11-24T11:30:44.949574Z","iopub.status.idle":"2023-11-24T11:30:44.961499Z","shell.execute_reply.started":"2023-11-24T11:30:44.949545Z","shell.execute_reply":"2023-11-24T11:30:44.960287Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Specify the path to your image\nimage_path_4 = \"/kaggle/input/appphoto/Booking page.png\"\n\n# Display the image\ndisplay(Image(filename=image_path_4))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-11-24T11:30:44.965795Z","iopub.execute_input":"2023-11-24T11:30:44.966137Z","iopub.status.idle":"2023-11-24T11:30:44.981256Z","shell.execute_reply.started":"2023-11-24T11:30:44.966106Z","shell.execute_reply":"2023-11-24T11:30:44.980141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<u>**Key Features**</u><br>\n***Smart Booking Systen***\n<p style=\"text-align: justify;\">\n    The core functionality of UniReserve Tech revolves around a sophisticated booking system. Students can effortlessly browse through available study rooms, viewing details such as seating capacity, humidity levels, and temperature conditions.\n</p>\n\n***Real-time Data Integration***\n<p style=\"text-align: justify;\">\n    UniReserve Tech integrates real-time data from campus sensors, ensuring that the information provided is accurate and up-to-date. This includes live updates on temperature, humidity, and room occupancy.\n</p>\n\n***Optimal Study Environment***\n<p style=\"text-align: justify;\">\n    Students can customize their study preferences by selecting rooms based on preferred temperature and humidity levels. This feature enables users to create an environment conducive to their productivity and well-being.\n</p>\n\n***User-Friendly Interface***\n<p style=\"text-align: justify;\">\n    The app boasts a sleek and intuitive user interface, making it easy for students to navigate through the available study spaces, check real-time conditions, and make bookings effortlessly. The interface is designed to enhance user experience and accessibility.\n</p>\n\n***Notifications and Reminders***\n<p style=\"text-align: justify;\">\n    UniReserve Tech keeps users informed with timely notifications and reminders. Students receive alerts for upcoming bookings, changes in room conditions, and other relevant information, ensuring a seamless and stress-free study experience.\n</p>\n\n***Feedback and Ratings***\n<p style=\"text-align: justify;\">Users can provide feedback on the study rooms they book, helping to improve the overall quality of available spaces. The app also features a rating system, allowing students to share their experiences and insights with the community.\n</p>\n\n<u>**Conclusion**</u><br>\n<p style=\"text-align: justify;\">UniReserve Tech is a revolutionary app designed to simplify and enhance the study room booking process for NUS students. By incorporating real-time data on environmental factors, it goes beyond traditional booking systems, allowing users to create an optimal study environment tailored to their preferences. With its user-friendly interface and innovative features, UniReserve Tech is set to redefine the way students approach their academic endeavors at the National University of Singapore.\n</p>","metadata":{}},{"cell_type":"markdown","source":"<a id=\"Conclusion\"></a>\n# 6. Conclusion\n<u>**Limitation**</u><br>\n<p style=\"text-align: justify;\">\n    Thermal comfort within the NUS campus is not a one-size-fits-all matter; it's intrinsically subjective and influenced by personal factors. The comfort equation includes individual expectations and psychological parameters that fluctuate daily. For instance, the choice of clothing material can significantly impact one's thermal perception. A student dressed in lightweight fabrics may feel too cold in air-conditioned spaces, while another in heavier attire might find the same temperature agreeable. Similarly, metabolic rates vary from person to person, affecting how individuals generate and retain heat. Given that NUS also has a large number of foreign students and professors, it can be safely assumed that not all foreigners are comfortable with the year-long summer temperatures of Singapore. All these factors are limitations that we have to take into consideration when developing our app.\n    <br><br>Moreover, the air velocity plays a critical role; students seated directly beneath an AC vent may experience a more intense cooling effect, leading to a preference for warmer conditions. This spatial variability in air movement across different campus locations can create microclimates, making it challenging to achieve uniform thermal satisfaction.\n    <br><br>Another limitation that we have to factor into consideration is that the GPS map shown above only corresponds to the location of our research participants and does not show the general occupancy of the location. This might possibly mean that our participant might be recording their responses while they’re in a crowded room which can result in a lower level of thermal comfort, due to the high occupancy rate which leads to a higher rate of heat generation, or vice versa. This will result in skewed data that is not representative of what we’re trying to find out through this experiment. \n    <br><br>Finally, another limitation we have to acknowledge is the fact that since the majority of our data is collected around the end of the year when most of our research participants have project deadlines and exams fast approaching, it can be assumed that their high stress levels can also affect their perception of thermal comfort. In order to offset this possible bias, we will have to make sure our data collection occurs year round instead of lasting from October to January.\nThese limitations must be acknowledged in the pursuit of a universally comfortable environment, suggesting that flexibility and adaptability in temperature and air flow control systems are essential to cater to the diverse comfort needs of the NUS community.</p>\n\n<u>**Futher Improvement**</u><br>\n<p style=\"text-align: justify;\">\n    To further enhance our booking app, we are actively exploring ways to incorporate additional elements that will significantly improve the user experience. Recognizing the importance of creating a tailored and conducive environment, we are focusing on two key aspects: noise levels and essential amenities, such as power sockets.\n    <br><br>Firstly, our ongoing efforts involve refining the app's algorithms to provide users with more granular control over noise preferences. By implementing advanced noise detection technology, users can now filter and select spaces based on their desired ambient noise levels. Whether someone seeks a quiet space for focused work or a more lively atmosphere for collaborative activities, our app will offer a range of options to suit individual preferences.\n    <br><br>Secondly, we understand the critical role amenities play in ensuring productivity. In response, we are expanding our app's functionality to include a detailed amenity filter, with a specific emphasis on power sockets. Users can easily identify and choose spaces equipped with convenient power sources, streamlining the process of finding a workspace that meets their specific needs. The app also take into consideration previous booking and recommend similar rooms for booking based on previous preferences\n    <br><br>Thirdly, we realise that, although noise level and level of productivity has a clear correlation, we noticed that some students may find studying in crowded but quiet places to have a negative impact on their productivity and will prefer to study in a place that is both quiet and secluded so that they can be alone with their thoughts. In line with this, we will also be expanding our app’s functionality to show a level of occupancy in the currently available rooms so that people who prefer secluded environments can know beforehand which rooms are more tailored to their preferences at a moment’s notice.\n    <br><br>This commitment to continual improvement reflects our dedication to providing a comprehensive solution that goes beyond basic location-based services. By incorporating these refined features into our booking app, we aim to offer users a seamless and personalized experience, empowering them to find spaces that not only match their geographic preferences but also cater to their nuanced requirements for a productive and comfortable environment.</p>\n\n","metadata":{}},{"cell_type":"markdown","source":"<a id=\"References\"></a>\n# 7. Refrences\n[1] Feng, Jiajia, et al. “Associating Indoor Air Temperature with Building Spatial Design and Occupancy Features: A Statistical Analysis on University Classrooms.” Building and Environment, vol. 216, May 2022, p. 109009. ScienceDirect, https://doi.org/10.1016/j.buildenv.2022.109009.\n\n[2]  “What Materials Keep Buildings Cool?” ArchDaily, 26 Aug. 2019, https://www.archdaily.com/923445/what-materials-keep-buildings-cool.\n\n[3] Pal, R. K., et al. “Thermal Performance of Buildings with Light Colored Exterior Materials.” Materials Today: Proceedings, vol. 28, Jan. 2020, pp. 1307–13. ScienceDirect, https://doi.org/10.1016/j.matpr.2020.04.508.\n\n","metadata":{}}]}