Skip to content

API ​

TimeSamplers.TimeSamplers Module

TimeSamplers

A package for temporal sampling, aggregation, and resampling of N-dimensional arrays along their time dimension.

Overview

TimeSampler provides a flexible framework for performing temporal operations on arrays, including:

  • Aggregation to different time scales (hourly, daily, monthly, yearly)

  • Computation of anomalies and climatological means

  • Inter-annual variability (IAV) and multi-year seasonal cycle (MSC) calculations

  • Time-based indexing and subsetting

  • Year shuffling and random year selection

Main Types

  • TimeSample: Core struct containing indices and a sampling function for temporal aggregation

  • TimeSampleViewInstance: A view of an array with temporal sampling applied

  • TimeSampleMethod: Abstract type for different time sampling methods

Available Time Sampling Methods

The package supports various time sampling methods:

Basic Aggregation

  • TimeHour: Aggregate to hourly time steps

  • TimeDay: Aggregate to daily time steps

  • TimeMonth: Aggregate to monthly time steps

  • TimeYear: Aggregate to yearly time steps

  • TimeMean: Aggregate to mean over all time steps

Anomalies

  • TimeHourAnomaly: Hourly anomalies (hourly values minus overall mean)

  • TimeDayAnomaly: Daily anomalies (daily values minus overall mean)

  • TimeMonthAnomaly: Monthly anomalies (monthly values minus overall mean)

  • TimeYearAnomaly: Yearly anomalies (yearly values minus overall mean)

  • TimeDayMSCAnomaly: Daily MSC anomalies (daily values minus multi-year seasonal cycle)

  • TimeMonthMSCAnomaly: Monthly MSC anomalies (monthly values minus multi-year seasonal cycle)

Climatological Statistics

  • TimeDayMSC: Multi-year seasonal cycle for daily data

  • TimeMonthMSC: Multi-year seasonal cycle for monthly data

  • TimeDayIAV: Inter-annual variability for daily data

  • TimeMonthIAV: Inter-annual variability for monthly data

  • TimeHourDayMean: Mean of hourly data over days

Resampling to n-unit periods

  • TimePeriodSample: Aggregate to bins of any n-unit period such as Hour(6) or "8-day"

  • TimePeriodAnomaly: Bin values minus the overall mean

  • TimePeriodMSC: Mean seasonal cycle of n-unit bins, or the mean diurnal cycle with cycle = Day(1)

  • TimePeriodMSCAnomaly: Mean cycle minus the overall mean

  • TimePeriodIAV: Bin values minus the mean cycle value at their position

Periods can be given as strings such as "30-sec", "15-min", "6-hour", "8-day", "3-month" or "year". A kind and a cycle can follow, as in "8-day_msc", "month_iav" or "3-hour_msc_day". The calendar methods TimeHour, TimeDay, TimeMonth and TimeYear and their anomaly, MSC and IAV variants are built on these period methods.

Time Selection

  • TimeAllYears: Include all years

  • TimeFirstYear: Select first year only

  • TimeRandomYear: Select a random year

  • TimeShuffleYears: Shuffle years

Special Methods

  • TimeArray: Use array-based time sampling

  • TimeSizedArray: Use sized array for indices

  • TimeIndexed: Use time indices for selection

  • TimeDiff: Compute time differences (e.g., anomalies)

  • TimeNoDiff: No time differences required

Main Functions

  • create_TimeSampler: Create one or more TimeSample aggregators from a date vector and time step specification

  • do_time_sampling: Apply temporal sampling/aggregation to data using a vector of time samplers

  • time_sampling: Apply a single time sampler to an array

  • get_TimeSampler: Get a time sampler method instance from a string or symbol

  • time_resample: Resample data to an n-unit period in one call

  • time_resample_dates: Labels for the output of time_resample

  • parse_temporal_resolution: Parse "6-hour" into (6, "hour")

  • get_time_period: Convert "6-hour" into Hour(6)

Usage Example

julia
using TimeSamplers
using Dates

# Create a date vector
dates = collect(Date(2000, 1, 1):Day(1):Date(2000, 12, 31))

# Create a time sampler for daily aggregation
daily_sampler = create_TimeSampler(dates, TimeDay())

# Apply to data (assuming data is a 2D array with time as first dimension)
# sampled_data = do_time_sampling(data, daily_sampler, TimeNoDiff())

Resampling example

julia
hourly = collect(DateTime(2000, 1, 1):Hour(1):DateTime(2001, 12, 31, 23))
data = rand(length(hourly), 3)

