Skip to content

Commit

Permalink
Merge pull request #560 from NREL/556_dev_deprecations
Browse files Browse the repository at this point in the history
556 dev deprecations
  • Loading branch information
cdeline authored Oct 7, 2024
2 parents 74d0249 + 1945f65 commit 1ad0111
Show file tree
Hide file tree
Showing 7 changed files with 71 additions and 45 deletions.
19 changes: 17 additions & 2 deletions bifacial_radiance/load.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
TEMP folder in bifacial_radiance \\ bifacial_radiance
"""
from deprecated import deprecated

''' DEPRECATED - doesn't work with python3
def load_inputvariablesfile(inputfile):
"""
Expand Down Expand Up @@ -245,9 +247,14 @@ def loadTrackerDict(trackerdict, fileprefix=None):
``finalkey`` (last index file in directory)
"""

# TODO: get this module working
import re, os
import numpy as np

print('Warning: loadTrackerDict has not been updated to the new v0.5.0' +\
' dictionary structure and is currently incomplete. Please' +\
' reach out at github.com/NREL/bifacial_radiance/issues if' +\
' this is functionality you need.\n')

# get list of filenames in \results\
filelist = sorted(os.listdir('results'))
Expand Down Expand Up @@ -459,7 +466,11 @@ def _exportTrackerDict(trackerdict, savefile, cumulativesky=False, reindex=False
D4join.to_csv(savefile4)

return



@deprecated(reason='load.deepcleanResult has been abandoned'+\
' Please use load.cleanResult instead',
version='0.5.0')
def deepcleanResult(resultsDict, sensorsy, numpanels, automatic=True):
"""
Cleans results file read by read1Result. If automatic = False, user is
Expand All @@ -468,6 +479,10 @@ def deepcleanResult(resultsDict, sensorsy, numpanels, automatic=True):
If you pass in results from a file with only _Front or _Back parameters,
only the corresponding Frontresults or Backresults will be returned.
.. deprecated:: 0.5.0
This cleaning routine is deprecated in favor of :func:`cleanResult` which
is more stable
Parameters
-----------
sensorsy : int
Expand Down
76 changes: 37 additions & 39 deletions bifacial_radiance/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
import pandas as pd
import numpy as np
import warnings

from deprecated import deprecated


global DATA_PATH # path to data files including module.json. Global context
Expand Down Expand Up @@ -374,9 +374,28 @@ def results(self):

return getResults(self.trackerdict, self.cumulativesky)

@property
@deprecated(reason='RadianceObj.Wm2Front has been abandoned'+\
' Please use values recorded in ' +
' AnalysisObj.Wm2Front or RadianceObj.results.',
version='0.5.0' )
def Wm2Front(self):
return None

@property
@deprecated(reason='RadianceObj.Wm2Back has been abandoned'+\
' Please use values recorded in ' +
' AnalysisObj.Wm2Back or RadianceObj.results.',
version='0.5.0')
def Wm2Back(self):
return None


def __repr__(self):
#return str(self.__dict__)
return str(type(self)) + ' : ' + str({key: self.__dict__[key] for key in self.columns if (key != 'trackerdict') & (key != 'results') })
return str(type(self)) + ' : ' + str({key: self.__dict__[key]
for key in self.columns if key not in ('trackerdict', 'results', 'Wm2Front','Wm2Back') })

