GithubHelp home page GithubHelp logo

nrel / pysam Goto Github PK

View Code? Open in Web Editor NEW
106.0 18.0 47.0 252.91 MB

Python Wrapper for the System Advisor Model

Home Page: http://nrel-pysam.readthedocs.io

License: BSD 3-Clause "New" or "Revised" License

C 77.15% Python 8.01% PowerBuilder 14.81% Shell 0.02% Batchfile 0.01%

pysam's Introduction

PySAM Package

https://nrel-pysam.readthedocs.io

  • Provides a wrapper around the SAM library that groups together the C API functions by technology or financial model into modules.
  • Includes error-checking, explicit input and output definition, and conversion between Python data types.
  • PySAM modules are compatible with PySSC, which is included as a subpackage. PySSC is the original wrapper used by SAM's code generator.
  • Automatically assign default values to input parameters from SAM's default value database.
  • Built-in documentation of models and parameters.

Requirements

  1. Python 3.8 - 3.12, 64 bit
  2. Operating system:
    • MacOSX 10.7+
    • Most Linux
    • Windows 7, x64
  3. CMake 3.20+

Installing

  1. PyPi:

    pip install nrel-pysam
    
  2. Anaconda (Versions > 1.2.1 only):

    conda install -c nrel nrel-pysam
    

May not be compatible with different builds of the CPython reference interpreter, and not with alternative interpreters such as PyPy, IronPython or Jython

Usage Examples

Citing this package

PySAM . National Renewable Energy Laboratory. Golden, CO. Accessed . https://github.com/nrel/pysam

pysam's People

Contributors

allendowney avatar bje- avatar brtietz avatar cpaulgilman avatar cwhanse avatar dakotaramos avatar dguittet avatar frohro avatar grgmiller avatar janinefreeman avatar kandersolar avatar masonbowen avatar matthew-boyd avatar mike-welch avatar mjprilliman avatar qualand avatar shirubana avatar sjanzou avatar skoeb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pysam's Issues

`Value` Error messages are Blank

Value throws an empty error if given a variable that isn't in its attributes:


error Traceback (most recent call last)
in
10
11 b = bt.new()
---> 12 b.value("en_batt", 1)
error:

Example code for Resource Tools URDBv7_to_ElectricityRates throws error

Attempting to use the example code from https://nrel-pysam.readthedocs.io/en/master/Tools.html?highlight=utility%20rate#resource-tools for ResourceTools.URDBv7_to_ElectricityRates throws the error "Must assign Technology module attributes with nested dictionaries" Iterating through the key-value pairs and using Utilityrate5.value works.

Either update ResourceTools.URDBv7_to_ElectricityRates to return the correct dictionary format for assign or update the example to iterate over key-value pairs.

Notations for variables that need recomputing missing....

On this page the documentation states, "In each PySAM Module’s page, each variable that may be affected by such equations will have a “Changes to this variable may require updating the values of the following” and “This variable may need to be updated if the values of the following have changed” section to provide suggestions for which variables may be affected upstream or downstream." I am finding any notations like that on the Cashloan page, but when I change the size of the solar array (Pvwatts7.SystemDesign.system_capacity), the net capital cost (Cashloan.Outputs.adjusted_installed_cost) doesn't change.
I searched for warning notes about this in Pvwatts7, and Utilityrate5, and don't think I found any warnings there, so I thought I was home free. :-) It doesn't look that way at the moment.
I'm enclosing my python code, and the files I'm using to check things.
Recompute_problem.zip
For me, it really doesn't matter what installed cost was used. I just need to know what was used for the calculation, because I need to subtract it out, except for the actual first year, which is correct. :-)
I would like to know if I'm looking in the wrong place for the documentation, etc.
Am I missing something? I must be.
Thanks so much for all your help!
Rob

Numpy Compatibility

ndarrays can sometimes be used for array inputs, but seem to cause errors when used within dictionary inputs.

For instance, from test_ResourceTools.py:

        # get a solar_resource_data dictionary
        solar = str(Path(__file__).parent / "blythe_ca_33.617773_-114.588261_psmv3_60_tmy.csv")
        data = tools.TMY_CSV_to_solar_data(solar)

        # each irradiance input is a list
        assert (data['dn'][7] == 262)

        # turning into ndarray will cause errors
        data['gh'] = np.array(data['gh'])
     
        model = pvsam.default("FlatPlatePVNone")
        model.SolarResource.solar_resource_data = data
>       model.execute()
E       TypeError: only size-1 arrays can be converted to Python scalars

Question: Can I use the dev branch if I need to a PV grid limit as SAM beta has?

