Exemplo n.º 1
0
 def end_date_time(self):
     """Get a ladybug DateTime object for the end time of the schedule's values."""
     num_hoys = (len(self._values) - 1) / self.timestep
     end_hoy = (self.start_date.doy - 1) * 24 + num_hoys
     if not self.is_leap_year:
         end_dt = DateTime.from_hoy(end_hoy) if end_hoy < 8760 else \
             DateTime.from_hoy(end_hoy - 8760)
     else:
         end_dt = DateTime.from_hoy(end_hoy, True) if end_hoy < 8784 else \
             DateTime.from_hoy(end_hoy - 8760, True)
     return end_dt
Exemplo n.º 2
0
    def _calculate_solar_values(wea, hoys, output_type, north=0, is_leap_year=False):
        """Calculate solar values for requested hours of the year.

        This method is called everytime that output type is set.
        """
        month_date_time = (DateTime.from_hoy(idx, is_leap_year) for idx in hoys)

        sp = Sunpath.from_location(wea.location, north)
        sp.is_leap_year = is_leap_year
        solar_values = []
        sun_up_hours = []

        # use gendaylit to calculate radiation values for each hour.
        print('Calculating solar values...')
        for timecount, dt in enumerate(month_date_time):
            month, day, hour = dt.month, dt.day, dt.float_hour
            sun = sp.calculate_sun(month, day, hour)
            if sun.altitude < 0:
                continue
            else:
                dnr, dhr = wea.get_irradiance_value(month, day, hour)
                if dnr == 0:
                    solarradiance = 0
                else:
                    solarradiance = \
                        int(gendaylit(sun.altitude, month, day, hour, dnr, dhr,
                                      output_type))

                solar_values.append(solarradiance)
                # keep the number of hour relative to hoys in this sun matrix
                sun_up_hours.append(dt.hoy)

        return solar_values, sun_up_hours
Exemplo n.º 3
0
def set_sun(location, hoy, north=0):
    """Set the sun in the Rhino scene to correspond to a given location and DateTime.

    Args:
        location: A Ladybug Location object to set the latitude, longitude and
            time zone of the Rhino sun path.
        hoy: A number between 0 and 8760 that represent the hour of the year at
            which to evaluate the sun position. Note that this does not need to
            be an integer and decimal values can be used to specify date times
            that are not on the hour mark.
        north: A number between -360 and 360 for the counterclockwise
            difference between the North and the positive Y-axis in degrees.
            90 is West and 270 is East. (Default: 0).

    Returns:
        The Rhino sun object.
    """
    # process the hoy into a .NET date/time
    lb_dt = DateTime.from_hoy(hoy)
    rh_dt = System.DateTime(lb_dt.year, lb_dt.month, lb_dt.day, lb_dt.hour,
                            lb_dt.minute, 0)

    # enable the sun and set its position based on the location and date/time
    sun_position = doc.Lights.Sun
    sun.Enabled.SetValue(sun_position, True)
    sun.TimeZone.SetValue(sun_position, location.time_zone)
    sun.SetPosition(sun_position, rh_dt, location.latitude, location.longitude)

    # set the north of the sun, ensuring the the y-axis is North
    sun.North.SetValue(sun_position, 90 + north)
    return sun
Exemplo n.º 4
0
    def _calculate_solar_values(self):
        """Calculate solar values for requested hours of the year.

        This method is called everytime that output type is set.
        """
        wea = self.wea
        hoys_set = set(wea.hoys)
        output_type = self.output_type
        month_date_time = (DateTime.from_hoy(idx) for idx in self.hoys)

        sp = Sunpath.from_location(wea.location, self.north)

        # use gendaylit to calculate radiation values for each hour.
        print('Calculating solar values...')
        for timecount, dt in enumerate(month_date_time):
            if dt.hoy not in hoys_set:
                print('Warn: Wea data for {} is not available!'.format(dt))
                continue
            month, day, hour = dt.month, dt.day, dt.float_hour
            dnr, dhr = wea.get_radiation_values(month, day, hour)
            sun = sp.calculate_sun(month, day, hour)
            if sun.altitude < 0:
                continue
            if dnr == 0:
                solarradiance = 0
            else:
                solarradiance = \
                    int(gendaylit(sun.altitude, month, day, hour, dnr, dhr, output_type))

            self._solar_values.append(solarradiance)
            # keep the number of hour relative to hoys in this sun matrix
            self._sun_up_hours_indices.append(timecount)
Exemplo n.º 5
0
except ImportError as e:
    raise ImportError('\nFailed to import honeybee:\n\t{}'.format(e))