def __init__(self, name=None, path=None, hpc=False):
'''
initialize RadianceObj with path of Radiance materials and objects,
Expand Down Expand Up @@ -405,11 +424,6 @@ def __init__(self, name=None, path=None, hpc=False):
#self.radfiles = [] # scene rad files for oconv, compiled from self.scenes
self.scenes = [] # array of scenefiles to be compiled
self.octfile = [] #octfile name for analysis
self.Wm2Front = 0 # cumulative tabulation of front W/m2
self.Wm2Back = 0 # cumulative tabulation of rear W/m2
self.backRatio = 0 # ratio of rear / front Wm2
#self.nMods = None # number of modules per row
#self.nRows = None # number of rows per scene
self.hpc = hpc # HPC simulation is being run. Some read/write functions are modified
self.compiledResults = pd.DataFrame(None) # DataFrame of cumulative results, output from self.calculatePerformance1axis()

Expand Down Expand Up @@ -669,6 +683,7 @@ def exportTrackerDict(self, trackerdict=None,


# loadtrackerdict not updated to match new trackerdict configuration
@deprecated(version='0.5.0')
def loadtrackerdict(self, trackerdict=None, fileprefix=None):
"""
Use :py:class:`bifacial_radiance.load._loadtrackerdict`
Expand All @@ -684,8 +699,8 @@ def loadtrackerdict(self, trackerdict=None, fileprefix=None):
if trackerdict is None:
trackerdict = self.trackerdict
(trackerdict, totaldict) = loadTrackerDict(trackerdict, fileprefix)
self.Wm2Front = totaldict['Wm2Front']
self.Wm2Back = totaldict['Wm2Back']
#self.Wm2Front = totaldict['Wm2Front']
#self.Wm2Back = totaldict['Wm2Back']

def returnOctFiles(self):
"""
Expand Down Expand Up @@ -729,30 +744,6 @@ def returnMaterialFiles(self, material_path=None):
self.materialfiles = materialfilelist
return materialfilelist

'''
def getResults(self, trackerdict=None): #DEPRECATED IN FAVOR OF self.results
"""
Iterate over trackerdict and return irradiance results
following analysis1axis runs
Parameters
----------
trackerdict : dict, optional
trackerdict, after analysis1axis has been run
Returns
-------
results : Pandas.DataFrame
dataframe containing irradiance scan results.
"""
from bifacial_radiance.load import getResults
if trackerdict is None:
trackerdict = self.trackerdict
return getResults(trackerdict, self.cumulativesky)
'''

def sceneNames(self, scenes=None):
if scenes is None: scenes = self.scenes
Expand Down Expand Up @@ -2094,7 +2085,7 @@ def gendaylit1axis(self, metdata=None, trackerdict=None, startdate=None,
print('Creating ~%d skyfiles. '%(len(trackerdict.keys())))
count = 0 # counter to get number of skyfiles created, just for giggles

trackerdict2={}
trackerdict2=TrackerDict({})
#for i in range(0, len(trackerdict.keys())):
for key in trackerdict.keys():
time_target = pd.to_datetime(key, format="%Y-%m-%d_%H%M").tz_localize(int(self.metdata.timezone*3600))
Expand Down Expand Up @@ -3135,7 +3126,7 @@ def _printRow(analysisobj, key):



else:
else: #cumulative analysis
if module is None:
for key in keys: # loop over trackerdict to find first available module
try:
Expand Down Expand Up @@ -4173,11 +4164,11 @@ def _set1axis(self, azimuth=180, limit_angle=45, angledelta=None,
#times = [str(i)[5:-12].replace('-','_').replace(' ','_') for i in self.datetime]
times = [i.strftime('%Y-%m-%d_%H%M') for i in self.datetime]
#trackerdict = dict.fromkeys(times)
trackerdict = {}
trackerdict = TrackerDict({})
for i,time in enumerate(times) :
# remove NaN tracker theta from trackerdict
if (self.ghi[i] > 0) & (~np.isnan(self.tracker_theta[i])):
trackerdict[time] = {
trackerdict[time] = TrackerDict({
'surf_azm':self.surface_azimuth[i],
'surf_tilt':self.surface_tilt[i],
'theta':self.tracker_theta[i],
Expand All @@ -4186,7 +4177,7 @@ def _set1axis(self, azimuth=180, limit_angle=45, angledelta=None,
'dhi':self.dhi[i],
'temp_air':self.temp_air[i],
'wind_speed':self.wind_speed[i]
}
})

return trackerdict

Expand Down Expand Up @@ -4330,7 +4321,7 @@ def _makeTrackerCSV(self, theta_list, trackingdata):
trackerdict = dict.fromkeys(theta_list)

for theta in sorted(trackerdict):
trackerdict[theta] = {}
trackerdict[theta] = TrackerDict({})
csvfile = os.path.join('EPWs', '1axis_{}.csv'.format(theta))
tempdata = trackingdata[trackingdata['theta_round'] == theta]

Expand Down Expand Up @@ -5591,3 +5582,10 @@ def quickExample(testfolder=None):
return analysis


class TrackerDict(dict):
def __getitem__(self, key):
if key == 'scene':
warnings.warn('Key `scene` deprecated. Please use the new key: `scenes` '+\
'which returns a list of SceneObj rather than a single SceneObj', DeprecationWarning)
return super().__getitem__('scenes')
return super().__getitem__(key)
5 changes: 3 additions & 2 deletions bifacial_radiance/mismatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
@author: sayala
"""

#from load import *
from deprecated import deprecated



Expand Down Expand Up @@ -300,7 +300,8 @@ def _mad_1D(data): #1D calculation of MAD
return _mad_1D(data)



@deprecated(reason='This analysis script will be moved to its own tutorial' +\
' file in a future release.', version='0.5.0')
def analysisIrradianceandPowerMismatch(testfolder, writefiletitle, portraitorlandscape, bififactor, numcells=72, downsamplingmethod='byCenter'):
r'''
Use this when sensorsy calculated with bifacial_radiance > cellsy
Expand Down
2 changes: 2 additions & 0 deletions docs/sphinx/source/whatsnew/v0.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ Deprecations
* :py:class:`~bifacial_radiance.RadianceObj.makeScene1axis`.`appendtoScene` is deprecated in favor of :py:class:`~bifacial_radiance.makeScene1axis`.`customtext`
* `Wm2Front` and `Wm2Back` are no longer attributes of :py:class:`~bifacial_radiance.RadianceObj` object. Results are now tracked in :py:class:`~bifacial_radiance.AnalysisObj.results` and :py:class:`~bifacial_radiance.RadianceObj.results` for trackerDict simulations.