six_hourly = time_resample(data, hourly, "6-hour")
daily_sum = time_resample(data, hourly, :day; sampler_func=sum)
seasonal_cycle = time_resample(data, hourly, "3-hour_msc")
diurnal_cycle = time_resample(data, hourly, "3-hour_msc_day")
iav = time_resample(data, hourly, "8-day_iav")
out_dates = time_resample_dates(hourly, "6-hour")

Notes

  • The package is designed to work efficiently with views, avoiding unnecessary data copying

  • Multiple samplers can be chained together for complex temporal operations

  • The default aggregation function is mean, but custom functions can be provided

  • Time dimension is configurable (defaults to dimension 1)

See Also

  • TimeSample for the core type

  • create_TimeSampler for creating samplers

  • do_time_sampling for applying samplers to data

TimeSamplers.create_TimeSampler Function
julia
create_TimeSampler(date_vector, t_step, sampler_func = mean, skip_sampling = false)

Create one or more temporal sampling/aggregation objects (TimeSample) for a given target time step.

Arguments

  • date_vector: A vector of Dates.TimeType values (e.g. Date or DateTime) that define the time axis to be aggregated.

  • t_step: The target sampling/aggregation specification. Common forms:

    • ::Union{String, Symbol}: A name that resolves to a time-sampler type in TimeSampler (e.g. "TimeDay" / :TimeDay).

    • ::TimeSampleMethod: A concrete method instance (e.g. TimeDay()), used via multiple dispatch.

    • ::Union{String, Symbol} period spec: "6-hour", "8-day_msc" or :day resolve to the period methods TimePeriodSample, TimePeriodAnomaly, TimePeriodMSC, TimePeriodMSCAnomaly and TimePeriodIAV. See get_TimeSampler.

    • ::Dates.Period: resamples to bins of that period, same as TimePeriodSample(period).

date_vector must be sorted in ascending order, because bins are formed from contiguous runs of dates.

  • sampler_func: Function to apply per group (defaults to mean).

  • skip_sampling: If true, return nothing for samplers that would be a no-op (defaults to false).

Returns

  • Vector{Union{Nothing, TimeSample}}: Time-sampling/aggregation objects, with nothing entries when skip_sampling=true.

Examples

julia
julia> using TimeSamplers, Dates

julia> dates = collect(Date(2000, 1, 1):Day(1):Date(2000, 1, 10))
10-element Vector{Date}:
 2000-01-01
 2000-01-02
 2000-01-03
 2000-01-04
 2000-01-05
 2000-01-06
 2000-01-07
 2000-01-08
 2000-01-09
 2000-01-10

julia> daily_sampler = create_TimeSampler(dates, TimeDay())
1-element Vector{TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}}:
 TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}(UnitRange{Int64}[1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:10], Statistics.mean, 10)

julia> monthly_sampler = create_TimeSampler(dates, "TimeMonth")
1-element Vector{TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}}:
 TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}(UnitRange{Int64}[1:10], Statistics.mean, 10)

julia> anomaly_sampler = create_TimeSampler(dates, TimeDayAnomaly())
2-element Vector{TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}}:
 TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}(UnitRange{Int64}[1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:10], Statistics.mean, 10)
 TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}(UnitRange{Int64}[1:10], Statistics.mean, 10)
Code
julia
function create_TimeSampler(date_vector, t_step::Union{String, Symbol}, sampler_func=mean, skip_sampling=false)
    return create_TimeSampler(date_vector, get_TimeSampler(t_step), sampler_func, skip_sampling)
end

function create_TimeSampler(date_vector, ::TimeMean, sampler_func=mean, skip_sampling=false)
    mean_agg = TimeSample(getAllTimeIndices(date_vector), sampler_func, length(date_vector))
    return [mean_agg,]
end

function create_TimeSampler(date_vector, ::TimeAllYears, sampler_func=mean, skip_sampling=false)
    all_agg = TimeSample(getAllTimeIndices(date_vector), sampler_func, length(date_vector))
    return [all_agg,]
end

function create_TimeSampler(date_vector, t_step::TimeCalendarMethod, sampler_func=mean, skip_sampling=false)
    return create_TimeSampler(date_vector, getTimePeriodMethod(t_step), sampler_func, skip_sampling)
end

function create_TimeSampler(date_vector, ::TimeFirstYear, sampler_func=mean, skip_sampling=false)
    years = year.(date_vector)
    first_year = minimum(years)
    year_inds = getIndexForSelectedYear(years, first_year)
    year_agg = TimeSample(year_inds, sampler_func, length(date_vector))
    return [year_agg,]
