def sunpath_from_location( lat, lon, tz, north, folder, name, log_file, start_date, start_time, end_date, end_time, timestep, leap_year, reverse_vectors): """Generate a non climate-based sunpath for a location. This command also generates a mod file which includes all the modifiers in sunpath. mod file is usually used with rcontrib command to indicate the list of modifiers. Since rcontrib command has a hard limit of 10,000 modifiers in a single run the files will be broken down into multiple files if number of modifiers is more than 10000 modifiers. """ location = Location() location.latitude = lat location.longitude = lon location.time_zone = tz try: sp = Sunpath(location, north) hoys = get_hoys(start_date, start_time, end_date, end_time, timestep, leap_year) sp_files = sp.to_file( folder, name, hoys=hoys, leap_year=leap_year, reverse_vectors=reverse_vectors ) files = [ {'path': os.path.relpath(path, folder), 'full_path': path} for path in sp_files['suns'] ] log_file.write(json.dumps(files)) except Exception: _logger.exception('Failed to generate sunpath.') sys.exit(1) else: sys.exit(0)
def test_json_methods(self): """Test JSON serialization functions""" city = 'Tehran' country = 'Iran' latitude = 36 longitude = 34 time_zone = 3.5 elevation = 54 loc = Location(city=city, country=country, latitude=latitude, longitude=longitude, time_zone=time_zone, elevation=elevation) assert loc.to_json() == {"city": city, "country": country, "latitude": latitude, "longitude": longitude, "time_zone": time_zone, "elevation": elevation} loc_from_json = Location.from_json(loc.to_json()) assert loc_from_json.city == city assert loc_from_json.latitude == latitude assert loc_from_json.longitude == longitude assert loc_from_json.time_zone == time_zone assert loc_from_json.elevation == elevation assert loc_from_json.country == country
def test_dict_methods(): """Test JSON serialization functions""" city = 'Tehran' country = 'Iran' latitude = 36 longitude = 34 time_zone = 3.5 elevation = 54 loc = Location(city=city, country=country, latitude=latitude, longitude=longitude, time_zone=time_zone, elevation=elevation) assert loc.to_dict() == {"city": city, "state": '-', "country": country, "latitude": latitude, "longitude": longitude, "time_zone": time_zone, "elevation": elevation, "station_id": None, "source": None} loc_from_dict = Location.from_dict(loc.to_dict()) assert loc_from_dict.city == city assert loc_from_dict.latitude == latitude assert loc_from_dict.longitude == longitude assert loc_from_dict.time_zone == time_zone assert loc_from_dict.elevation == elevation assert loc_from_dict.country == country
def test_json_methods(self): """Test JSON serialization functions""" city = 'Tehran' country = 'Iran' latitude = 36 longitude = 34 time_zone = 3.5 elevation = 54 loc = Location(city=city, country=country, latitude=latitude, longitude=longitude, time_zone=time_zone, elevation=elevation) assert loc.to_json() == { "city": city, "country": country, "latitude": latitude, "longitude": longitude, "time_zone": time_zone, "elevation": elevation } loc_from_json = Location.from_json(loc.to_json()) assert loc_from_json.city == city assert loc_from_json.latitude == latitude assert loc_from_json.longitude == longitude assert loc_from_json.time_zone == time_zone assert loc_from_json.elevation == elevation assert loc_from_json.country == country
def test_north_south_pole(): """Test to be sure we don't get a math domain error at the poles.""" loc = Location("Santa's House", None, 'North Pole', 90, 0, 0, 0) sp = Sunpath.from_location(loc) suns = sp.hourly_analemma_suns() assert len(suns) == 24 loc = Location("Santa's Other House", None, 'South Pole', -90, 0, 0, 0) sp = Sunpath.from_location(loc) suns = sp.hourly_analemma_suns() assert len(suns) == 24
def extract_location(climate_file, time_zone=None): """Extract a Ladybug Location object from the data in the CSV. Args: climate_file: file path to the NCDC .csv file. time_zone: Optional integer for the time zone. If None, it will be estimated from the longitude in the file. """ with open(climate_file) as station_file: station_file.readline() # Skip header row # get the pattern of data within the file dat_line = station_file.readline().strip().split(',') # parse all of the info from the file station_id = dat_line[0].replace('"', '') city = dat_line[6].replace('"', '') latitude = float(dat_line[3].replace('"', '')) longitude = float(dat_line[4].replace('"', '')) elevation = float(dat_line[5].replace('"', '')) # estimate or parse time zone. if time_zone: assert -12 <= time_zone <= 14, ' time_zone must be between -12 and '\ ' 14. Got {}.'.format(time_zone) time_zone = time_zone else: time_zone = int((longitude / 180) * 12) # build the location object location = Location( city=city, latitude=latitude, longitude=longitude, time_zone=time_zone, elevation=elevation, station_id=station_id, source='NCDC') return location, time_zone
def test_to_urbanopt_electric_network(): """Test the Model.to.urbanopt method with an ElectricNetwork.""" model_json = './tests/json/buffalo_test_district.dfjson' with open(model_json) as json_file: data = json.load(json_file) model = Model.from_dict(data) network_json = './tests/json/buffalo_electric_grid.json' with open(network_json) as json_file: data = json.load(json_file) network = ElectricalNetwork.from_dict(data) # create the urbanopt folder location = Location('Buffalo', 'NY', 'USA', 42.813153, -78.852466) sim_folder = './tests/urbanopt_model_buffalo' geojson, hb_model_jsons, hb_models = \ model.to.urbanopt(model, location, electrical_network=network, folder=sim_folder) # check that the appropriate files were generated assert os.path.isfile(geojson) for model_json in hb_model_jsons: assert os.path.isfile(model_json) for h_model in hb_models: assert isinstance(h_model, hb_model.Model) assert os.path.isfile(os.path.join(sim_folder, 'electrical_database.json')) # clean up the files nukedir(sim_folder, True)
def from_json(cls, rec_json): """Create the solar access recipe from json. { "id": "solar_access", "type": "gridbased", "location": null, // a honeybee location - see below "hoys": [], // list of hours of the year "surfaces": [], // list of honeybee surfaces "analysis_grids": [] // list of analysis grids "sun_vectors": [] // list of sun vectors if location is not provided } """ hoys = rec_json["hoys"] if 'sun_vectors' not in rec_json or not rec_json['sun_vectors']: # create sun vectors from location inputs loc = Location.from_json(rec_json['location']) sp = Sunpath.from_location(loc) suns = (sp.calculate_sun_from_hoy(hoy) for hoy in hoys) sun_vectors = tuple(s.sun_vector for s in suns if s.is_during_day) else: sun_vectors = rec_json['sun_vectors'] analysis_grids = \ tuple(AnalysisGrid.from_json(ag) for ag in rec_json["analysis_grids"]) hb_objects = tuple(HBSurface.from_json(srf) for srf in rec_json["surfaces"]) return cls(sun_vectors, hoys, analysis_grids, 1, hb_objects)
def test_daylight_saving(): """Test the applicaiton of daylight saving time.""" nyc = Location('New_York', country='USA', latitude=40.72, longitude=-74.02, time_zone=-5) daylight_saving = AnalysisPeriod(st_month=3, st_day=8, st_hour=2, end_month=11, end_day=1, end_hour=2) sp = Sunpath.from_location(nyc, daylight_saving_period=daylight_saving) dt1 = DateTime(6, 21, 12, 0) dt2 = DateTime(12, 21, 12, 0) dt3 = DateTime(6, 21, 0) dt4 = DateTime(12, 21, 0) assert sp.is_daylight_saving_hour(dt1) assert not sp.is_daylight_saving_hour(dt2) assert sp.is_daylight_saving_hour(dt3) assert not sp.is_daylight_saving_hour(dt4) sun1ds = sp.calculate_sun_from_date_time(dt1) sun2ds = sp.calculate_sun_from_date_time(dt2) sun3ds = sp.calculate_sun_from_date_time(dt3) sun4ds = sp.calculate_sun_from_date_time(dt4) sp.daylight_saving_period = None assert sun1ds != sp.calculate_sun_from_date_time(dt1) assert sun3ds != sp.calculate_sun_from_date_time(dt3) assert sun1ds.altitude == \ approx(sp.calculate_sun_from_date_time(dt1.sub_hour(1)).altitude, rel=1e-2) assert sun3ds.altitude == \ approx(sp.calculate_sun_from_date_time(dt3.sub_hour(1)).altitude, rel=1e-2) sun2 = sp.calculate_sun_from_date_time(dt2) sun4 = sp.calculate_sun_from_date_time(dt4) assert sun2 == sun2ds assert sun4 == sun4ds
def test_from_geojson_units_test(): """Test the Model from_geojson method with non-meter units.""" # Load test geojson geojson_folder = os.path.join(os.getcwd(), 'tests', 'geojson') geo_fp = os.path.join(geojson_folder, 'TestGeoJSON.geojson') location = Location('Boston', 'MA', 'USA', 42.366151, -71.019357) model, loc = Model.from_geojson(geo_fp, location=location, units='Feet') # Check the first building bldg1 = [bldg for bldg in model.buildings if bldg.identifier == 'ResidenceBuilding'][0] # Check properties assert bldg1.identifier == 'ResidenceBuilding' assert bldg1.display_name == 'ResidenceBuilding' # Check if area is in feet square m2ft = 1 / hb_model.Model.conversion_factor_to_meters('Feet') sm2sft = m2ft * m2ft assert (600.0 * sm2sft) == pytest.approx(bldg1.floor_area, abs=1e-5) assert (200.0 * sm2sft) == pytest.approx(bldg1.footprint_area, abs=1e-5) assert bldg1.story_count == 3 # Check story assert bldg1.story_count == 3 assert len(bldg1.unique_stories) == 1 for story in bldg1.unique_stories: assert (3.0) == pytest.approx(story.floor_to_floor_height, abs=1e-10)
def from_json(cls, loc_json): """Create sky form json. { "location": {}, // honeybee (or actually ladybug location schema) "day": 1, // an integer between 1-31 "month": 1, // an integer between 1-12 "hour": 12.0, // a float number between 0-23 "north": 0, // degree for north if not Y axis "sky_type": 0 // A number between 0-5 -- 0: sunny sky } location schema { "city": "", "latitude": 0, "longitude": 0, "time_zone": 0, "elevation": 0 } """ data = loc_json location = Location.from_json(data["location"]) return cls(location, month=data["month"], day=data["day"], hour=data["hour"], north=data["north"], sky_type=data["sky_type"])
def from_json(cls, rec_json): """Create the solar access recipe from json. { "id": "solar_access", "type": "gridbased", "location": null, // a honeybee location - see below "hoys": [], // list of hours of the year "surfaces": [], // list of honeybee surfaces "analysis_grids": [] // list of analysis grids "sun_vectors": [] // list of sun vectors if location is not provided } """ raise NotImplementedError() hoys = rec_json["hoys"] if 'sun_vectors' not in rec_json or not rec_json['sun_vectors']: # create sun vectors from location inputs loc = Location.from_json(rec_json['location']) sp = Sunpath.from_location(loc) suns = (sp.calculate_sun_from_hoy(hoy) for hoy in hoys) sun_vectors = tuple(s.sun_vector for s in suns if s.is_during_day) else: sun_vectors = rec_json['sun_vectors'] analysis_grids = \ tuple(AnalysisGrid.from_json(ag) for ag in rec_json["analysis_grids"]) hb_objects = tuple( HBSurface.from_json(srf) for srf in rec_json["surfaces"]) return cls(sun_vectors, hoys, analysis_grids, 1, hb_objects)
def test_init(): """Test if the command correctly creates location based on individual values""" # This is totally a real place! It's in Wales, check it out! city = 'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch' country = 'United Kingdom' latitude = 53.2225252 longitude = -4.2211707 time_zone = 1 elevation = 12 station_id = 'SomeInventedStation' source = 'SomeNoneExistentSource' loc = Location(city=city, country=country, latitude=latitude, longitude=longitude, time_zone=time_zone, elevation=elevation, station_id=station_id, source=source) str(loc) # test the string representation assert loc.city == city assert loc.country == country assert loc.latitude == latitude assert loc.longitude == longitude assert loc.time_zone == time_zone assert loc.elevation == elevation assert loc.station_id == station_id assert loc.source == source assert loc.meridian == -15
def test_day_arc_geometry(): """Test the day_arc3d method.""" nyc = Location('New_York', country='USA', latitude=40.72, longitude=-74.02, time_zone=-5) sp = Sunpath.from_location(nyc) radius = 100 arc_geo = sp.day_arc3d(3, 21, radius=radius) assert isinstance(arc_geo, Arc3D) assert arc_geo.length == approx(math.pi * radius, rel=1e-2) arc_geo = sp.day_polyline2d(3, 21, radius=radius) assert isinstance(arc_geo, Polyline2D) arc_geo = sp.monthly_day_arc3d(radius=radius) assert len(arc_geo) == 12 for pline in arc_geo: assert isinstance(pline, Arc3D) arc_geo = sp.monthly_day_polyline2d(radius=radius) assert len(arc_geo) == 12 for pline in arc_geo: assert isinstance(pline, Polyline2D)
def test_init_horizontal_solarcal_collection(): """Test the initialization of the HorizontalSolarCal collection.""" calc_length = 24 irr_header = Header(Irradiance(), 'W/m2', AnalysisPeriod(end_month=1, end_day=1)) dir_norm = HourlyContinuousCollection(irr_header, [300] * calc_length) diff_horiz = HourlyContinuousCollection(irr_header, [100] * calc_length) solarcal_obj = HorizontalSolarCal(Location(), dir_norm, diff_horiz, 24) assert solarcal_obj.comfort_model == 'Horizontal SolarCal' assert solarcal_obj.calc_length == calc_length str(solarcal_obj) # test that the string representation is ok assert isinstance(solarcal_obj.direct_horizontal_solar, HourlyContinuousCollection) assert len(solarcal_obj.direct_horizontal_solar.values) == calc_length assert solarcal_obj.direct_horizontal_solar[12] == 300 assert isinstance(solarcal_obj.diffuse_horizontal_solar, HourlyContinuousCollection) assert len(solarcal_obj.diffuse_horizontal_solar.values) == calc_length assert solarcal_obj.diffuse_horizontal_solar[12] == 100 assert isinstance(solarcal_obj.effective_radiant_field, HourlyContinuousCollection) assert len(solarcal_obj.effective_radiant_field.values) == calc_length assert solarcal_obj.effective_radiant_field[12] == pytest.approx(79.35027, rel=1e-3) assert isinstance(solarcal_obj.mrt_delta, HourlyContinuousCollection) assert len(solarcal_obj.mrt_delta.values) == calc_length assert solarcal_obj.mrt_delta[12] == pytest.approx(18.20503, rel=1e-3) assert isinstance(solarcal_obj.mean_radiant_temperature, HourlyContinuousCollection) assert len(solarcal_obj.mean_radiant_temperature.values) == calc_length assert solarcal_obj.mean_radiant_temperature[12] == pytest.approx(42.20503, rel=1e-3)
def test_horizontal_solarcal_collection_defaults(): """Test the default inputs assigned to the HorizontalSolarCal collection.""" calc_length = 24 irr_header = Header(Irradiance(), 'W/m2', AnalysisPeriod(end_month=1, end_day=1)) dir_norm = HourlyContinuousCollection(irr_header, [500] * calc_length) diff_horiz = HourlyContinuousCollection(irr_header, [200] * calc_length) solarcal_obj = HorizontalSolarCal(Location(), dir_norm, diff_horiz, 24) assert isinstance(solarcal_obj.fraction_body_exposed, HourlyContinuousCollection) assert len(solarcal_obj.fraction_body_exposed.values) == calc_length assert solarcal_obj.fraction_body_exposed[12] == 1 assert isinstance(solarcal_obj.floor_reflectance, HourlyContinuousCollection) assert len(solarcal_obj.floor_reflectance.values) == calc_length assert solarcal_obj.floor_reflectance[12] == 0.25 assert isinstance(solarcal_obj.solarcal_body_parameter, SolarCalParameter) default_par = SolarCalParameter() assert solarcal_obj.solarcal_body_parameter.posture == default_par.posture assert solarcal_obj.solarcal_body_parameter.sharp == default_par.sharp assert solarcal_obj.solarcal_body_parameter.body_azimuth == default_par.body_azimuth assert solarcal_obj.solarcal_body_parameter.body_absorptivity == default_par.body_absorptivity assert solarcal_obj.solarcal_body_parameter.body_emissivity == default_par.body_emissivity
def from_lat_long(cls, city, latitude, longitude, timezone, elevation, month, day, hour, direct_radiation, diffuse_radiation, north=0, suffix=None): """Create sky from latitude and longitude.""" loc = Location(city, None, latitude, longitude, timezone, elevation) return cls(loc, month, day, hour, direct_radiation, diffuse_radiation, north, suffix=suffix)
def from_idf(cls, design_days=None, sizing_parameter=None, location=None): """Create a SizingParameter object from an EnergyPlus IDF text string. Args: design_days: An array of of IDF SizingPeriod:DesignDay strings that represent the criteria for which the HVAC systems will be sized. If None, no sizing criteria will be included. Default: None. sizing_parameter: A text string for an EnergyPlus Sizing:Parameters definition. If None, defaults of 1.25 anf 1.15 will be used. Default: None. location: An optional Ladybug Location object, which gets assigned to the DesignDay objects in order to interpret their SkyConditions. This object is not used in the export to IDF. If None, the intersection of the equator with the prime meridian will be used. Default: None. """ # process the input design_days des_day_objs = None if design_days is not None: location = Location() if location is None else location des_day_objs = [DesignDay.from_idf(dday, location) for dday in design_days] # process the sizing_parameter heating_factor = 1.25 cooling_factor = 1.15 if sizing_parameter is not None: try: ep_strs = parse_idf_string(sizing_parameter, 'Sizing:Parameters,') heating_factor = ep_strs[0] if ep_strs[0] != '' else 1.25 cooling_factor = ep_strs[1] if ep_strs[1] != '' else 1.15 except IndexError: pass # shorter SizingParameters definition return cls(des_day_objs, heating_factor, cooling_factor)
def test_from_location(): """Test the initialization of Sunpath from a Location.""" sydney = Location('Sydney', 'AUS', latitude=-33.87, longitude=151.22, time_zone=10) sunpath = Sunpath.from_location(sydney) assert sunpath.latitude == -33.87 assert sunpath.longitude == 151.22 assert sunpath.time_zone == 10
def test_vs_noaa_new_york(): """Test to be sure that the sun positions align with the NOAA formula.""" nyc = Location('New_York', 'USA', latitude=40.72, longitude=-74.02, time_zone=-5) sp = Sunpath.from_location(nyc) sun = sp.calculate_sun(month=9, day=15, hour=11.0) assert round(sun.altitude, 2) == 50.35 assert round(sun.azimuth, 2) == 159.72
def getSunVector(input_address, input_month, input_day, input_hour): geolocator = Nominatim(user_agent="UrbanInsight") location = geolocator.geocode(input_address) tf = TimezoneFinder() utc = pytz.utc def offset(target): today = datetime.now() tz_target = timezone( tf.certain_timezone_at(lat=target['lat'], lng=target['lng'])) # ATTENTION: tz_target could be None! handle error case today_target = tz_target.localize( datetime(2016, input_month, input_day)) today_utc = utc.localize(datetime(2016, input_month, input_day)) return (today_utc - today_target).total_seconds() / 60 # Create location. You can also extract location data from an epw file. lati = location.latitude long = location.longitude timez = dict({'lat': lati, 'lng': long}) tz = (offset(timez) / 60) # print(tz) city = Location('City', 'Country', latitude=lati, longitude=long, time_zone=tz) # Initiate sunpath sp = Sunpath.from_location(city) sun = sp.calculate_sun(month=input_month, day=input_day, hour=input_hour) # print('altitude: {}, azimuth: {}'.format(sun.altitude, sun.azimuth)) _year_ = 2016 _minute_ = 0 mydate = DateTime(input_month, input_day, input_hour) altitude = sun.altitude_in_radians azimuth = sun.azimuth_in_radians is_solar_time = "false" is_daylight_saving = "false" north_angle = 0 sn = Sun(DateTime, altitude, azimuth, is_solar_time, is_daylight_saving, north_angle, data=None) # print(sun.sun_vector) vector = str(sun.sun_vector) return vector
def test_origin_long_lat_from_location(): """Test the origin_long_lat_from_location method.""" lat = 42.0 lon = -70.0 loc = Location(latitude=lat, longitude=lon) o_lon, o_lat = origin_long_lat_from_location(loc, Point2D(10, 10)) assert lat == pytest.approx(o_lat, rel=1e-5) assert lon == pytest.approx(o_lon, rel=1e-5)
def test_from_individual_values(self): """Test if the command correctly creates location based on individual values""" loc = Location() new_latitude = 31.4234953 new_longitude = 72.9492158 new_time_zone = 5 new_elevation = 20 loc.latitude = new_latitude loc.longitude = new_longitude loc.time_zone = new_time_zone loc.elevation = new_elevation assert loc.latitude == new_latitude assert loc.longitude == new_longitude assert loc.time_zone == new_time_zone assert loc.elevation == new_elevation
def test_from_location(self): sydney = Location('Sydney', 'AUS', latitude=-33.87, longitude=151.22, time_zone=10) sunpath = Sunpath.from_location(sydney) self.assertEqual(sunpath.latitude, -33.87) self.assertEqual(sunpath.longitude, 151.22) self.assertEqual(sunpath.time_zone, 10)
def test_from_location(self): sydney = Location('Sydney', 'AUS', latitude=-33.87, longitude=151.22, time_zone=10) sunpath = Sunpath.from_location(sydney) assert sunpath.latitude == -33.87 assert sunpath.longitude == 151.22 assert sunpath.time_zone == 10
def test_vs_noaa_new_york(self): nyc = Location('New_York', 'USA', latitude=40.72, longitude=-74.02, time_zone=-5) sp = Sunpath.from_location(nyc) sun = sp.calculate_sun(month=9, day=15, hour=11.0) assert round(sun.altitude, 2) == 50.35 assert round(sun.azimuth, 2) == 159.72
def __init__(self, location=None, month=9, day=21, hour=12, north=0, suffix=None): """Create sky.""" RadianceSky.__init__(self) self.location = location or Location() assert hasattr(self.location, 'isLocation'), \ '{} is not a Ladybug Location.'.format(self.location) self._datetime = DateTime(month, day, hour) self.north = float(north % 360) self.suffix = suffix or ''
def test_default_values(): """Test if the command correctly creates a location.""" loc = Location() assert loc.city == '-' assert loc.country == '-' assert loc.latitude == 0 assert loc.longitude == 0 assert loc.time_zone == 0 assert loc.station_id is None assert loc.source is None
def test_vs_noaa_sydney(self): sydney = Location('Sydney', 'AUS', latitude=-33.87, longitude=151.22, time_zone=10) sp = Sunpath.from_location(sydney) sun = sp.calculate_sun(month=11, day=15, hour=11.0) assert round(sun.altitude, 2) == 72.26 assert round(sun.azimuth, 2) == 32.37
def test_solar_time(): """Test to be sure that solar time is being computed correctly.""" loc = Location('SHANGHAI', None, 'HONGQIAO', 31.17, 121.43, 8.0, 7.00) sp = Sunpath.from_location(loc) sun = sp.calculate_sun(3, 21, 12, True) assert sun.azimuth == approx(180, rel=1e-2) sun = sp.calculate_sun(3, 21, 6, True) assert sun.azimuth == approx(90, rel=1e-2) sun = sp.calculate_sun(3, 21, 18, True) assert sun.azimuth == approx(270, rel=1e-2)
def test_design_day_hourly_data(): """Test hourly data properties of a standard ddy.""" location = Location('Test City', '-', 'USA', 34.20, -118.35, -8, 226) date = Date(8, 21) des_day = DesignDay.from_design_day_properties('Test Day', 'SummerDesignDay', location, date, 36.8, 13.2, 'Wetbulb', 20.5, 98639, 3.9, 170, 'ASHRAETau', [0.436, 2.106]) # dry bulb values db_data_collect = des_day.hourly_dry_bulb assert db_data_collect[5] == approx(23.6, rel=1e-1) assert db_data_collect[14] == approx(36.8, rel=1e-1) # dew point values dpt_data_collect = des_day.hourly_dew_point assert dpt_data_collect[0] == approx(11.296, rel=1e-1) assert dpt_data_collect[-1] == approx(11.296, rel=1e-1) # relative humidity values rh_data_collect = des_day.hourly_relative_humidity assert rh_data_collect[5] == approx(45.896, rel=1e-1) assert rh_data_collect[14] == approx(21.508, rel=1e-1) # barometric pressure values bp_data_collect = des_day.hourly_barometric_pressure assert bp_data_collect[0] == approx(98639, rel=1e-1) assert bp_data_collect[-1] == approx(98639, rel=1e-1) # wind speed values ws_data_collect = des_day.hourly_wind_speed assert -0.1 < ws_data_collect[0] - 3.9 < 0.1 assert -0.1 < ws_data_collect[-1] - 3.9 < 0.1 # wind direction values wd_data_collect = des_day.hourly_wind_direction assert wd_data_collect[0] == approx(170, rel=1e-1) assert wd_data_collect[-1] == approx(170, rel=1e-1) # radiation values direct_normal_rad, diffuse_horizontal_rad, global_horizontal_rad = \ des_day.hourly_solar_radiation assert direct_normal_rad[0] == 0 assert direct_normal_rad[11] == approx(891.46, rel=1e-1) assert diffuse_horizontal_rad[0] == 0 assert diffuse_horizontal_rad[11] == approx(165.32, rel=1e-1) assert global_horizontal_rad[0] == 0 assert global_horizontal_rad[11] == approx(985.05, rel=1e-1) # sky cover values sc_data_collect = des_day.hourly_sky_cover # sky cover values hi_data_collect = des_day.hourly_horizontal_infrared
def from_json(cls, inp): """Create a SunMatrix from a dictionary.""" keys = ('location', 'solar_values', 'sun_up_hours', 'hoys') for key in keys: assert key in inp, '%s is missing from input dictionary' % key location = Location.from_json(inp['location']) solar_values = inp['solar_values'] sun_up_hours = inp['sun_up_hours'] hoys = inp['hoys'] return cls(location, solar_values, sun_up_hours, hoys)
def test_exact_solar_noon(): """Test to be sure we don't get a math domain error at solar noon.""" loc = Location('SHANGHAI', None, 'HONGQIAO', 31.17, 121.43, 8.0, 7.00) sp = Sunpath.from_location(loc) suns = [] for i in range(1, 13): sun = sp.calculate_sun(i, 21, 12, True) assert sun.azimuth == approx(180, rel=1e-2) suns.append(sun.sun_vector) assert len(suns) == 12
def test_from_location(self): """Test the from_location() class method""" city = 'Tehran' country = 'Iran' latitude = 36 longitude = 34 time_zone = 3.5 elevation = 54 loc = Location(city=city, country=country, latitude=latitude, longitude=longitude, time_zone=time_zone, elevation=elevation) loc_from_loc = Location.from_location(loc) assert loc_from_loc.city == city assert loc_from_loc.country == country assert loc_from_loc.latitude == latitude assert loc_from_loc.longitude == longitude assert loc_from_loc.time_zone == time_zone assert loc_from_loc.elevation == elevation