API Changes
~~~~~~~~~~~~
* Final irradiance and performance data are stored in: :py:class:`~bifacial_radiance.AnalysisObj.results` and :py:class:`~bifacial_radiance.RadianceObj.results`.
* Results generated with the above can be saved with the :py:class:`~bifacial_radiance.RadianceObj.exportTrackerDict`, which saves an Hourly, Monthly and Yearly .csvs in the results folder.
* `trackerdict['key']['scene']` has been renamed `trackerdict['key']['scenes']` and now returns a list of SceneObjs.
* NSRDB weather data can now be loaded using :py:class:`~bifacial_radiance.RadianceObj.NSRDBWeatherData`.
* :py:class:`~bifacial_radiance.AnalysisObj.analysis` updated to allow single (front-only) scans in support of AgriPV modeling. Pass `None` to `backscan` for single-sided scan. (:pull:`499`)
* :py:class:`~bifacial_radiance.makeScene`.`append` added to allow multiple scenes to be attached to a single RadianceObj. Default: False (over-write the scene). (:pull:`487`)
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
'pyradiance',
'scipy > 1.6.0',
'tqdm',
'deprecated',
],

# List additional groups of dependencies here (e.g. development
Expand Down
5 changes: 4 additions & 1 deletion tests/test_bifacial_radiance.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,9 @@ def test_Radiance_1axis_gendaylit_modelchains():
#V 0.2.5 fixed the gcr passed to set1axis. (since gcr was not being passd to set1axis, gcr was default 0.33 default).
assert(demo2.compiledResults.Gfront_mean[0] == pytest.approx(205.0, 0.01) ) # was 214 in v0.2.3 # was 205 in early v0.2.4
assert(demo2.compiledResults.Grear_mean[0] == pytest.approx(43.0, 0.1) )
assert demo2.trackerdict['2001-01-01_1100']['scenes'][0].text.__len__() == 134
# test that trackerdict['scene'] is deprecated
with pytest.warns(DeprecationWarning):
assert demo2.trackerdict['2001-01-01_1100']['scene'][0].text.__len__() == 134
assert demo2.trackerdict['2001-01-01_1100']['scenes'][0].text[23:28] == " 2.0 "
demo2.exportTrackerDict(savefile = 'results\exportedTrackerDict.csv', reindex=True)
# Run groundscan
Expand All @@ -165,6 +167,7 @@ def test_Radiance_1axis_gendaylit_modelchains():
assert results_ground.sensorsground == 56
assert results_ground.mattype[0] == 'groundplane'


"""
def test_RadianceObj_1axis_gendaylit_end_to_end():
name = "_test_1axis_gendaylit_end_to_end"
Expand Down
8 changes: 7 additions & 1 deletion tests/test_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,13 @@ def test_load_trackerdict():
trackerdict = demo.set1axis(cumulativesky = False)
print(trackerdict)
demo.loadtrackerdict(trackerdict,fileprefix = 'test_')
assert demo.Wm2Front[0] == pytest.approx(166.3, abs = 0.01)
# test that Wm2Front is deprecated
with pytest.warns(DeprecationWarning):
demo.Wm2Front
with pytest.warns(DeprecationWarning):
demo.Wm2Back
#assert demo.Wm2Front[0] == pytest.approx(166.3, abs = 0.01)


def test_cleanResult():
# example of setting NaN's when the scan intersects undesired material
Expand Down

0 comments on commit 1ad0111

Please sign in to comment.