end

function create_TimeSampler(date_vector, ::TimeRandomYear, sampler_func=mean, skip_sampling=false)
    years = year.(date_vector)
    random_year = rand(unique(years))
    year_inds = getIndexForSelectedYear(years, random_year)
    year_agg = TimeSample(year_inds, sampler_func, length(date_vector))
    return [year_agg,]
end

function create_TimeSampler(date_vector, ::TimeShuffleYears, sampler_func=mean, skip_sampling=false)
    years = year.(date_vector)
    unique_years = unique(years)
    shuffled_unique_years = sample(unique_years, length(unique_years), replace=false)
    year_inds = getIndexForSelectedYear.(Ref(years), shuffled_unique_years)
    year_agg = TimeSample(year_inds, sampler_func, length(date_vector))
    return [year_agg,]
end

function create_TimeSampler(date_vector, period::Dates.Period, sampler_func=mean, skip_sampling=false)
    return create_TimeSampler(date_vector, TimePeriodSample(period), sampler_func, skip_sampling)
end

function create_TimeSampler(date_vector, t_step::TimePeriodMethod, sampler_func=mean, skip_sampling=false)
    return skipFirstSampler(getPeriodSamplers(date_vector, t_step, sampler_func), t_step, skip_sampling)
end
TimeSamplers.do_time_sampling Function
julia
do_time_sampling(dat, time_samplers, sampling/aggregation_type)
do_time_sampling(dat, time_samplers)

a temporal sampling/aggregation function to aggregate the data using a vector of aggregators

Arguments:

  • dat: a data array/vector to aggregate

  • time_samplers: a vector of time aggregator structs with indices and function to do sampling/aggregation

  • sampling/aggregation_type: a type defining the type of sampling/aggregation to be done as follows:

    • ::TimeNoDiff: a type defining that the aggregator does not require removing/reducing values from original time series

    • ::TimeDiff: a type defining that the aggregator requires removing/reducing values from original time series. First aggregator aggregates the main time series, second aggregator aggregates to the time series to be removed.

    • ::TimeIndexed: a type defining that the aggregator requires indexing the original time series. The time steps of the first aggregator are selected along the first dimension in their order, so shuffled years come out in the shuffled order.

If sampling/aggregation_type is omitted, it defaults to TimeNoDiff().

Examples

julia
julia> using TimeSamplers, Dates

julia> dates = collect(Date(2000, 1, 1):Day(1):Date(2000, 1, 5))
5-element Vector{Date}:
 2000-01-01
 2000-01-02
 2000-01-03
 2000-01-04
 2000-01-05

julia> data = [1.0, 2.0, 3.0, 4.0, 5.0]
5-element Vector{Float64}:
 1.0
 2.0
 3.0
 4.0
 5.0

julia> samplers = create_TimeSampler(dates, TimeDay())
1-element Vector{TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}}:
 TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}(UnitRange{Int64}[1:1, 2:2, 3:3, 4:4, 5:5], Statistics.mean, 5)

julia> do_time_sampling(data, samplers)
5-element Vector{Float64}:
 1.0
 2.0
 3.0
 4.0
 5.0

julia> anomaly_samplers = create_TimeSampler(dates, TimeDayAnomaly())
2-element Vector{TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}}:
 TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}(UnitRange{Int64}[1:1, 2:2, 3:3, 4:4, 5:5], Statistics.mean, 5)
 TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}(UnitRange{Int64}[1:5], Statistics.mean, 5)

julia> do_time_sampling(data, anomaly_samplers, TimeDiff())
5-element Vector{Float64}:
 -2.0
 -1.0
  0.0
  1.0
  2.0
Code
julia
function do_time_sampling(dat, time_samplers)
    return do_time_sampling(dat, time_samplers, TimeNoDiff())
end

function do_time_sampling(dat, time_samplers, ::TimeIndexed)
    time_sampler = first(time_samplers)
    checkTimeLength(dat, time_sampler.n_time, 1)
    # the indices are flat for one year and one group per year for shuffled years
    time_inds = reduce(vcat, time_sampler.indices)
    return dat[time_inds, ntuple(_ -> Colon(), ndims(dat) - 1)...]
end

function do_time_sampling(dat, time_samplers, ::TimeNoDiff)
    return time_sampling(dat, first(time_samplers))
end

