-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Add read_bsrn function #1145
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add read_bsrn function #1145
Changes from 14 commits
Commits
Show all changes
46 commits
Select commit
Hold shift + click to select a range
73e6f9e
Add bsrn file to read bsrn files
AdamRJensen 31203b3
simplified read_bsrn function
AdamRJensen 7a437c3
Simplified selection of rows in read_bsrn
AdamRJensen 93b92c8
Added read_bsrn to api.rst
AdamRJensen b0a6ddf
Merge pull request #1 from AdamRJensen/AdamRJensen-patch-1
AdamRJensen c6447a3
Delete 2021_01_16_read_bsrn_pull_request_v2.py
AdamRJensen 52a952a
Improved format, e.g removed trailing white spaces
AdamRJensen 870095a
Fixed spacing issues
AdamRJensen 444e979
Update v0.9.0.rst
AdamRJensen f11288e
Add iotools.bsrn and import read_bsrn
AdamRJensen 93deb2f
Merge pull request #2 from AdamRJensen/patch-3
AdamRJensen 2fc95ad
Split multiple lines to obey 75 character limit
AdamRJensen 656bbda
Corrected indentation
AdamRJensen c10d75b
Fixed indentation again
AdamRJensen d16d935
Remove bsrn email in description
AdamRJensen 86cfb17
Correct COL_SPEC variable
AdamRJensen 2eb3d44
Changed air_temperature to temp_air
AdamRJensen 3218ab5
Add test_bsrn file
AdamRJensen ad8d45a
Reference to FTP updated
AdamRJensen fe632b8
Add zipped bsrn test file
AdamRJensen db1ac24
Update test filename
AdamRJensen a4c1d6f
Get file month/year from file instead of filename
AdamRJensen fc6f56d
Fixed formatting/stickler issues
AdamRJensen d7a5af8
Fixed formatting/stickler issues
AdamRJensen 17d9b0b
Fixed formatting/stickler issues
AdamRJensen 6ab294f
Fix to test_format_index
AdamRJensen 5f59024
Refactored file opening and utc localization
AdamRJensen 66209e4
Fixed indentation issue
AdamRJensen 32a7cfb
Fixed hyperlink
AdamRJensen 536f53c
Fixed doc error
AdamRJensen 63dd3ac
Handle file start date explicitly
AdamRJensen 6924183
Correct pytest fixture magic
AdamRJensen 5e5f9d5
Fix indentation broken by previous commit
AdamRJensen 5cf3d30
Correct Dataframe to DataFrame in doc string
AdamRJensen 71895d1
Add offset to line num after explicitly handling start date
AdamRJensen b5ed6ee
Update test_bsrn.py
AdamRJensen 23d4525
Added compression='infer', fixed end line number issue
AdamRJensen 8dae943
Fixed test issue
AdamRJensen 23c3455
Changed timedelta unit from min to minute
AdamRJensen 260b68a
Add files via upload
AdamRJensen 6b52a72
Changed to_timedelta unit from minute' to 'T'
AdamRJensen 7c12848
Updated test to cover unzipped and zipped files
AdamRJensen 17206df
Removed error causing blank line in test file
AdamRJensen 9466626
Change to Unix end of line character from file by wholmgren
AdamRJensen 4d3a21c
Remove extra line at end of file
AdamRJensen 4db55be
Fix typo in bsrn.py doc string
AdamRJensen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,141 @@ | ||
"""Functions to read data from the Baseline Surface Radiation Network (BSRN). | ||
.. codeauthor:: Adam R. Jensen<[email protected]> | ||
""" | ||
|
||
import pandas as pd | ||
import gzip | ||
import os | ||
|
||
COL_SPECS = [(0, 3), (4, 9), (10, 16), (17, 22), (23, 27), (28, 32), (33, 39), | ||
(40, 45), (46, 50), (51, 55), (56, 64), (65, 70), (71, 75)] | ||
|
||
BSRN_COLUMNS = ['day', 'minute', | ||
'ghi', 'ghi_std', 'ghi_min', 'ghi_max', | ||
'dni', 'dni_std', 'dni_min', 'dni_max', | ||
'empty', 'empty', 'empty', 'empty', 'empty', | ||
'dhi', 'dhi_std', 'dhi_min', 'dhi_max', | ||
'lwd', 'lwd_std', 'lwd_min', 'lwd_max', | ||
'air_temperature', 'relative_humidity', 'pressure'] | ||
|
||
|
||
def read_bsrn(filename): | ||
""" | ||
Read a BSRN station-to-archive file into a DataFrame. | ||
|
||
The BSRN (Baseline Surface Radiation Network) is a world wide network | ||
of high-quality solar radiation monitoring stations as described in [1]_. | ||
The function only parses the basic measurements (LR0100), which include | ||
global, diffuse, direct and downwelling long-wave radiation [2]_. Future | ||
updates may include parsing of additional data and meta-data. | ||
|
||
Required username and password are easily obtainable by writing an email to | ||
Amelie Driemel ([email protected]) [3]_ on condition that users follow | ||
BSRN's Data Release Guidelines [4]_. | ||
|
||
|
||
Parameters | ||
---------- | ||
filename: str | ||
A relative or absolute file path. | ||
|
||
Returns | ||
------- | ||
data: Dataframe | ||
A Dataframe with the columns as described below. For more extensive | ||
description of the variables, consult [2]_. | ||
|
||
Notes | ||
----- | ||
The data Dataframe includes the following fields: | ||
|
||
======================= ====== ========================================== | ||
Key Format Description | ||
======================= ====== ========================================== | ||
day int Day of the month 1-31 | ||
minute int Minute of the day 0-1439 | ||
ghi float Mean global horizontal irradiance [W/m^2] | ||
ghi_std float Std. global horizontal irradiance [W/m^2] | ||
ghi_min float Min. global horizontal irradiance [W/m^2] | ||
ghi_max float Max. global horizontal irradiance [W/m^2] | ||
dni float Mean direct normal irradiance [W/m^2] | ||
dni_std float Std. direct normal irradiance [W/m^2] | ||
dni_min float Min. direct normal irradiance [W/m^2] | ||
dni_max float Max. direct normal irradiance [W/m^2] | ||
dhi float Mean diffuse horizontal irradiance [W/m^2] | ||
dhi_std float Std. diffuse horizontal irradiance [W/m^2] | ||
dhi_min float Min. diffuse horizontal irradiance [W/m^2] | ||
dhi_max float Max. diffuse horizontal irradiance [W/m^2] | ||
lwd float Mean. downward long-wave radiation [W/m^2] | ||
lwd_std float Std. downward long-wave radiation [W/m^2] | ||
lwd_min float Min. downward long-wave radiation [W/m^2] | ||
lwd_max float Max. downward long-wave radiation [W/m^2] | ||
air_temperature float Air temperature [°C] | ||
relative_humidity float Relative humidity [%] | ||
pressure float Atmospheric pressure [hPa] | ||
======================= ====== ========================================== | ||
|
||
References | ||
---------- | ||
.. [1] `World Radiation Monitoring Center - Baseline Surface Radiation | ||
Network (BSRN) `BSRN homepage <https:/https://bsrn.awi.de/>`_ | ||
.. [2] `Update of the Technical Plan for BSRN Data Management, 2013, | ||
Global Climate Observing System (GCOS) GCOS-172. | ||
<https://bsrn.awi.de/fileadmin/user_upload/bsrn.awi.de/Publications/gcos-174.pdf>`_ | ||
.. [3] `BSRN Data Retrieval via FTP | ||
<https://bsrn.awi.de/data/data-retrieval-via-ftp/>`_ | ||
.. [4] `BSRN Data Release Guidelines | ||
<https://bsrn.awi.de/data/conditions-of-data-release/>`_ | ||
""" | ||
|
||
# Read file and store the starting line number for each logical record (LR) | ||
line_no_dict = {} | ||
if str(filename).endswith('.gz'): # check if file is a gzipped (.gz) file | ||
with gzip.open(filename, 'rt') as f: | ||
for num, line in enumerate(f): | ||
if line.startswith('*'): # Find start of all logical records | ||
line_no_dict[line[2:6]] = num # key is 4 digit LR number | ||
else: | ||
with open(filename, 'r') as f: | ||
for num, line in enumerate(f): | ||
if line.startswith('*'): # Find start of all logical records | ||
line_no_dict[line[2:6]] = num | ||
|
||
# Determine start and end line of logical record LR0100 to be parsed | ||
start_row = line_no_dict['0100'] + 1 # Start line number | ||
# If LR0100 is the last logical record, then read rest of file | ||
if start_row-1 == max(line_no_dict.values()): | ||
end_row = num # then parse rest of the file | ||
else: # otherwise parse until the beginning of the next logical record | ||
end_row = min([i for i in line_no_dict.values() if i > start_row]) | ||
nrows = end_row-start_row | ||
|
||
# Read file as a fixed width file (fwf) | ||
data = pd.read_fwf(filename, skiprows=start_row, nrows=nrows, header=None, | ||
colspecs=COL_SPECS, na_values=[-999.0, -99.9]) | ||
|
||
# Create multi-index and unstack, resulting in one column for each variable | ||
data = data.set_index([data.index // 2, data.index % 2]) | ||
data = data.unstack(level=1).swaplevel(i=0, j=1, axis='columns') | ||
|
||
# Sort columns to match original order and assign column names | ||
data = data.reindex(sorted(data.columns), axis='columns') | ||
data.columns = BSRN_COLUMNS | ||
# Drop empty columns | ||
data = data.drop('empty', axis='columns') | ||
|
||
# Change day and minute type to integer | ||
data['day'] = data['day'].astype('Int64') | ||
data['minute'] = data['minute'].astype('Int64') | ||
|
||
# Set datetime index and localize to UTC | ||
basename = os.path.basename(filename) # get month and year from filename | ||
data.index = (pd.to_datetime(basename[3:7], format='%m%y') | ||
+ pd.to_timedelta(data['day']-1, unit='d') | ||
+ pd.to_timedelta(data['minute'], unit='min')) | ||
|
||
try: | ||
data.index = data.index.tz_localize('UTC') # BSRN timestamps are UTC | ||
except TypeError: | ||
AdamRJensen marked this conversation as resolved.
Show resolved
Hide resolved
|
||
pass | ||
|
||
return data |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.