if _analysis_grid:
    _modes = ('total', 'direct', 'diffuse')
    _mode_ = _mode_ or 0
    _analysis_grid.sum_values_by_id([])
    hoy_ = hoy_ or _analysis_grid.hoys[0]
    assert _mode_ < 3, '_mode_ can only be 0: total, 1: direct or 2: sky.'

    try:
        states = eval(blind_state_)
    except Exception as e:
        if blind_state_:
            raise TypeError('Failed to read blind_state_:\n{}'.format(e))
        states = None
    
    
    if _mode_ < 2:
        values = (v[_mode_] for v in _analysis_grid.combined_value_by_id(hoy_, states))
        if _mode_ != 0 and not _analysis_grid.has_direct_values:
                print('Direct values are not available. Results will be 0.')
    else:
        cValues = tuple(_analysis_grid.combined_value_by_id(hoy_, states))
        if _analysis_grid.has_direct_values:
            print('Loading {} values for {}.'.format(_modes[_mode_],
                                                     DateTime.from_hoy(hoy_)))
            values = (v[0] - v[1] for v in cValues)
        else:
            print('Loading total values for {}.'.format(DateTime.from_hoy(hoy_)))
            values = (v[0] for v in cValues)
Exemplo n.º 6
0
ghenv.Component.NickName = 'DateTime'
ghenv.Component.Message = '1.2.0'
ghenv.Component.Category = 'Ladybug'
ghenv.Component.SubCategory = '1 :: Analyze Data'
ghenv.Component.AdditionalHelpFromDocStrings = '0'

try:
    from ladybug.dt import DateTime
except ImportError as e:
    raise ImportError('\nFailed to import ladybug:\n\t{}'.format(e))

try:
    from ladybug_rhino.grasshopper import all_required_inputs
except ImportError as e:
    raise ImportError('\nFailed to import ladybug:\n\t{}'.format(e))

if all_required_inputs(ghenv.Component):
    month = []
    day = []
    hour = []
    minute = []
    date = []

    for hoy in _hoy:
        datetime = DateTime.from_hoy(hoy)
        month.append(datetime.month)
        day.append(datetime.day)
        hour.append(datetime.hour)
        minute.append(datetime.minute)
        date.append(datetime)
    use_shell = True if os.name == 'nt' else False
    # command for direct patches
    cmds = [gendaymtx_exe, '-m', str(density), '-d', '-O1', '-A', wea_file]
    process = subprocess.Popen(cmds, stdout=subprocess.PIPE, shell=use_shell)
    stdout = process.communicate()
    dir_data_str = stdout[0]
    # command for diffuse patches
    cmds = [gendaymtx_exe, '-m', str(density), '-s', '-O1', '-A', wea_file]
    process = subprocess.Popen(cmds, stdout=subprocess.PIPE, shell=use_shell)
    stdout = process.communicate()
    diff_data_str = stdout[0]

    # parse the data into a single matrix
    dir_vals = parse_mtx_data(dir_data_str, wea_duration, density)
    diff_vals = parse_mtx_data(diff_data_str, wea_duration, density)

    # collect sky metadata like the north, which will be used by other components
    metadata = [north_, ground_r]
    if _hoys_:
        metadata.extend(
            [DateTime.from_hoy(h) for h in (_hoys_[0], _hoys_[-1])])
    else:
        metadata.extend(
            [wea.analysis_period.st_time, wea.analysis_period.end_time])
    for key, val in _direct_rad.header.metadata.items():
        metadata.append('{} : {}'.format(key, val))

    # wrap everything together into an object to output from the component
    mtx_data = (metadata, dir_vals, diff_vals)
    sky_mtx = objectify_output('Cumulative Sky Matrix', mtx_data)
Exemplo n.º 8
0
 def hoy(self, v):
     """Set datetime by hour of year."""
     self._datetime = DateTime.from_hoy(v)
except ImportError as e:
    raise ImportError('\nFailed to import honeybee:\n\t{}'.format(e))

if _analysisGrid:
    _modes = ('total', 'direct', 'diffuse')
    _mode_ = _mode_ or 0
    hoy_ = hoy_ or _analysisGrid.hoys[0]
    assert _mode_ < 3, '_mode_ can only be 0: total, 1: direct or 2: sky.'

    try:
        states = eval(blindState_)
    except Exception as e:
        if blindState_:
            raise TypeError('Failed to read blindState_:\n{}'.format(e))
        states = None

    if _mode_ < 2:
        values = (v[_mode_]
                  for v in _analysisGrid.combined_value_by_id(hoy_, states))
        if _mode_ != 0 and not _analysisGrid.has_direct_values:
            print('Direct values are not available. Results will be 0.')
    else:
        cValues = tuple(_analysisGrid.combined_value_by_id(hoy_, states))
        if _analysisGrid.has_direct_values:
            print('Loading {} values for {}.'.format(_modes[_mode_],
                                                     DateTime.from_hoy(hoy_)))
            values = (v[0] - v[1] for v in cValues)
        else:
            print('Loading total values for {}.'.format(
                DateTime.from_hoy(hoy_)))
            values = (v[0] for v in cValues)