function do_time_sampling(dat, time_samplers, ::TimeDiff)
    dat_samp = time_sampling(dat, first(time_samplers))
    dat_samp_to_remove = time_sampling(dat, last(time_samplers))
    return dat_samp .- dat_samp_to_remove
end
TimeSamplers.format_temporal_resolution Function
julia
format_temporal_resolution(period)

The canonical resolution string of a period: the bare unit for a count of one, otherwise "<n>-<unit>". The unit is the full lowercase name, so the result can be parsed with parse_temporal_resolution by other packages without aliases.

Arguments:

  • period: a Dates.Period, or a resolution string such as "3h" that is first converted with get_time_period

Examples

julia
julia> using TimeSamplers, Dates

julia> format_temporal_resolution(Hour(3))
"3-hour"

julia> format_temporal_resolution("d")
"day"
Code
julia
function format_temporal_resolution(period::Dates.Period)
    unit = lowercase(string(nameof(typeof(period))))
    n = Dates.value(period)
    return n == 1 ? unit : "$(n)-$(unit)"
end
TimeSamplers.get_TimeSampler Function
julia
get_TimeSampler(aggr)

Creates and returns a time aggregator instance based on the provided sampling/aggregation.

Arguments

  • aggr::Symbol: Symbol specifying the time sampling/aggregation method type name (e.g. :TimeDay)

  • aggr::String: String specifying the time sampling/aggregation method type name (e.g. "TimeDay")

  • origin: bin origin used when aggr is a period spec, see TimePeriodSample

  • cycle: cycle used when aggr is a period spec of kind msc, msc_anomaly or iav

A snake case name such as "first_year" or "day_MSC" resolves to the method type TimeFirstYear or TimeDayMSC, with the same rule as to_uppercase_first in OmniTools. This only applies when origin and cycle keep their defaults.

Any other name is read as a period spec with the grammar <n>-<unit>[_<kind>[_<cycle>]]. The separator may be _ or -, and the kind is one of anomaly, msc, msc_anomaly or iav. The count may also be joined to the unit, as in "3h". The spec mean gives TimeMean().

Returns

An instance of the corresponding TimeSamplerMethod subtype.

Examples

julia
julia> using TimeSamplers

julia> get_TimeSampler("TimeDay")
TimeDay()

julia> get_TimeSampler(:TimeMonth)
TimeMonth()

julia> get_TimeSampler("TimeYear")
TimeYear()

julia> get_TimeSampler("6-hour")
TimePeriodSample{Hour}(Hour(6), :calendar)

julia> get_TimeSampler("3-hour_msc_day")
TimePeriodMSC{Hour, Day}(Hour(3), Day(1))

Notes

  • A similar approach (getTypeInstanceForNamedOptions) is used in Setup for creating other named options.
Code
julia
function get_TimeSampler(aggr::Symbol; kwargs...)
    return get_TimeSampler(string(aggr); kwargs...)
end

function get_TimeSampler(aggr::String; origin=:calendar, cycle=Year(1))
    method = getTimeSamplerMethodByName(aggr)
    isnothing(method) || return method
    # snake case names only map to the calendar methods, which have no origin or
    # cycle, so other keywords are only honoured by a period spec
    if origin === :calendar && cycle == Year(1)
        method = getTimeSamplerMethodByName("Time" * join(uppercasefirst.(split(aggr, "_"))))
        isnothing(method) || return method
    end
    return getTimePeriodMethodFromSpec(aggr; origin=origin, cycle=cycle)
end
TimeSamplers.get_time_period Function
julia
get_time_period(spec)
get_time_period(n, unit)

Convert a temporal resolution into a Dates.Period.

Arguments:

  • spec: a resolution string or symbol such as "6-hour", "30-sec" or :day, or a Dates.Period which is returned unchanged

  • n: a positive integer count

  • unit: a unit name or alias from TIME_PERIOD_UNITS

Examples

julia
julia> using TimeSamplers

julia> get_time_period("6-hour")
6 hours

julia> get_time_period(8, "day")
8 days
Code
julia
function get_time_period(spec::Union{AbstractString,Symbol})
    n, unit = parse_temporal_resolution(spec)
    return get_time_period(n, unit)
end

function get_time_period(n::Integer, unit)
    n > 0 || error("invalid time period count $(n): must be a positive integer.")
    unit_type = get(TIME_PERIOD_UNITS, lowercase(String(unit)), nothing)
    if isnothing(unit_type)
        supported = join(sort(collect(keys(TIME_PERIOD_UNITS))), ", ")
        error("unsupported time unit \"$(unit)\". Supported units are: $(supported).")
    end
    return unit_type(n)
