8000 Add read_bsrn function by AdamRJensen · Pull Request #1145 · pvlib/pvlib-python · GitHub
[go: up one dir, main page]

Skip to content

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 46 commits into from
Feb 11, 2021
Merged
Changes from 1 commit
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
73e6f9e
Add bsrn file to read bsrn files
AdamRJensen Jan 15, 2021
31203b3
simplified read_bsrn function
AdamRJensen Jan 16, 2021
7a437c3
Simplified selection of rows in read_bsrn
AdamRJensen Jan 16, 2021
93b92c8
Added read_bsrn to api.rst
AdamRJensen Jan 16, 2021
b0a6ddf
Merge pull request #1 from AdamRJensen/AdamRJensen-patch-1
AdamRJensen Jan 24, 2021
c6447a3
Delete 2021_01_16_read_bsrn_pull_request_v2.py
AdamRJensen Jan 24, 2021
52a952a
Improved format, e.g removed trailing white spaces
AdamRJensen Jan 24, 2021
870095a
Fixed spacing issues
AdamRJensen Jan 24, 2021
444e979
Update v0.9.0.rst
AdamRJensen Jan 24, 2021
f11288e
Add iotools.bsrn and import read_bsrn
AdamRJensen Jan 25, 2021
93deb2f
Merge pull request #2 from AdamRJensen/patch-3
AdamRJensen Jan 25, 2021
2fc95ad
Split multiple lines to obey 75 character limit
AdamRJensen Jan 25, 2021
656bbda
Corrected indentation
AdamRJensen Jan 25, 2021
c10d75b
Fixed indentation again
AdamRJensen Jan 25, 2021
d16d935
Remove bsrn email in description
AdamRJensen Feb 1, 2021
86cfb17
Correct COL_SPEC variable
AdamRJensen Feb 1, 2021
2eb3d44
Changed air_temperature to temp_air
AdamRJensen Feb 2, 2021
3218ab5
Add test_bsrn file
AdamRJensen Feb 2, 2021
ad8d45a
Reference to FTP updated
AdamRJensen Feb 8, 2021
fe632b8
Add zipped bsrn test file
AdamRJensen Feb 9, 2021
db1ac24
Update test filename
AdamRJensen Feb 9, 2021
a4c1d6f
Get file month/year from file instead of filename
AdamRJensen Feb 9, 2021
fc6f56d
Fixed formatting/stickler issues
AdamRJensen Feb 9, 2021
d7a5af8
Fixed formatting/stickler issues
AdamRJensen Feb 9, 2021
17d9b0b
Fixed formatting/stickler issues
AdamRJensen Feb 9, 2021
6ab294f
Fix to test_format_index
AdamRJensen Feb 9, 2021
5f59024
Refactored file opening and utc localization
AdamRJensen Feb 9, 2021
66209e4
Fixed indentation issue
AdamRJensen Feb 9, 2021
32a7cfb
Fixed hyperlink
AdamRJensen Feb 9, 2021
536f53c
Fixed doc error
AdamRJensen Feb 9, 2021
63dd3ac
Handle file start date explicitly
AdamRJensen Feb 10, 2021
6924183
Correct pytest fixture magic
AdamRJensen Feb 10, 2021
5e5f9d5
Fix indentation broken by previous commit
AdamRJensen Feb 10, 2021
5cf3d30
Correct Dataframe to DataFrame in doc string
AdamRJensen Feb 10, 2021
71895d1
Add offset to line num after explicitly handling start date
AdamRJensen Feb 10, 2021
b5ed6ee
Update test_bsrn.py
AdamRJensen Feb 10, 2021
23d4525
Added compression='infer', fixed end line number issue
AdamRJensen Feb 10, 2021
8dae943
Fixed test issue
AdamRJensen Feb 10, 2021
23c3455
Changed timedelta unit from min to minute
AdamRJensen Feb 10, 2021
260b68a
Add files via upload
AdamRJensen Feb 10, 2021
6b52a72
Changed to_timedelta unit from minute' to 'T'
AdamRJensen Feb 10, 2021
7c12848
Updated test to cover unzipped and zipped files
AdamRJensen Feb 10, 2021
17206df
Removed error causing blank line in test file
AdamRJensen Feb 10, 2021
9466626
Change to Unix end of line character from file by wholmgren
AdamRJensen Feb 10, 2021
4d3a21c
Remove extra line at end of file
AdamRJensen Feb 10, 2021
4db55be
Fix typo in bsrn.py doc string
AdamRJensen Feb 10, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Simplified selection of rows in read_bsrn
  • Loading branch information