Exemplo n.º 10
0
    def execute(self, working_dir, reuse=True):
        """Generate sun matrix.

        Args:
            working_dir: Folder to execute and write the output.
            reuse: Reuse the matrix if already existed in the folder.

        Returns:
            Full path to analemma, sunlist and sun_matrix.
        """
        fp = os.path.join(working_dir, self.analemmafile)
        lfp = os.path.join(working_dir, self.sunlistfile)
        mfp = os.path.join(working_dir, self.sunmtxfile)
        hrf = os.path.join(working_dir, self.name + '.hrs')
        output_type = self.sky_type

        if reuse:
            if self.hours_match(hrf):
                for f in (fp, lfp, mfp):
                    if not os.path.isfile(f):
                        break
                else:
                    return fp, lfp, mfp

        with open(hrf, 'wb') as outf:
            outf.write(','.join(str(h) for h in self.hoys) + '\n')

        wea = self.wea
        month_date_time = (DateTime.from_hoy(idx) for idx in self.hoys)
        latitude, longitude = wea.location.latitude, -wea.location.longitude

        sp = Sunpath.from_location(wea.location, self.north)
        solarradiances = []
        sun_values = []
        sun_up_hours = []  # collect hours that sun is up
        solarstring = \
            'void light solar{0} 0 0 3 {1} {1} {1} ' \
            'solar{0} source sun 0 0 4 {2:.6f} {3:.6f} {4:.6f} 0.533'

        # use gendaylit to calculate radiation values for each hour.
        print('Calculating sun positions and radiation values.')
        count = 0
        for timecount, timeStamp in enumerate(month_date_time):
            month, day, hour = timeStamp.month, timeStamp.day, timeStamp.hour + 0.5
            dnr, dhr = int(wea.direct_normal_radiation[timeStamp.int_hoy]), \
                int(wea.diffuse_horizontal_radiation[timeStamp.int_hoy])
            if dnr == 0:
                continue
            count += 1
            sun = sp.calculate_sun(month, day, hour)
            if sun.altitude < 0:
                continue
            x, y, z = sun.sun_vector
            solarradiance = \
                int(gendaylit(sun.altitude, month, day, hour, dnr, dhr, output_type))
            cur_sun_definition = solarstring.format(count, solarradiance, -x,
                                                    -y, -z)
            solarradiances.append(solarradiance)
            sun_values.append(cur_sun_definition)
            # keep the number of hour relative to hoys in this sun matrix
            sun_up_hours.append(timecount)

        sun_count = len(sun_up_hours)

        assert sun_count > 0, ValueError('There is 0 sun up hours!')

        print('# Number of sun up hours: %d' % sun_count)
        print('Writing sun positions and radiation values to {}'.format(fp))
        # create solar discs.
        with open(fp, 'w') as annfile:
            annfile.write("\n".join(sun_values))
            annfile.write('\n')

        print('Writing list of suns to {}'.format(lfp))
        # create list of suns.
        with open(lfp, 'w') as sunlist:
            sunlist.write("\n".join(
                ("solar%s" % (idx + 1) for idx in xrange(sun_count))))
            sunlist.write('\n')

        # Start creating header for the sun matrix.
        file_header = ['#?RADIANCE']
        file_header += ['Sun matrix created by Honeybee']
        file_header += ['LATLONG= %s %s' % (latitude, -longitude)]
        file_header += ['NROWS=%s' % sun_count]
        file_header += ['NCOLS=%s' % len(self.hoys)]
        file_header += ['NCOMP=3']
        file_header += ['FORMAT=ascii']

        print('Writing sun matrix to {}'.format(mfp))
        # Write the matrix to file.
        with open(mfp, 'w') as sunMtx:
            sunMtx.write('\n'.join(file_header) + '\n' + '\n')
            for idx, sunValue in enumerate(solarradiances):
                sun_rad_list = ['0 0 0'] * len(self.hoys)
                sun_rad_list[sun_up_hours[idx]] = '{0} {0} {0}'.format(
                    sunValue)
                sunMtx.write('\n'.join(sun_rad_list) + '\n\n')

            sunMtx.write('\n')

        return fp, lfp, mfp
Exemplo n.º 11
0
def test_date_time_from_hoy():
    """Test the from_hoy method for DateTime and basic properties."""
    dt1 = DateTime.from_hoy(4116)
    assert dt1 == DateTime(6, 21, 12)
    dt2 = DateTime.from_hoy(4116, leap_year=True)
    assert dt2 == DateTime(6, 20, 12, leap_year=True)