end
TimeSamplers.parse_temporal_resolution Function
julia
parse_temporal_resolution(resolution)

Parse a temporal resolution string into an integer count and a base unit string.

Accepts either a bare unit such as "day" or an n-unit string of the form "<positive integer>-<unit>" such as "6-hour". The count may also be written directly before the unit, as in "3hour" or "3h", or with a space, as in "3 hour". A bare unit is equivalent to "1-<unit>". The unit is returned as given and is not validated. Use get_time_period to turn a resolution into a Dates.Period.

Arguments:

  • resolution: a temporal resolution string or symbol

Returns:

  • (n::Int, unit::String): the count and the base unit string

Examples

julia
julia> using TimeSamplers

julia> parse_temporal_resolution("6-hour")
(6, "hour")

julia> parse_temporal_resolution("day")
(1, "day")

julia> parse_temporal_resolution("3h")
(3, "h")
Code
julia
function parse_temporal_resolution(resolution)
    parts = split(String(resolution), "-")
    if length(parts) == 1
        # a count written directly before the unit, such as 3hour, 3h or 3 hour
        joined = match(r"^\s*(\d+)\s*([A-Za-z]+)\s*$", parts[1])
        if !isnothing(joined)
            n = parse(Int, joined.captures[1])
            n > 0 || error("invalid temporal resolution \"$(resolution)\": count must be a positive integer, got $(n).")
            return n, String(joined.captures[2])
        end
        return 1, String(parts[1])
    elseif length(parts) == 2
        n = tryparse(Int, parts[1])
        if isnothing(n)
            error("invalid temporal resolution \"$(resolution)\": count \"$(parts[1])\" is not an integer. Expected format \"<integer>-<unit>\", e.g. \"6-hour\".")
        elseif n <= 0
            error("invalid temporal resolution \"$(resolution)\": count must be a positive integer, got $(n).")
        end
        return n, String(parts[2])
    else
        error("invalid temporal resolution \"$(resolution)\": expected a bare unit (e.g. \"day\") or \"<integer>-<unit>\" (e.g. \"6-hour\"), got $(length(parts)) dash-separated parts.")
    end
end
TimeSamplers.time_resample Function
julia
time_resample(dat, date_vector, period; sampler_func = mean, dim = 1, origin = :calendar, cycle = Year(1))
time_resample(dat, rs::TimeResampler; dim = 1)

Resample data along its time dimension. The first form builds the samplers and uses them once. The second form reuses the samplers of a TimeResampler, which is faster when many arrays on the same time axis are resampled.

Arguments:

  • dat: an array whose dimension dim matches date_vector

  • date_vector: a sorted vector of Date or DateTime values

  • period: the target, given as one of

    • a string or symbol such as "6-hour", :day, "8-day_msc", "3-hour_msc_day", "month_iav" or :mean

    • a Dates.Period such as Hour(6)

    • a time sampling method such as TimePeriodMSC(Day(8)) or TimeMonth()

  • sampler_func: the function applied to every group, defaults to mean

  • dim: the time dimension of dat

  • origin: bin origin for plain and anomaly bins, see TimePeriodSample

  • cycle: cycle for msc, msc_anomaly and iav when period does not name one

Anomaly, MSC anomaly and IAV targets subtract their second sampler automatically.

Examples

julia
julia> using TimeSamplers, Dates

julia> dates = collect(DateTime(2000, 1, 1):Hour(1):DateTime(2000, 1, 1, 11));

julia> time_resample(collect(1.0:12.0), dates, "6-hour")
2-element Vector{Float64}:
 3.5
 9.5

julia> time_resample(collect(1.0:12.0), dates, Hour(4); sampler_func=sum)
3-element Vector{Float64}:
 10.0
 26.0
 42.0
Code
julia
function time_resample(dat, date_vector, period; sampler_func=mean, dim=1, origin=:calendar, cycle=Year(1))
    checkTimeLength(dat, length(date_vector), dim)
    rs = TimeResampler(date_vector, period; sampler_func=sampler_func, origin=origin, cycle=cycle)
    return time_resample(dat, rs; dim=dim)
end

function time_resample(dat, rs::TimeResampler; dim=1)
    return doTimeResample(dat, rs.samplers, rs.combine, dim)
end
TimeSamplers.time_resample_dates Function
julia
time_resample_dates(date_vector, period; origin = :calendar, cycle = Year(1))
time_resample_dates(rs::TimeResampler)

Labels for the output of time_resample, one per slice along the time dimension.