Hi,
I need to customize the calculations SAM makes using PVWatts, Commercial, so I can have utility rates changing as a function of time. (I'm on Guam, and they have a LEAC (fuel cost) that changes every six months, and is projected to do a healthy drop in 2022.) I also need to limit the energy that goes back to the grid. I found the 2018.11.11 version of SAM that goes with the released PySAM doesn't have the Grid Limits section that the 2020.1.14 beta version does. Can and should I use the dev branch for this purpose? Also, where should I look for examples?
Thanks,
Rob

Battwatts execution error: charging loss length must be 1 or 12 for monthly input mode

I am trying to run a simple Battwatts model, where some inputs to the model are outputs from the Pvwattsv5 model:

import PySAM.Pvwattsv5 as pvwatts
import PySAM.Battwatts as battery

pv = pvwatts.default("PVWattsResidential")
pv.LocationAndResource.solar_resource_file = resource_file
pv.SystemDesign.batt_simple_enable = 1
pv.execute()

batt = battery.default("PVWattsResidential")
batt.BatteryModelSimple.batt_simple_enable = 1
batt.Common.ac = pv.Outputs.ac
batt.Common.dc = pv.Outputs.dc
batt.Common.inverter_efficiency = pv.Outputs.inverter_efficiency
batt.Common.inverter_model = pv.Outputs.inverter_model

batt.execute()

I receive the following error:
error: battwatts execution error. exec fail(battery): charging loss length must be 1 or 12 for monthly input mode

I traced the error back to line 856 of cmod_battery.cpp where the battery attributes batt_loss_choice and batt_losses_charging are checked. However, I cannot set the values of these variables using the Battwatts module from PySAM (only the StandAloneBatteryModel, which I've been doing as a work-around).

Is there an issue with the way I am using Battwatts? I would prefer to use that simplified battery model but I am unaware of how to get rid of that error.

ssc_data_t values cannot be assigned with an uppercase variable name

The following works fine:
data.P_ref = ${P_ref}; // in UI form Equations window in MSPT System Design
vt_get_number(vt, "P_ref", &P_ref); // in cmod_csp_tower_eqns.cpp

This does not work:
vt->assign("Q_rec_des", Q_rec_des); // in cmod_csp_tower_eqns.cpp
${Q_rec_des} = data.Q_rec_des; // in UI form Equations window in MSPT System Design

This works:
vt->assign("q_rec_des", Q_rec_des); // in cmod_csp_tower_eqns.cpp
${Q_rec_des} = data.q_rec_des; // in UI form Equations window in MSPT System Design

URDBv7_to_ElectricityRates fails when flat demand exists without TOU

When a URDB-provided rate has only flat demand changes but no TOU charges, the utilityrate5 calculation will fail. This is because the TOU inputs are required whenever ur_dc_enable is true, regardless. In the SAM GUI, the TOU schedules are set to a default with a single period, and the TOU structure is set to $0/kW.

URDBv7_to_ElectricityRates should be modified to provide these same dummy defaults.

Not available for Python 3.7 on MacOSX version < 10.14

Even though the file name NREL_PySAM-1.2.1-cp37-cp37m-macosx_10_14_x86_64.whl implies that the minimum required version of macosx is 10.14 for the python 3.7 version, it actually works fine on 10.12. The name needs to be changed so that pip will not require 10.14 when 10.12 is acceptable.

Until then, the work-around is to download the file directly, replace '14' with '12' and use pip to install PySAM from the downloaded file:

pip install path/to/NREL_PySAM-1.2.1-cp37-cp37m-macosx_10_12_x86_64.whl

Changing bifaciality factor values does not modify annual energy

Hello,

NREL-PySAM: 2.0.2
NREL-PySAM-stubs: 2.0.2
Installed in: 5.4.15-2-MANJARO
With: conda version : 4.7.12
With: python version : 3.7.4

Problem: When changing the bifaciality factor values the final annual energy does not change.

Detailed description: I set up a PV plant configuration with SAM. Then, I export the parameters in a json file. In a python script, I load the parameters and execute. When I change the bifaciality factor and execute again the resulting annual energy is always the same. If I modify other parameters, like the ground_clearance_height then the annual energy changes, as expected. In no case, the annual energy calculated with the python script is equal to that calculated directly with SAM (it is similar but different). It seems like some parameter is not being used in the simulation with PySAM and also that the bifacility factor is ignored.

Example:

import json
import PySAM.Pvsamv1 as sampv
from PySAM.PySSC import dict_to_ssc_table

# Loading predefined plant with SAM in a json
# 065 in file-name means "Bifaciality factor = 0.65"
with open('PV-plant_bifaciality-065.json') as sg_plant_params_file:
    plant_dict = json.load(sg_plant_params_file)
reference_pvplant_065 = dict_to_ssc_table(plant_dict, "Pvsamv1")
plant065 =  sampv.wrap(reference_pvplant_065)

# Print loaded attributes
print('module_model (0=SPE): ',
      plant065.Module.module_model)
print('spe_is_bifacial: ',
      plant065.SimpleEfficiencyModuleModel.spe_is_bifacial)
print('spe_bifaciality: ',
      plant065.SimpleEfficiencyModuleModel.spe_bifaciality)
print('spe_bifacial_transmission_factor: ',
      plant065.SimpleEfficiencyModuleModel.spe_bifacial_transmission_factor)
print('spe_bifacial_ground_clearance_height: ',
      plant065.SimpleEfficiencyModuleModel.spe_bifacial_ground_clearance_height)

# Execute
plant065.execute()
print('annual energy (with Bf 0.65): ', plant065.Outputs.annual_energy, '[kWh]')

# Modify Bifaciality factor and execute again
plant065.SimpleEfficiencyModuleModel.spe_bifaciality = 0.80
plant065.execute()
print('annual energy (with Bif_f 0.80): ', plant065.Outputs.annual_energy, '[kWh]')

# make sure the attribute is right
print('spe_bifaciality: ',
      plant065.SimpleEfficiencyModuleModel.spe_bifaciality)

# try modify other parameter: from ground_clearance_height 1 to 1.5
plant065.SimpleEfficiencyModuleModel.spe_bifacial_ground_clearance_height = 1.5
plant065.execute()
print('annual energy (with GCH 1.5): ', plant065.Outputs.annual_energy, '[kWh]')

# try deactivate bifacial
plant065.SimpleEfficiencyModuleModel.spe_is_bifacial = 0
plant065.execute()
print('annual energy (with Bif 0): ', plant065.Outputs.annual_energy, '[kWh]')

The result:
[mimxvi scripts]$ python -u testing_sam.py
module_model (0=SPE): 0.0
spe_is_bifacial: 1.0
spe_bifaciality: 0.6499999761581421
spe_bifacial_transmission_factor: 0.013000000268220901
spe_bifacial_ground_clearance_height: 1.0
annual energy (with Bf 0.65): 2595990.586107735 [kWh] # This value directly in SAM is 2537343[kWh].
annual energy (with Bif_f 0.80): 2595990.586107735 [kWh]
spe_bifaciality: 0.8
annual energy (with GCH 1.5): 2622277.451320002 [kWh]
annual energy (with Bif 0): 2415502.2998500825 [kWh]

I do not know what I am doing wrong, or what is happening. In the web, it is said that bifaciality factor is in %, but even changing one order of magnitude does not help.
"spe_bifaciality
float: Bifaciality factor [%]
Required: set to 0 if not provided."

Thank you very much in advance for any help.

fopen reaches the maximum 509 limit

When using default models, the PySAM_load_defaults function in PySAM_utils.h opens a file and it appears that this file is never closed.

When constructing a model using the .default function such as in PySAM.Pvwattsv5.default('PVWattsNone'), if 509 files have already been open it will return an unable to open file because 509 files are already opened.

I got around this issue by reading the default files once and then copying the parameters into a new model.

Is it necessary that the files be kept open?

Resource Tools URDBv7_to_ElectricityRates does not support kWh daily units

If a user attempts to run URDBv7_to_ElectricityRates on a rate with tier units other than kWh, they get the following error: "UtilityRateDatabase error: unrecognized unit in rate structure"

However, SSC supports kWh daily, kWh/kW, and kWh/kW daily: https://github.com/NREL/ssc/blob/596403ea2a2aca2913bf491f1537ad92c90ee905/shared/lib_utility_rate_equations.cpp#L472

See SAM conversion here: https://github.com/NREL/SAM/blob/8e3245d31171482835ab9bd2c91fc1b16f1f82e0/src/urdb.cpp#L669

Add the three additional units to the type checker in URDBv7_to_ElectricityRates

CEC 6 parameter values

Continuing from a question by @Stev0198 from this thread.

Currently, retrieving the CEC 6 parameter values [6par_Adj,6par_Il,6par_Io,6par_Rs,6par_Rsh,6par_a] from a CECPerformanceModelWithUserEnteredSpecifications Group by defining the required parameters can be done by:

  1. examining the Outputs
  2. separately running the 6parsolve compute_module with PySAM.PySSC.

How to do so from the Outputs would be:

import PySAM.Pvsamv1 as Pvsamv1
pv = Pvsamv1.default("FlatPlatePVCommercial")
pv.SolarResource.solar_resource_file = file
pv.Module.module_model = 2
pv.execute(1)
outputs = pv.Outputs.export()
params = {k:outputs[k] for k in ('6par_Adj','6par_Il','6par_Io', '6par_Rs', '6par_Rsh', '6par_a') if k in outputs}
# {'6par_Adj': 25.238671555498257, '6par_Il': 7.062310805915052, '6par_Io': 3.458041948093099e-10, '6par_Rs': 0.3778517943111882, '6par_Rsh': 42.44789603827558, '6par_a': 1.5672527775344784}

An example of how to do the second would be:

datadict = {"tech_model": '6parsolve' ,'celltype': 'multiSi', 'Vmp': 30, 'Imp': 6, 'Voc': 37, 'Isc': 7, 'alpha_isc':0.004, 'beta_voc':-0.11, 'gamma_pmp':-0.41, 'Nser': 60, 'Tref':25, 'financial_model':'none'}
from PySAM.PySSC import *
ssc_sim_from_dict(datadict)
# {'celltype': 'multiSi', 'Vmp': 30.0, 'Imp': 6.0, 'Voc': 37.0, 'Isc': 7.0, 'alpha_isc': 0.004, 'beta_voc': -0.11, 'gamma_pmp': -0.41, 'Nser': 60.0, 'Tref': 25.0, 'a': 1.5672527775344784, 'Il': 7.062310805915052, 'Io': 3.458041948093099e-10, 'Rs': 0.3778517943111882, 'Rsh': 42.44789603827558, 'Adj': 25.238671555498257, 'tech_model': '6parsolve', 'financial_model': 'none', 'cmod_success': 1}

Hope that helps!

InverterMermoudLejeuneModel Input Parameter Values

Is there a working example of an input dictionary that could be used via the PySAM.Pvsamv1.Pvsamv1.InverterMermoudLejeuneModel.assign() method? I am presently parsing in values from supplier OND files and have included an example .export() from the inverter object.

When I attempt to run with the following inverter object, the model falls over and all I have as an error message is: "Process finished with exit code 3". I have had an issue with this using a modified SAM sscapi.py file as well with the self.data_set_matrix method. When running directly from the SAM SDK sscapi.py, it falls over with a windows error.

Below is my current inverter object. Is this a known issue, or do I have a problem with my input format? I have no issues when replacing the MLM inverter module with the datasheet inverter module.

{
  "ond_Aux_Loss": 0.0,
  "ond_CompPMax": "Lim",
  "ond_CompVMax": "Lim",
  "ond_IMaxAC": 2150.0,
  "ond_IMaxDC": 0.0,
  "ond_INomAC": 2150.0,
  "ond_INomDC": 0.0,
  "ond_ModeAffEnum": "Efficiencyf_POut",
  "ond_ModeOper": "MPPT",
  "ond_NbInputs": 24.0,
  "ond_NbMPPT": 1.0,
  "ond_Night_Loss": 200.0,
  "ond_PLim1": 1995000.0,
  "ond_PLimAbs": 0.0,
  "ond_PMaxDC": 0.0,
  "ond_PMaxOUT": 2310000.0,
  "ond_PNomConv": 2100000.0,
  "ond_PNomDC": 0.0,
  "ond_PSeuil": 2887.5,
  "ond_TPLim1": 55.0,
  "ond_TPLimAbs": 60.0,
  "ond_TPMax": 25.0,
  "ond_TPNom": 50.0,
  "ond_VAbsMax": 1500.0,
  "ond_VMPPMax": 1310.0,
  "ond_VMppMin": 891.0,
  "ond_VNomEff": [
    891.0,
    970.0,
    1200.0
  ],
  "ond_VOutConv": 630.0,
  "ond_doAllowOverpower": 1.0,
  "ond_doUseTemperatureLimit": 1.0,
  "ond_effCurve_Pac": [
    [
      0.0,
      222600.0,
      445200.0,
      667800.0,
      1113000.0,
      1669500.0,
      2226000.0,
      0.0,
      0.0,
      0.0
    ],
    [
      0.0,
      222600.0,
      445200.0,
      667800.0,
      1113000.0,
      1669500.0,
      2226000.0,
      0.0,
      0.0,
      0.0
    ],
    [
      0.0,
      222600.0,
      445200.0,
      667800.0,
      1113000.0,
      1669500.0,
      2226000.0,
      0.0,
      0.0,
      0.0
    ]
  ],
  "ond_effCurve_Pdc": [
    [
      2887.5,
      228636.0,
      453776.4,
      678589.5,
      1128231.1,
      1692689.9,
      2259439.8,
      0.0,
      0.0,
      0.0
    ],
    [
      2887.5,
      228706.5,
      453915.2,
      677969.5,
      1129032.2,
      1694407.8,
      2259210.4,
      0.0,
      0.0,
      0.0
    ],
    [
      2887.5,
      228542.1,
      454146.7,
      678382.7,
      1130178.7,
      1695268.0,
      2261505.6,
      0.0,
      0.0,
      0.0
    ]
  ],
  "ond_effCurve_elements": 3.0,
  "ond_effCurve_eta": [
    [
      0.0,
      0.9735999580118616,
      0.981099942614909,
      0.9841001076497647,
      0.986500017593913,
      0.9862999714241811,
      0.9851999597422335,
      0.0,
      0.0,
      0.0
    ],
    [
      0.0,
      0.9732998406254304,
      0.9807999379619805,
      0.9850000626871858,
      0.9858000506982884,
      0.9852999968484564,
      0.9852999968484565,
      0.0,
      0.0,
      0.0
    ],
    [
      0.0,
      0.9739999763719682,
      0.980299977958664,
      0.984400103363485,
      0.984800014369409,
      0.9848000434149645,
      0.9843000167675905,
      0.0,
      0.0,
      0.0
    ]
  ],
  "ond_lossRAc": 0.0,
  "ond_lossRDc": 0.0
}

Cannot assign Solar Resource using tools.TMY_CSV_to_solar_data()

`def get_resource(latitude, longitude):
# --- Initialize Sun Fetcher ---
sunfetcher = tools.FetchResourceFiles(
tech='pv',
workers=1, #thread workers if fetching multiple files
nrel_api_key='3LFmI97FanZVzvNlN0LiL0dRNU3y3Mxj5rGfinca',
nrel_api_email='[email protected]')

# --- Pass a list of (lon, lat) tuples or Shapely points to fetch the nearest resource data ---
lon_lats = [(longitude, latitude)]  # golden CO
sunfetcher.fetch(lon_lats)
    
# --- Get resource data file path ---
path_dict = sunfetcher.resource_file_paths_dict
fp = path_dict[lon_lats[0]]

solarResource = tools.TMY_CSV_to_solar_data(fp)

return solarResource`

I get an unnamed exception when using the solarResource dictionary returned by this function when assigning this dictionary to system_model.

system_model.SolarResource.assign(solarResource)

Thank you for your assistance.

Not able to load defaults: <built-in function default> returned a result with an error set

Hello.
I'm experiencing this problem:

NREL-PySAM
Installed in: 5.4.15-2-MANJARO
With: conda version : 4.7.12
With: python version : 3.7.4
Problem: I'm not able to load the defaults values.
Code and results:

(py3_SAM) [xvi@leonardo programs]$ python
Python 3.7.6 (default, Jan  8 2020, 19:59:22) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import PySAM.Pvwattsv5 as pv
>>> d = pv.default("PVWattsSingleOwner")
PySAM.error: Could not open defaults file.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
SystemError: <built-in function default> returned a result with an error set

Thank you very much in advance for any help.

IAM mismatch between SAM gui and pysam

Dear all,

I am struggling to make "subarray1_aoi_modifier" agree between SAM gui pysam although:

  • subarray1_axisrotation
  • dn
  • df
  • gh/gh_calc
  • airmass
    agree!
    I use 'blythe_ca_33.617773_-114.588261_psmv3_60_tmy.csv' and a single axis tracker.

How can I assign Utilityrate5.ElectricityRates.ur_ec_tou_mat, as it is a tuple?

Hi Darice,
This is probably just a python thing, and I'm not really very versed in python, but I need to assign different rates to my different simulations to make a varying rate simulation, and unfortunately, I don't know how to change the value of a tuple.

type(ur.ElectricityRates.ur_ec_tou_mat)
Out[114]: tuple

Paul tried to help me here, but I'm still stuck.
Thanks,
Rob

Python layer for customizing PySAM Classes

A Python layer around the PySAM C Extension classes will allow the addition of Python functions to the PySAM classes without having to write C code.

In the SSC repo, I am moving towards making auxiliary functions (calculating cec parameters, calculating turbine powercurve, etc) available as standalone C functions that can be used from the SDK, the GUI, or PySAM. This involves moving functions such as Turbine_calculate_powercurve(https://github.com/NREL/ssc/blob/wind_pruf/ssc/cmod_windpower_eqns.cpp) from an LK script into an exported C function, and binding methods of PySAM classes to use these C functions.

The currently implementation Windpower_eqns.c is reliant on C. To make it easier to develop future auxiliary functions in Python for PySAM classes, a Python class layer wrapping the C Extension should be used. This layer can also be used to introduce pure Python methods to the class, when appropriate-- such as when they are not needed in the SAM GUI, C++ SDK or any other platform.

'system_use_lifetime_output' not working with Pvwattsv7

I'm trying to get a multi-year generation profile from Pvwattsv7, I believe I should be using the system_use_lifetime_output argument to specify this, and than accessing generator.Outputs.dc, however the length of the output array is still only 8760.

import PySAM.Pvwattsv7 as pv

# --- Initialize Generator ---
generator = pv.default('PVWattsMerchantPlant')

# --- Load Resource File from FetchResourceFile ---
generator.SolarResource.solar_resource_file = 'data/PySAM Downloaded Weather Files/-83.572_41.475_psm3_60_tmy.csv'

# --- Assign 20 year lifetime ---
generator.Lifetime.assign({'system_use_lifetime_output':1,
                           'analysis_period':3,
                           'dc_degradation':[0.005]*3})

# --- Execute ---
generator.execute()

print(len(generator.Outputs.dc))
output> 8760

Am I missing an argument? Version 2.0.2 install with pip.

Thanks!

ResourceTools for PySAM 2.1.4 need to use PySAM 2.1.5.dev

ResourceTools was updated for recent NSRDB api changes in PySAM 2.1.5.dev3 -- please use this version if you are running into issues.

snippet of example traceback:

/usr/local/anaconda3/envs/pysam/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2895                 return self._engine.get_loc(casted_key)
   2896             except KeyError as err:
-> 2897                 raise KeyError(key) from err
   2898
   2899         if tolerance is not None:
KeyError: 'Year'

See #53

FetchResourceFileExample.py not working

Maybe I'm doing something incorrect. I'm trying to use the code FetchResourceFileExample.py to download wind data but I always encounter the some issues.

Initially I have the following error when running (wtkfetcher.fetch(lon_lats)):
Beginning data download for wind using 1 thread workers
Downloading wind toolkit file for 39.7383155_-105.1800775...
C:\Users\JonnSmithi\anaconda3\lib\site-packages\urllib3\connectionpool.py:1004: InsecureRequestWarning: Unverified HTTPS request is being made to host 'developer.nrel.gov'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning,

Then moving on when I run the code I get the following error: windpower execution error. exec fail(windpower): failed to read local weather file: error at year_response could not open file for reading: error at year_response

At the line 35 when I'm using: wtk_path_dict = wtkfetcher.resource_file_paths_dict, I obtain a dictionary in Python with the key equals to the lon and lat and as a value a string = 'error at year_response' (I have changed location and years[2007 to 2013] but always the same error occurs)

What I'm doing wrong? can you please help me with this?

Thank you very much in advance

Fix stubs for version 2+

The files & init.py were not added to the packages correctly due to changes in the build process.

New packages for Anaconda cloud and PyPi will be released with versions: 2.0.2.post0, 2.1.1.post0 and 2.1.3.post0.

SAM and PySAM don't agree?

I probably don't understand what I'm doing, but it seems to me that the 2020.1.17 beta is not giving me the same results when I import the .json data from SAM as SAM gives me.

What I did was to export my pvwatts7 simulation from SAM, and I tried to import it following the example. It seems to run okay, and some values especially from PWwatts7 agree, but some, especially the financial model do not agree.

I'm enclosing a .zip with the .json and the .py files. You will need Tkinter installed to pick the files, or modify the source code if you like.

I'm just trying to make sure I understand what I'm doing by trying to duplicate what SAM is telling me before I try running my calculations to calculate npv and payback period for a changing electricity price.

Any help would be appreciated. And my apologies if I'm just doing something stupid. It is kind of likely. :-)

Example_Problem.zip

seg fault on Mac OS Catalina

reV wind gen test seg faults when run on Mac OS Catalina

repo: https://github.com/nrel/reV
Test: https://github.com/nrel/reV/tests/test_gen_wind.py:

Env:
Mac OS Catalina
Version 10.15.3

Python 3.7.6
PySAM 1.2.1

Traceback:
pytest -v test_gen_wind.py
================================================================================ test session starts ================================================================================
platform darwin -- Python 3.7.6, pytest-5.3.2, py-1.8.1, pluggy-0.13.1 -- /Users/mrossol/miniconda3/envs/rev/bin/python
cachedir: .pytest_cache
rootdir: /Users/mrossol/Git_Repos/reV
collected 5 items

test_gen_wind.py::test_wind_gen_slice[project_outputs.h5-rev2_points0-2012-1] PASSED [ 20%]
test_gen_wind.py::test_wind_gen_slice[project_outputs.h5-rev2_points1-2013-1] PASSED [ 40%]
test_gen_wind.py::test_wind_gen_new_outputs Fatal Python error: Aborted

Current thread 0x0000000104a8fdc0 (most recent call first):
File "/Users/mrossol/Git_Repos/reV/reV/SAM/generation.py", line 731 in default
File "/Users/mrossol/Git_Repos/reV/reV/generation/generation.py", line 309 in _get_data_shape
File "/Users/mrossol/Git_Repos/reV/reV/generation/generation.py", line 497 in site_mem
File "/Users/mrossol/Git_Repos/reV/reV/generation/generation.py", line 468 in site_limit
File "/Users/mrossol/Git_Repos/reV/reV/generation/generation.py", line 411 in _init_out_arrays
File "/Users/mrossol/Git_Repos/reV/reV/generation/generation.py", line 179 in init
File "/Users/mrossol/Git_Repos/reV/reV/generation/generation.py", line 1297 in reV_run
File "/Users/mrossol/Git_Repos/reV/tests/test_gen_wind.py", line 116 in test_wind_gen_new_outputs
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/python.py", line 166 in pytest_pyfunc_call
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/callers.py", line 187 in _multicall
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/manager.py", line 87 in
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/manager.py", line 93 in _hookexec
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/hooks.py", line 286 in call
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/python.py", line 1435 in runtest
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/runner.py", line 131 in pytest_runtest_call
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/callers.py", line 187 in _multicall
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/manager.py", line 87 in
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/manager.py", line 93 in _hookexec
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/hooks.py", line 286 in call
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/runner.py", line 207 in
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/runner.py", line 234 in from_call
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/runner.py", line 207 in call_runtest_hook
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/runner.py", line 182 in call_and_report
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/runner.py", line 96 in runtestprotocol
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/runner.py", line 81 in pytest_runtest_protocol
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/callers.py", line 187 in _multicall
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/manager.py", line 87 in
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/manager.py", line 93 in _hookexec
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/hooks.py", line 286 in call
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/main.py", line 270 in pytest_runtestloop
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/callers.py", line 187 in _multicall
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/manager.py", line 87 in
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/manager.py", line 93 in _hookexec
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/hooks.py", line 286 in call
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/main.py", line 246 in _main
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/main.py", line 196 in wrap_session
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/main.py", line 239 in pytest_cmdline_main
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/callers.py", line 187 in _multicall
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/manager.py", line 87 in
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/manager.py", line 93 in _hookexec
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/pluggy/hooks.py", line 286 in call
File "/Users/mrossol/miniconda3/envs/rev/lib/python3.7/site-packages/_pytest/config/init.py", line 92 in main
File "/Users/mrossol/miniconda3/envs/reV/bin/pytest", line 11 in
[1] 22203 abort pytest -v test_gen_wind.py

Net Present Value in SAM and PySAM Don't Agree

This is in the 2020.1.17 beta and the 2020.2.24 beta. I mentioned this in a previous issue, but at that time I thought the problem was that PVWatts wasn't giving me the correct data, and that caused the NPV to be off, but PVWatts was not the problem. I thought I better open a new issue, because that one still has unanswered questions, but this one is really somewhat separate.

I tried this with the default project, and SAM and PySAM agree.
Steps to reproduce:

  • Unzip the files enclosed.
  • Load the enclosed SAM file.
  • Run the simulation for the simulation titled NPV Not Right.
  • Note the NPV is $196,043.
  • Generate code -> JSON for inputs
  • Put it in the directory with the enclosed python script.
  • Run the python script.
  • Note the cl.Outputs.npv is $200,340.

I hope this is useful. The difference isn't enough to cause me great grief, but something seems amiss. If you see anything wrong with my python script, please let me know. I'm using it as an example for the docs.
Thanks,
Rob
NPV_Not_Right.zip

Make stubs a dependency for conda packages

The stubs package provides autocompletion and static typing for the package. This increases usability in IDEs which support stub files (PyCharm for instance).

Currently, installation via conda install requires both nrel-pysam and nrel-pysam-stubs to be downloaded separately.

With pip install, the nrel-pysam download will install the stubs package as a dependency automatically.

Issue with assigning inverter parameters for Pvsamv1 model.

I'm attempting to build a PVsamv1 (Photovoltaic (Detailed)) model and am running into an issue with assigning the temperature derate curve parameter in the InverterDatasheet Group. I get the same issue in the CEC Inverter Database group.

I am able to assign the Inverter model set to datasheet. If I then try to assign the datasheet without the 'inv_tdc_ds' parameter set, I get a PySAM.error: "pvsamv1 execution error. precheck input: variable 'inv_tdc_ds' required but not assigned". Cool, makes sense since this is listed as a required parameter. I don't have the derate curves in this case so I set to '1' since they are not provided, as per the documentation. Then, upon running model.execute(), I just get:

"model.InverterDatasheet.assign(inv_datasheet)
PySAM.error"

With no message beyond this.

Wondering what I'm doing wrong, thanks!

Pip install causing "SAMNIDIR" error

Based on issue 4 responses, my laptop is a 64-bit machine. I setup a new virtual env for a new project if that might cause the issue.

Otherwise I get this error.

   Complete output (7 lines):
    
Traceback (most recent call last):
      
File "<string>", line 1, in <module>
      
File "C:\\Temp\pip-install-0qja93qc\NREL-PySAM\setup.py", line 24, in <module>
        defaults_dir = os.environ['SAMNTDIR']+"/api/api_autogen/library/defaults/"
      
File "C:\Users\\AppData\Local\Programs\Python\Python38-32\lib\os.py", line 675, in __getitem__
        raise KeyError(key) from None
    
KeyError: 'SAMNTDIR'

    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.`

Example: "To Import a System from the SAM GUI" seems broken....

This example has this error:
Traceback (most recent call last):

File "/home/frohro/SAM/2020.1.17/LEAC1_test.py", line 25, in
so.execute()

error: singleowner execution error. precheck input: variable 'ppa_price_input' required but not assigned

I'm using the beta 2020.1.17 when I do this, and PySAM 2.02. In SAM I simply added a new Generic System, and went to Generate, and generated the .json for it. It was untitled(1).

I'll insert my code in case it is useful. I just copied and pasted it from the example.

import json
import PySAM.GenericSystem as GenericSystem
import PySAM.Singleowner as Singleowner
from PySAM.PySSC import *
ssc = PySSC()
with open("/home/frohro/SAM/2020.1.17/untitled__1_.json") as f:
    dic = json.load(f)
    gs_dat = dict_to_ssc_table(dic, "generic_system")
    so_dat = dict_to_ssc_table(dic, "singleowner")
    gs = GenericSystem.wrap(gs_dat)
    # to create GenericSystem and Singleowner combined simulation, sharing the same data
    so = Singleowner.from_existing(gs)
    so.assign(Singleowner.wrap(so_dat).export())
    gs.execute()
    so.execute()
    so.Outputs.export() # as dictionary
    print('gs.Outputs.ac_annual: ', gs.Outputs.ac_annual)

This issue isn't really important to me, but I thought I would report it. The one I care about will be next. :-)

BatteryStateful `setup` Error: Unhandled Exception

If BatteryStateful's setup function fails, the error is not conveyed to the user on Windows.

Turns out the issue was due to exceptions being thrown across the DLL barrier in the dll exported function ssc_stateful_module_setup. This behavior is unsafe as it depends on the C++ ABI being the same across the caller and the ssc library.

@qualand

UTC Timezone issues with ResourceTools

When fetching files from the NSRDB using PySAM.ResourceTools.FetchResourceFiles(tech='pv'), the returned csv file lists the time zone = 0, or in UTC time. According to the NSRDB API documentation, it states that the utc parameter in the API call must be set to false:

# Specify Coordinated Universal Time (UTC), 'true' will use UTC, 'false' will use the local time zone of the data.
  # NOTE: In order to use the NSRDB data in SAM, you must specify UTC as 'false'. SAM requires the data to be in the
  # local time zone.

However, in the _NSRDB_worker function in ResourceTools the lookup_query_url variable does not include the &utc=false parameter

helper function for Wind and Solar resource data

The structure for wind data to input into Windpower's wind_resource_data is complicated. A helper function that organizes the appropriate inputs from file or from memory would increase the usability of wind_resource_data, which provides a speedier way to run simulations.

The same is true for Pvsamv1 and Pvwattsv5's solar_resource_data feature.

Improve user friendliness of lat, long inputs in ResourceTools

The ResourceTools module currently requires coordinates to be entered as (longitude, latitude), which creates a frustrating user experience when you have to convert the standard (latitude, longitude) format to the reverse order. It is also confusing because the resource files are saved in the (latitude, longitude) order rather than the other way around.

Could the fetch() function please be updated so that the coordinate naming convention is consistent and more user friendly?

Thank you

Groups should not be overwrite-able

Currently, PySAM groups can be overwritten and the reference to the appropriate PySAM structure is then lost.

For instance: model.SolarResource = 10 will overwrite the SolarResource group with all its variable attributes.

BatteryTools.size_li_ion_battery(): Is`batt_power_discharge_max_kwac` really AC?

Hi there,

I am wondering if the setting of batt_power_charge_max_kwac (and batt_power_discharge_max_kwac) in the size_li_ion_battery() function of BatteryTools is truly expressed in AC. Let's consider the case where the model's batt_ac_or_dc key in BatterySystem is set to 1.0, and therefore the ac_connected (this line) and size_by_ac_not_dc (this line) booleans are both True. The desired_power variable is mutated here and converted to DC. It then seems that desired_power is still in DC when assigned to batt_power_charge_max_kwac, see this line and this line. Is this a bug, or am I misunderstanding the code?

thanks for looking into it!

Add tz output to all solar and wind modules

The PVWatts7 module includes a time zone output. However, this output does not seem to exist for any of the other modules, including the windpower modules and concentrating solar power modules.

Especially when working with resources across multiple time zones, it would be nice to have this output so that timeseries outputs can be easily converted to a single time zone.

KeyError in _csv_to_srw

I am using v2.1.4 of PySAM

Whenever I try to fetch data from the windtoolkit using the following code:

lon_lats = [(-106.21,41.60)]
wtkfetcher = tools.FetchResourceFiles(
                tech='wind',
                workers=1,  # thread workers if fetching multiple files
                nrel_api_key=nrel_api_key,
                nrel_api_email=nrel_api_email,
                resource_year=2007,
                resource_dir='PySAM Downloaded Weather Files/Onshore_Wind')
wtkfetcher.fetch(lon_lats)

I keep getting a KeyError, which seems to be raised in the _csv_to_srw function, in particular in line 305 site_year = df.iloc[0]['Year'].

One strange aspect about this error is that when I check the source code here, the code seems to be different.

Full error output is below:

Beginning data download for wind using 1 thread workers
Downloading wind toolkit file for 41.6_-106.21...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\anaconda3\envs\time-coincident\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
   4410             try:
-> 4411                 return libindex.get_value_at(s, key)
   4412             except IndexError:

pandas\_libs\index.pyx in pandas._libs.index.get_value_at()

pandas\_libs\index.pyx in pandas._libs.index.get_value_at()

pandas\_libs\util.pxd in pandas._libs.util.get_value_at()

pandas\_libs\util.pxd in pandas._libs.util.validate_indexer()

TypeError: 'str' object cannot be interpreted as an integer

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
 in 
     10 
     11 #fetch resource data from the dictionary
---> 12 wtkfetcher.fetch(lon_lats)

~\anaconda3\envs\time-coincident\lib\site-packages\PySAM\ResourceTools.py in fetch(self, points)
    452             results = []
    453             for job in points:
--> 454                 results.append(self.data_function(job))
    455 
    456         self.resource_file_paths = results

~\anaconda3\envs\time-coincident\lib\site-packages\PySAM\ResourceTools.py in _windtk_worker(self, job)
    425                 # --- Convert response to string, read as pandas df, write to csv ---
    426                 raw_csv = io.StringIO(year_response.text)
--> 427                 df = self._csv_to_srw(raw_csv)
    428                 df.to_csv(file_path, index=False, header=False, na_rep='')
    429                 return file_path

~\anaconda3\envs\time-coincident\lib\site-packages\PySAM\ResourceTools.py in _csv_to_srw(self, raw_csv)
    303         site_lon = header[1, 1]
    304         site_lat = header[2, 1]
--> 305         site_year = df.iloc[0]['Year']
    306 
    307         # --- create header lines ---

~\anaconda3\envs\time-coincident\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    869         key = com.apply_if_callable(key, self)
    870         try:
--> 871             result = self.index.get_value(self, key)
    872 
    873             if not is_scalar(result):

~\anaconda3\envs\time-coincident\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
   4417                     raise InvalidIndexError(key)
   4418                 else:
-> 4419                     raise e1
   4420             except Exception:
   4421                 raise e1

~\anaconda3\envs\time-coincident\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
   4403         k = self._convert_scalar_indexer(k, kind="getitem")
   4404         try:
-> 4405             return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
   4406         except KeyError as e1:
   4407             if len(self) > 0 and (self.holds_integer() or self.is_boolean()):

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'Year'

Conda installation did not work for me

$ conda config --append channels NREL-PySAM
$ conda config --show channels
channels:
  - dsdale24
  - defaults
  - NREL-PySAM
$ conda install -c nrel nrel-pysam
Collecting package metadata (repodata.json): failed

UnavailableInvalidChannel: The channel is not accessible or is invalid.
  channel name: NREL-PySAM
  channel url: https://conda.anaconda.org/NREL-PySAM
  error code: 404

You will need to adjust your conda configuration to proceed.
Use `conda config --show channels` to view your configuration's current state,
and use `conda config --show-sources` to view config file locations.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.