AdamRJensen authored Jan 16, 2021
commit 7a437c39714ff3d06ba8646cfd2d3f031afea093
93 changes: 37 additions & 56 deletions pvlib/iotools/bsrn.py
10000
8000
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,21 @@
.. codeauthor:: Adam R. Jensen<adam-r-j@hotmail.com>
"""

import gzip
from collections import OrderedDict
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',
'empty0','empty1','empty2','empty3','empty4',
'dhi','dhi_std','dhi_min','dhi_max',
'lwd','lwd_std','lwd_min','lwd_max',
'air_temperature','relative_humidity','pressure']


def read_bsrn(filename):
"""
Expand All @@ -30,28 +40,12 @@ def read_bsrn(filename):

Returns
-------
Tuple of the form (data, metadata).

data: Dataframe
A Dataframe with the columns as described below. For more extensive
description of the variables, consult [2]_.

metadata: dict
Site metadata included in the file.

Notes
-----
Metadata dictionary includes the following fields:

=============== ====== ===============
Key Format Description
=============== ====== ===============
station String site name
latitude Float site latitude
longitude Float site longitude
elevation Int site elevation
=============== ====== ===============

The data Dataframe includes the following fields:

======================= ====== ==========================================
Expand Down Expand Up @@ -91,69 +85,56 @@ def read_bsrn(filename):
<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 each section
line_no_dict = OrderedDict()
if str(filename).endswith('.gz'): # if file is a gzipped (.gz) file

# Read file and store the starting line number for each 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 ('*U' in line) or ('*C' in line):
line_no_dict[line.splitlines()[0]] = num
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 ('*U' in line) or ('*C' in line):
line_no_dict[line.splitlines()[0]] = num

# Get line numbers for the data set
line_no_dict_keys = list(line_no_dict.keys())
data_id = [k for k in line_no_dict_keys if ('*C0100' in k) or ('*U0100' in k)][0] # tag for start of data sets, either *C0100 or *U0100
start_row = line_no_dict[data_id] + 1 # First line number of data
if data_id == line_no_dict_keys[-1]: # check if the dataset is the last dataset
end_row = num
else:
end_row = line_no_dict[line_no_dict_keys[line_no_dict_keys.index(data_id)+1]] # Last line number of data # should there be -1?
if line.startswith('*'): # Find start of all logical records
line_no_dict[line[2:6]] = num

# Determine start and end line of logical recrod 0100 to be parsed
start_row = line_no_dict['0100'] + 1 # Start line number of the data (LR0100)
if start_row-1 == max(line_no_dict.values()): # If LR0100 is the last logical record
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)
COLSPECS = [(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)]
data = pd.read_fwf(filename, skiprows=start_row, nrows=nrows, header=None,
colspecs=COLSPECS, na_values=[-999.0, -99.9])
colspecs=COL_SPECS, na_values=[-999.0,-99.9])

# Assign multi-index and unstack DataFrame, such that each variable has a seperate column
data = data.set_index([data.index//2, data.index%2]).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')
BSRN_COLUMNS = ['day','minute',
'ghi','ghi_std','ghi_min','ghi_max',
'dni','dni_std','dni_min','dni_max','empty0','empty1','empty2','empty3','empty4',
'dhi','dhi_std','dhi_min','dhi_max',
'lwd','lwd_std','lwd_min','lwd_max',
'air_temperature','relative_humidity','pressure']
data.columns = BSRN_COLUMNS

# Change day and minute type to integer and drop empty columns
data['day'] = data['day'].astype('Int64')
data['minute'] = data['minute'].astype('Int64')
data = data.drop(['empty0','empty1','empty2','empty3','empty4'], axis='columns')

# Set datetime index and localize to UTC
basename = os.path.basename(filename)
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') # all BSRN timestamps are in UTC
except TypeError:
pass

# Sort index and add missing timesteps
##data = data.sort_index().asfreq('1min') # can cause problems with duplicate time stamps
meta = {}
return data, meta
return data


0