For plain, anomaly and IAV targets every label is the start of a bin. For MSC and MSC anomaly targets the labels are the zero based cycle positions in ascending order. In a yearly cycle of day or sub-day bins the positions count on a 366 day calendar, so position 59 is Feb 29 for daily bins. For TimeMean the label is the first date. The arguments are the same as for time_resample.

Examples

julia
julia> using TimeSamplers, Dates

julia> dates = collect(DateTime(2000, 1, 1, 3):Hour(1):DateTime(2000, 1, 1, 13));

julia> time_resample_dates(dates, "6-hour")
3-element Vector{DateTime}:
 2000-01-01T00:00:00
 2000-01-01T06:00:00
 2000-01-01T12:00:00
Code
julia
function time_resample_dates(date_vector, period; origin=:calendar, cycle=Year(1))
    t_step = toTimePeriodMethod(period; origin=origin, cycle=cycle)
    return getTimeResampleLabels(date_vector, getTimePeriodMethod(t_step))
end
TimeSamplers.time_sampling Function
julia
time_sampling(dat::AbstractArray, time_sampler::TimeSample, dim = 1)

a temporal sampling/aggregation function to aggregate the data using a given aggregator when the input data is an array

Arguments:

  • dat: a data array/vector to aggregate with function for the following types:

    • ::AbstractArray: an array

    • ::SubArray: a view of an array

    • ::Nothing: a dummy type to return the input and do no sampling/aggregation data

  • time_sampler: a time aggregator struct with indices and function to do sampling/aggregation

  • dim: the dimension along which the sampling/aggregation should be done

Examples

julia
julia> using TimeSamplers, Dates

julia> dates = collect(Date(2000, 1, 1):Day(1):Date(2000, 1, 5))
5-element Vector{Date}:
 2000-01-01
 2000-01-02
 2000-01-03
 2000-01-04
 2000-01-05

julia> data = [1.0, 2.0, 3.0, 4.0, 5.0]
5-element Vector{Float64}:
 1.0
 2.0
 3.0
 4.0
 5.0

julia> sampler = create_TimeSampler(dates, TimeDay())[1]
TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}(UnitRange{Int64}[1:1, 2:2, 3:3, 4:4, 5:5], Statistics.mean, 5)

julia> time_sampling(data, sampler)
5-element Vector{Float64}:
 1.0
 2.0
 3.0
 4.0
 5.0

julia> monthly_sampler = create_TimeSampler(dates, TimeMonth())[1]
TimeSample{Vector{UnitRange{Int64}}, typeof(Statistics.mean)}(UnitRange{Int64}[1:5], Statistics.mean, 5)

julia> time_sampling(data, monthly_sampler)
1-element Vector{Float64}:
 3.0
Code
julia
function time_sampling(dat::AbstractArray, time_sampler::TimeSample, dim=1)
    dat = view(dat, time_sampler, dim=dim)
    return getTimeSampledArray(dat)
end

function time_sampling(dat::SubArray, time_sampler::TimeSample, dim=1)
    dat = view(dat, time_sampler, dim=dim)
    return getTimeSampledArray(dat)
end

function time_sampling(dat, time_sampler::Nothing, dim=1)
    return dat
end
TimeSamplers.time_sampling_period Function
julia
time_sampling_period(method)

The length of the bins of a method as a Dates.Period, or nothing for methods without bins such as TimeMean or TimeFirstYear. For a mean cycle this is the length of the bins inside the cycle, not the cycle.

method can also be a name or spec that get_TimeSampler accepts.

Examples

julia
julia> using TimeSamplers

julia> time_sampling_period("3-hour_msc_day")
3 hours

julia> time_sampling_period("day_MSC")
1 day

julia> time_sampling_period("all_years") === nothing
true
TimeSamplers.time_sampling_type Function
julia
time_sampling_type(method)

How the samplers of a method are combined, as the type to pass to do_time_sampling:

  • TimeNoDiff() applies the first sampler, as for bins and mean cycles

  • TimeDiff() subtracts the second sampler from the first, as for anomalies and IAV

  • TimeIndexed() selects the time steps of the first sampler, as for TimeFirstYear, TimeAllYears, TimeRandomYear and TimeShuffleYears

method can also be a name or spec that get_TimeSampler accepts.

Examples

julia
julia> using TimeSamplers

julia> time_sampling_type("8-day_iav")
TimeDiff()

julia> time_sampling_type("first_year")
TimeIndexed()

TimeSamplers.jl - Temporal sampling and aggregation for time series data