Propagatable

Utility functions

PortfolioOptimisers.@propagatable — Macro
@propagatable expr

Define a struct, and make its propagation methods from six field tags. The tags are independent, and a field can carry more than one:

  • @fprop (factory propagation): a call of factory calls factory on each tagged field. It passes runtime values, such as observation weights, prior results and solvers, down the tree of composed structs. The macro always makes a factory(x, args...) method. When no field carries @fprop or @wprop, that method returns x.
  • @wprop (weights replacement): an incoming ObsWeights argument replaces each tagged observation-weights field through _wprop. When no ObsWeights is threaded, the field keeps its value. Use @wprop for the weights field and @fprop for sub-estimators. A weights field with the default nothing must take the incoming weights, but @fprop keeps a nothing value.
  • @vprop (view propagation): a view of the struct at an index selection calls port_opt_view on each tagged field. The call recurses into composed children and views data arrays. The macro makes a port_opt_view method only when at least one field carries @vprop. With it, the macro makes an asset_axis_fields method that names the tagged fields, because a field that the asset index views is a field on the asset axis.
  • @pprop (prior selection): the prior method selects each tagged field against the field of the same name of a prior result, through sel(getfield(x, :f), getproperty(pr, :f)).
  • @cprop (context selection): the prior method selects each tagged field against a threaded optimiser value, a solver, that it finds by type, through sel(getfield(x, :f), _ctx(args...)).
  • @oprop (observation child): a cut of the observations through obs_weights_view recurses into each tagged field. No other method reads the tag.

When at least one field carries @pprop or @cprop, the macro makes a second method, factory(x, pr::AbstractPriorResult, args...). This method selects the @pprop and @cprop fields as above. It threads pr into the fields that carry only @fprop, as factory(getfield(x, :f), pr, args...). A field with both @pprop and @fprop takes the prior selection in this method, because @pprop wins. Then the method calls resolve_deferred_quantities on the selected struct. That call returns the struct with no change when the type has no deferred slot and no method of its own. So the Deferred-Quantity resolution runs last, and a slot that holds a Deferred Quantity sees the solver, the observation weights and the children in their last state. This method is more specific than the general factory(x, args...), so Julia selects it for every call that passes a prior.

A field with no tag keeps its value in every method, whatever its type. A tag is explicit, and the author adds it by choice. Do not put @pprop and @cprop on one field, because a value comes from one source. The valid stacks are @pprop @fprop, for a sub-estimator, and @pprop @wprop, for a weights field.

Two results of the emitted code are contracts on the declaration. The library checks both where the author writes the struct, not at the first call:

  • Every generated method builds the struct again as StructName(; field = …) over all fields, with or without a tag. So every field name must also be a keyword of the outer constructor. A kwargs... slurp does not satisfy this, because it accepts the keyword and then discards it.
  • The prior method reads getproperty(pr, :field), so every @pprop field name must be a property of a prior result. See prior_result_property_pool.

The macro registers each declaration in PROPAGATABLE_CONTRACTS. check_propagatable_contracts checks the whole registry when the module is complete. A field name with a typing error fails at precompilation with a suggestion from suggest_declared_key. It does not wait to raise a MethodError at the first call of factory. forward_prior uses the same contract.

The set of tags is data. PROP_TAG_NAMES holds the rows, prop_tag_expr holds the field transform of each tag, and PROP_TAG_CHANNELS holds the gate and the tag precedence of each channel. So a new tag is a row of those tables and a stub macro. A new channel is also a row of PROP_TAG_CHANNELS, but it needs its own emission step in this macro, because each channel has its own method head.

The macro works with @concrete. Put @propagatable on the outside:

@propagatable @concrete struct MyMeasure <: RiskMeasure    @pprop @wprop w       # prior factory selects pr.w; ObsWeights factory fills w    @pprop sigma          # prior-selected from pr.sigma    @fprop alg            # threaded (recursed) with pr / args    config                # passed through unchanged    function MyMeasure(w, sigma, alg, config)        return new{typeof(w), typeof(sigma), typeof(alg), typeof(config)}(w, sigma, alg,                                                                          config)    endend

@wprop gates two channels, and they do different operations on the same field. factory replaces the field with an incoming ObsWeights value. obs_weights_view indexes the value of the field at a set of observations. A weights field needs no second tag to join the view on the observation axis. The observation method also opens on a @fprop or an @oprop field, and it recurses into each of them, so a cut reaches a weights field at any depth of the tree.

The macro adds the generated factory, port_opt_view, asset_axis_fields and obs_weights_view methods to the functions of PortfolioOptimisers. So @propagatable also works for a type that an external package defines.

Base.@__doc__ forwards a docstring on the declaration to the struct.

Algorithm

  1. Find the struct with propagatable_find_struct, which gives struct_node and rebuild. rebuild puts a replacement struct back inside the same chain of wrapping macros.
  2. Read type_head and body from struct_node. Read struct_name from type_head with propagatable_bare_name, which drops the type parameters and the supertype.
  3. Parse the body with propagatable_parse_body. It gives tagged, the field names of each tag, all_fields, every declared field in declaration order, and new_body, the body with no tags.
  4. Build new_struct from new_body, and chain from rebuild(new_struct). chain is the original declaration without the tags, so @concrete and Julia both see an ordinary struct.
  5. Bind POMOD to the module that defines the macro, and qualify every emitted name with it. A bare name resolves in the module of the caller. There, function factory(…) declares a new function of the caller, and the method never gets to PortfolioOptimisers.factory. That failure gives no error, because the declaration compiles and the type never joins the propagation chain.
  6. Emit the factory method. When prop_channel_active holds for the factory channel, the body is a call to the keyword constructor, with the pairs from prop_channel_pairs. Otherwise, the body is x. The macro always emits this method, so a @propagatable struct with no tags returns itself from factory.
  7. When the view channel is active, emit port_opt_view(x::StructName, i, args...). Its channel threads i before args.... Also emit asset_axis_fields(::StructName), which returns the names of the @vprop fields as a tuple of symbols.
  8. When the obs channel is active, emit obs_weights_view(x::StructName, i). Its channel threads i and takes no tail. A @wprop, a @fprop or an @oprop field opens the channel.
  9. When the prior channel is active, emit factory(x::StructName, pr::AbstractPriorResult, args...; kwargs...). Its body selects every tagged field from x, and then gives the selected struct to resolve_deferred_quantities, which makes the Deferred-Quantity resolution the last operation. A Deferred Quantity and a Calibration Rule see the solver, the observation weights and the children in the state that the optimisation gave them, and a rule can call ERM or RRM. This method is more specific than the method of step 6, so Julia selects it for a call that threads a prior.
  10. Build pprop_tuple, the names of the @pprop fields as a tuple of quoted symbols.
  11. Return one escaped block. It holds Base.@__doc__ chain, so a docstring on the declaration gets to the struct. Then it holds the emitted methods, and last the call to propagatable_register! that records the type and pprop_tuple.

Steps 6 to 9 differ only in the method head and in the arguments that the channel threads. Each step reads its gate and its tag precedence from PROP_TAG_CHANNELS. A new tag is a row of the tables, a branch in prop_tag_expr and a stub macro, but a new channel also needs a new step here.

Related

source
PortfolioOptimisers.@fprop — Macro
@fprop field

Field tag for a @propagatable struct body. It marks a composed child for factory propagation. A call of factory on the struct calls factory on the field.

Algorithm

The tag never expands, because @propagatable runs first and removes it. The steps below tell what happens to the tagged field, not what this macro does.

  1. propagatable_parse_body peels the tag off the field, records the field name under :fprop, and puts the stripped field into the struct body. Neither Julia nor a wrapped macro such as @concrete ever sees the tag.

  2. prop_channel_active reads the recorded name. This tag gates the factory channel and the obs channel, and each active channel makes @propagatable emit one method.

  3. prop_channel_pairs builds the keyword pair of the field for each emitted method, and prop_tag_expr gives the value:

    • factory channel: factory(x.field, args...; kwargs...), which recurses into the child.
    • obs channel: obs_weights_view(x.field, i), which recurses into the child on the observation axis.
  4. The generated method builds the struct again with its keyword constructor, so every check of the constructor runs again on the propagated value.

Step 3 gives the meaning of the tag. The same tag has two transforms, because a channel decides what a tag means. The obs channel gates on @fprop, so a struct whose only tag is @fprop gets an obs_weights_view method. A cut of the observations then reaches a weights field at any depth of the tree, through every wrapper above it.

The body of this macro raises an error. Julia runs it only when the tag is outside a @propagatable struct body, where no macro removed it.

Related

source
PortfolioOptimisers.@vprop — Macro
@vprop field

Field tag for a @propagatable struct body. It marks the field for port_opt_view propagation. A view of the struct at an index selection calls port_opt_view on the field.

The tag is independent of @fprop. A field can carry both, as @fprop @vprop field, when it takes part in factory propagation and in view propagation.

Algorithm

The tag never expands, because @propagatable runs first and removes it. The steps below tell what happens to the tagged field, not what this macro does.

  1. propagatable_parse_body peels the tag off the field, records the field name under :vprop, and puts the stripped field into the struct body. Neither Julia nor a wrapped macro such as @concrete ever sees the tag.
  2. prop_channel_active reads the recorded name. This tag gates the view channel alone, and an active channel makes @propagatable emit one method.
  3. prop_channel_pairs builds the keyword pair of the field for each emitted method, and prop_tag_expr gives the value: view_child(x.field, i, args...). This is port_opt_view(x.field, i, args...) for every value except a precomputed optimisation result, which it keeps with no change. The channel forwards the threaded tail and no keywords.
  4. The generated method builds the struct again with its keyword constructor, so every check of the constructor runs again on the propagated value.

Step 3 gives the meaning of the tag. @vprop is in one channel, so it has one transform and one meaning. The index that the method threads selects assets. The observation axis has its own verb, obs_weights_view.

The body of this macro raises an error. Julia runs it only when the tag is outside a @propagatable struct body, where no macro removed it.

Related

source
PortfolioOptimisers.@pprop — Macro
@pprop field

Field tag for a @propagatable struct body. It marks the field as prior-selected. A call factory(x, pr::AbstractPriorResult, …) sets the field to sel(getfield(x, :field), getproperty(pr, :field)). This is the value of the risk measure when it is not nothing, else the moment of the same name from the prior result.

A field can carry this tag together with @wprop or @fprop. For example, @pprop @wprop w gives a weights field a prior method and an ObsWeights method. @pprop wins in the prior method. Do not put this tag and @cprop on one field, because a value comes from one source. No check refuses the pair, and @pprop wins because it is first in the precedence of the prior channel.

Algorithm

The tag never expands, because @propagatable runs first and removes it. The steps below tell what happens to the tagged field, not what this macro does.

  1. propagatable_parse_body peels the tag off the field, records the field name under :pprop, and puts the stripped field into the struct body. Neither Julia nor a wrapped macro such as @concrete ever sees the tag.
  2. prop_channel_active reads the recorded name. This tag gates the prior channel alone, and an active channel makes @propagatable emit one method.
  3. prop_channel_pairs builds the keyword pair of the field for each emitted method, and prop_tag_expr gives the value: sel(x.field, getproperty(pr, :field)). The prior result gives the property of the same name as the field, so the tag names no source of its own.
  4. The generated method builds the struct again with its keyword constructor, so every check of the constructor runs again on the propagated value.

Step 3 gives the meaning of the tag. @pprop is first in the precedence of the prior channel. So a field with @pprop and @fprop takes the prior transform on that channel and the factory transform on the factory channel.

The body of this macro raises an error. Julia runs it only when the tag is outside a @propagatable struct body, where no macro removed it.

Related

source
PortfolioOptimisers.@wprop — Macro
@wprop field

Field tag for a @propagatable struct body. It marks the field as an observation-weights slot. A call factory(x, w::ObsWeights, …) replaces the field with the incoming weights through _wprop. When no ObsWeights is threaded, the field keeps its value.

This tag is different from @fprop, which recurses into a sub-estimator and keeps a nothing value. A weights field has the default nothing, which means uniform weights, and it must take the incoming weights, which the nothing rule of @fprop does not do. Use @wprop for the weights field w, and @fprop for sub-estimators.

Algorithm

The tag never expands, because @propagatable runs first and removes it. The steps below tell what happens to the tagged field, not what this macro does.

  1. propagatable_parse_body peels the tag off the field, records the field name under :wprop, and puts the stripped field into the struct body. Neither Julia nor a wrapped macro such as @concrete ever sees the tag.

  2. prop_channel_active reads the recorded name. This tag gates the factory channel and the obs channel, and each active channel makes @propagatable emit one method.

  3. prop_channel_pairs builds the keyword pair of the field for each emitted method, and prop_tag_expr gives the value:

    • factory channel: _wprop(x.field, args...; kwargs...), which replaces the field with an incoming ObsWeights, and keeps it when none is threaded.
    • obs channel: obs_weights_index(x.field, i), which indexes the value of the field at the selected observations. An index keeps the AbstractWeights subtype, and a view does not.
  4. The generated method builds the struct again with its keyword constructor, so every check of the constructor runs again on the propagated value.

Step 3 gives the meaning of the tag. The two channels do different operations on the same field, so factory and obs_weights_view are not two names for one operation. One @wprop field gives the struct an obs_weights_view method, with no second tag.

A risk measure stacks @pprop @wprop on its weights field. The prior channel then selects the field against the weights of the prior result, and the obs channel indexes it.

The body of this macro raises an error. Julia runs it only when the tag is outside a @propagatable struct body, where no macro removed it.

Related

source
PortfolioOptimisers.@cprop — Macro
@cprop field

Field tag for a @propagatable struct body. It marks the field as context-selected. A call factory(x, pr::AbstractPriorResult, …) sets the field to sel(getfield(x, :field), _ctx(args...)). This is the value of the risk measure when it is not nothing, else the threaded optimiser value, a solver, that _ctx finds by type in the tail. The slv fields use this tag, because their source is a threaded argument and not the prior. Do not put this tag and @pprop on one field.

Algorithm

The tag never expands, because @propagatable runs first and removes it. The steps below tell what happens to the tagged field, not what this macro does.

  1. propagatable_parse_body peels the tag off the field, records the field name under :cprop, and puts the stripped field into the struct body. Neither Julia nor a wrapped macro such as @concrete ever sees the tag.
  2. prop_channel_active reads the recorded name. This tag gates the prior channel alone, and an active channel makes @propagatable emit one method.
  3. prop_channel_pairs builds the keyword pair of the field for each emitted method, and prop_tag_expr gives the value: sel(x.field, _ctx(args...)). _ctx finds the value by type in the threaded tail, so the source is an argument and not the prior result.
  4. The generated method builds the struct again with its keyword constructor, so every check of the constructor runs again on the propagated value.

Step 3 gives the meaning of the tag. @cprop comes after @pprop in the precedence of the prior channel. If a field carries both, @pprop wins and the field ignores the context.

The body of this macro raises an error. Julia runs it only when the tag is outside a @propagatable struct body, where no macro removed it.

Related

source
PortfolioOptimisers.@oprop — Macro
@oprop field

Field tag for a @propagatable struct body. It marks a composed child that only the observation channel reads. A cut of the observations, through obs_weights_view, recurses into the child. factory, port_opt_view and the prior selection do not read the tag.

Use @oprop for a child that reads the observations of the sample, when the factory channel must not reach it. The prior of an optimiser is an example. factory(opt, w) passes the portfolio weights w to the fees of the optimiser, and not to its prior, but a cut of the observations must reach the observation weights of the prior. A child that factory reaches carries @fprop, which the obs channel reads too, so it needs no second tag.

Algorithm

The tag never expands, because @propagatable runs first and removes it. The steps below tell what happens to the tagged field, not what this macro does.

  1. propagatable_parse_body peels the tag off the field, records the field name under :oprop, and puts the stripped field into the struct body. Neither Julia nor a wrapped macro such as @concrete ever sees the tag.
  2. prop_channel_active reads the recorded name. This tag gates the obs channel alone, and an active channel makes @propagatable emit one method.
  3. prop_channel_pairs builds the keyword pair of the field for the obs method, and prop_tag_expr gives the value obs_weights_view(x.field, i), which recurses into the child on the observation axis. Every other channel keeps the value of the field.
  4. The generated method builds the struct again with its keyword constructor, so every check of the constructor runs again on the propagated value.

The body of this macro raises an error. Julia runs it only when the tag is outside a @propagatable struct body, where no macro removed it.

Related

source
PortfolioOptimisers.asset_axis_fields — Function
asset_axis_fields(x) -> Tuple{Vararg{Symbol}}

Return the names of the fields of x whose values lie on the asset axis of the data that x reads.

A child on the asset axis reads the same columns as its parent, so a UniverseSets in that child must name the same assets. assert_universe_axis_order walks these fields to find each such universe. A child on another axis, such as the factor prior of a FactorPrior, which reads the factor returns, is not on this list.

Algorithm

The method that Julia selects is the algorithm.

  1. A @propagatable struct with at least one @vprop field: return the names of its @vprop fields, in the order of the declaration. The macro makes this method. A @vprop field is a field that port_opt_view views at the asset index, so the tag already states that the field lies on the asset axis.
  2. Any other value: return the names of the fields whose declared type can hold an estimator, an algorithm or a vector. A @concrete struct records the type of each value in a type parameter, so a field that holds a number, a matrix or a nothing gives no name. The answer comes from the type alone, so the compiler computes it once for each type.

A struct with no @vprop field, such as a struct with a hand-written view, takes step 2, which reads all of its children. If such a struct holds a child on another axis, it must define its own method of this function, which leaves that child out. Otherwise the check reads the universe of the child against the asset names, and refuses a correct universe.

Arguments

  • x: The estimator, algorithm or value to read.

Returns

  • fields::Tuple{Vararg{Symbol}}: The names of the fields on the asset axis.

Related

source

Summary statistics

Some estimators and constraints reduce a vector to one number, such as its minimum, mean, median or maximum. Each type below names one reduction, and some of them take observation weights. vec_to_real_measure applies the reduction to a vector.

PortfolioOptimisers.factory — Method
factory(a, args...; kwargs...) -> a
factory(a::AbstractArray{<:Union{Nothing, AbstractEstimator, AbstractAlgorithm,
                                 AbstractResult, StatsBase.CovarianceEstimator}},
        args...; kwargs...) -> AbstractArray

Rebuild an estimator, an algorithm or a result with runtime values. These two methods are the leaf and the array step of the traversal.

factory and port_opt_view are the two propagation mechanisms of this library. factory passes runtime values, such as prior moments, observation weights and previous portfolio weights, down a tree of composed structs. port_opt_view passes an index selection, a subset of the assets, down the same tree.

factory is a traversal, so it owns the identity on every leaf, as fmap in Functors.jl and adapt_structure in Adapt.jl do. A value that has no method of its own comes back with no change: a data field, a scalar, nothing, a set of observation weights and a covariance estimator of StatsBase. So a @propagatable struct sends each @fprop field to factory directly, whatever the field holds.

The array method is the one forwarding contract for every propagation field that holds an array of estimators, algorithms, results or covariance estimators. It applies factory to each element, and it forwards args... and kwargs... with no change. A family that accepts an array of them needs no method of its own. A family that needs more than the forward defines its own, more specific method. A concrete element type, through concrete_typed_array_if_abstract, is an example. An array of data, such as a vector of numbers, is a leaf, and it comes back with no change and with no copy.

Algorithm

The leaf method:

  1. Return a with no change, and drop args... and kwargs.... This method is the leaf of the recursion. Because of it, a call of the verb on a type with no tags returns the value and raises no error.

The array method:

  1. For each element ai of a, call factory on ai, and forward args... and kwargs... with no change.
  2. Collect the results into a new array of the shape of a, in the order of a, and return it.

A @propagatable struct always has a generated method that is more specific than the leaf method. If the struct has at least one @fprop or @wprop field, that method builds the struct again with its keyword constructor. It sends each @fprop field through factory and each @wprop field through _wprop. If the struct has no such field, that method returns x.

The leaf method does not fill a nothing field. A weights field that must take the incoming weights when it holds nothing carries @wprop, and it goes to _wprop.

Arguments

  • a: Any value, which the leaf method returns with no change. For the array method, an array of estimators, algorithms, results, covariance estimators or nothing, which it rebuilds one element at a time.
  • args...: Positional arguments. The leaf method ignores them, and the array method forwards them.
  • kwargs...: Keyword arguments. The leaf method ignores them, and the array method forwards them.

Returns

  • a: The input with no change, for the leaf method.
  • v::AbstractArray: The rebuilt elements, in an array of the shape of a, for the array method.

Examples

julia> factory(nothing, 1, 2; x = 3)julia> factory([1.0, 2.0], 1, 2; x = 3)2-element Vector{Float64}: 1.0 2.0julia> factory(MeanValue())MeanValue  w ┴ nothing

Related

source
PortfolioOptimisers.factory — Method
factory(a, args...; kwargs...) -> a
factory(a::AbstractArray{<:Union{Nothing, AbstractEstimator, AbstractAlgorithm,
                                 AbstractResult, StatsBase.CovarianceEstimator}},
        args...; kwargs...) -> AbstractArray

Rebuild an estimator, an algorithm or a result with runtime values. These two methods are the leaf and the array step of the traversal.

factory and port_opt_view are the two propagation mechanisms of this library. factory passes runtime values, such as prior moments, observation weights and previous portfolio weights, down a tree of composed structs. port_opt_view passes an index selection, a subset of the assets, down the same tree.

factory is a traversal, so it owns the identity on every leaf, as fmap in Functors.jl and adapt_structure in Adapt.jl do. A value that has no method of its own comes back with no change: a data field, a scalar, nothing, a set of observation weights and a covariance estimator of StatsBase. So a @propagatable struct sends each @fprop field to factory directly, whatever the field holds.

The array method is the one forwarding contract for every propagation field that holds an array of estimators, algorithms, results or covariance estimators. It applies factory to each element, and it forwards args... and kwargs... with no change. A family that accepts an array of them needs no method of its own. A family that needs more than the forward defines its own, more specific method. A concrete element type, through concrete_typed_array_if_abstract, is an example. An array of data, such as a vector of numbers, is a leaf, and it comes back with no change and with no copy.

Algorithm

The leaf method:

  1. Return a with no change, and drop args... and kwargs.... This method is the leaf of the recursion. Because of it, a call of the verb on a type with no tags returns the value and raises no error.

The array method:

  1. For each element ai of a, call factory on ai, and forward args... and kwargs... with no change.
  2. Collect the results into a new array of the shape of a, in the order of a, and return it.

A @propagatable struct always has a generated method that is more specific than the leaf method. If the struct has at least one @fprop or @wprop field, that method builds the struct again with its keyword constructor. It sends each @fprop field through factory and each @wprop field through _wprop. If the struct has no such field, that method returns x.

The leaf method does not fill a nothing field. A weights field that must take the incoming weights when it holds nothing carries @wprop, and it goes to _wprop.

Arguments

  • a: Any value, which the leaf method returns with no change. For the array method, an array of estimators, algorithms, results, covariance estimators or nothing, which it rebuilds one element at a time.
  • args...: Positional arguments. The leaf method ignores them, and the array method forwards them.
  • kwargs...: Keyword arguments. The leaf method ignores them, and the array method forwards them.

Returns

  • a: The input with no change, for the leaf method.
  • v::AbstractArray: The rebuilt elements, in an array of the shape of a, for the array method.

Examples

julia> factory(nothing, 1, 2; x = 3)julia> factory([1.0, 2.0], 1, 2; x = 3)2-element Vector{Float64}: 1.0 2.0julia> factory(MeanValue())MeanValue  w ┴ nothing

Related

source
PortfolioOptimisers.factory — Method
factory(a, args...; kwargs...) -> a
factory(a::AbstractArray{<:Union{Nothing, AbstractEstimator, AbstractAlgorithm,
                                 AbstractResult, StatsBase.CovarianceEstimator}},
        args...; kwargs...) -> AbstractArray

Rebuild an estimator, an algorithm or a result with runtime values. These two methods are the leaf and the array step of the traversal.

factory and port_opt_view are the two propagation mechanisms of this library. factory passes runtime values, such as prior moments, observation weights and previous portfolio weights, down a tree of composed structs. port_opt_view passes an index selection, a subset of the assets, down the same tree.

factory is a traversal, so it owns the identity on every leaf, as fmap in Functors.jl and adapt_structure in Adapt.jl do. A value that has no method of its own comes back with no change: a data field, a scalar, nothing, a set of observation weights and a covariance estimator of StatsBase. So a @propagatable struct sends each @fprop field to factory directly, whatever the field holds.

The array method is the one forwarding contract for every propagation field that holds an array of estimators, algorithms, results or covariance estimators. It applies factory to each element, and it forwards args... and kwargs... with no change. A family that accepts an array of them needs no method of its own. A family that needs more than the forward defines its own, more specific method. A concrete element type, through concrete_typed_array_if_abstract, is an example. An array of data, such as a vector of numbers, is a leaf, and it comes back with no change and with no copy.

Algorithm

The leaf method:

  1. Return a with no change, and drop args... and kwargs.... This method is the leaf of the recursion. Because of it, a call of the verb on a type with no tags returns the value and raises no error.

The array method:

  1. For each element ai of a, call factory on ai, and forward args... and kwargs... with no change.
  2. Collect the results into a new array of the shape of a, in the order of a, and return it.

A @propagatable struct always has a generated method that is more specific than the leaf method. If the struct has at least one @fprop or @wprop field, that method builds the struct again with its keyword constructor. It sends each @fprop field through factory and each @wprop field through _wprop. If the struct has no such field, that method returns x.

The leaf method does not fill a nothing field. A weights field that must take the incoming weights when it holds nothing carries @wprop, and it goes to _wprop.

Arguments

  • a: Any value, which the leaf method returns with no change. For the array method, an array of estimators, algorithms, results, covariance estimators or nothing, which it rebuilds one element at a time.
  • args...: Positional arguments. The leaf method ignores them, and the array method forwards them.
  • kwargs...: Keyword arguments. The leaf method ignores them, and the array method forwards them.

Returns

  • a: The input with no change, for the leaf method.
  • v::AbstractArray: The rebuilt elements, in an array of the shape of a, for the array method.

Examples

julia> factory(nothing, 1, 2; x = 3)julia> factory([1.0, 2.0], 1, 2; x = 3)2-element Vector{Float64}: 1.0 2.0julia> factory(MeanValue())MeanValue  w ┴ nothing

Related

source
PortfolioOptimisers.factory — Method
factory(a, args...; kwargs...) -> a
factory(a::AbstractArray{<:Union{Nothing, AbstractEstimator, AbstractAlgorithm,
                                 AbstractResult, StatsBase.CovarianceEstimator}},
        args...; kwargs...) -> AbstractArray

Rebuild an estimator, an algorithm or a result with runtime values. These two methods are the leaf and the array step of the traversal.

factory and port_opt_view are the two propagation mechanisms of this library. factory passes runtime values, such as prior moments, observation weights and previous portfolio weights, down a tree of composed structs. port_opt_view passes an index selection, a subset of the assets, down the same tree.

factory is a traversal, so it owns the identity on every leaf, as fmap in Functors.jl and adapt_structure in Adapt.jl do. A value that has no method of its own comes back with no change: a data field, a scalar, nothing, a set of observation weights and a covariance estimator of StatsBase. So a @propagatable struct sends each @fprop field to factory directly, whatever the field holds.

The array method is the one forwarding contract for every propagation field that holds an array of estimators, algorithms, results or covariance estimators. It applies factory to each element, and it forwards args... and kwargs... with no change. A family that accepts an array of them needs no method of its own. A family that needs more than the forward defines its own, more specific method. A concrete element type, through concrete_typed_array_if_abstract, is an example. An array of data, such as a vector of numbers, is a leaf, and it comes back with no change and with no copy.

Algorithm

The leaf method:

  1. Return a with no change, and drop args... and kwargs.... This method is the leaf of the recursion. Because of it, a call of the verb on a type with no tags returns the value and raises no error.

The array method:

  1. For each element ai of a, call factory on ai, and forward args... and kwargs... with no change.
  2. Collect the results into a new array of the shape of a, in the order of a, and return it.

A @propagatable struct always has a generated method that is more specific than the leaf method. If the struct has at least one @fprop or @wprop field, that method builds the struct again with its keyword constructor. It sends each @fprop field through factory and each @wprop field through _wprop. If the struct has no such field, that method returns x.

The leaf method does not fill a nothing field. A weights field that must take the incoming weights when it holds nothing carries @wprop, and it goes to _wprop.

Arguments

  • a: Any value, which the leaf method returns with no change. For the array method, an array of estimators, algorithms, results, covariance estimators or nothing, which it rebuilds one element at a time.
  • args...: Positional arguments. The leaf method ignores them, and the array method forwards them.
  • kwargs...: Keyword arguments. The leaf method ignores them, and the array method forwards them.

Returns

  • a: The input with no change, for the leaf method.
  • v::AbstractArray: The rebuilt elements, in an array of the shape of a, for the array method.

Examples

julia> factory(nothing, 1, 2; x = 3)julia> factory([1.0, 2.0], 1, 2; x = 3)2-element Vector{Float64}: 1.0 2.0julia> factory(MeanValue())MeanValue  w ┴ nothing

Related

source
PortfolioOptimisers.factory — Method
factory(a, args...; kwargs...) -> a
factory(a::AbstractArray{<:Union{Nothing, AbstractEstimator, AbstractAlgorithm,
                                 AbstractResult, StatsBase.CovarianceEstimator}},
        args...; kwargs...) -> AbstractArray

Rebuild an estimator, an algorithm or a result with runtime values. These two methods are the leaf and the array step of the traversal.

factory and port_opt_view are the two propagation mechanisms of this library. factory passes runtime values, such as prior moments, observation weights and previous portfolio weights, down a tree of composed structs. port_opt_view passes an index selection, a subset of the assets, down the same tree.

factory is a traversal, so it owns the identity on every leaf, as fmap in Functors.jl and adapt_structure in Adapt.jl do. A value that has no method of its own comes back with no change: a data field, a scalar, nothing, a set of observation weights and a covariance estimator of StatsBase. So a @propagatable struct sends each @fprop field to factory directly, whatever the field holds.

The array method is the one forwarding contract for every propagation field that holds an array of estimators, algorithms, results or covariance estimators. It applies factory to each element, and it forwards args... and kwargs... with no change. A family that accepts an array of them needs no method of its own. A family that needs more than the forward defines its own, more specific method. A concrete element type, through concrete_typed_array_if_abstract, is an example. An array of data, such as a vector of numbers, is a leaf, and it comes back with no change and with no copy.

Algorithm

The leaf method:

  1. Return a with no change, and drop args... and kwargs.... This method is the leaf of the recursion. Because of it, a call of the verb on a type with no tags returns the value and raises no error.

The array method:

  1. For each element ai of a, call factory on ai, and forward args... and kwargs... with no change.
  2. Collect the results into a new array of the shape of a, in the order of a, and return it.

A @propagatable struct always has a generated method that is more specific than the leaf method. If the struct has at least one @fprop or @wprop field, that method builds the struct again with its keyword constructor. It sends each @fprop field through factory and each @wprop field through _wprop. If the struct has no such field, that method returns x.

The leaf method does not fill a nothing field. A weights field that must take the incoming weights when it holds nothing carries @wprop, and it goes to _wprop.

Arguments

  • a: Any value, which the leaf method returns with no change. For the array method, an array of estimators, algorithms, results, covariance estimators or nothing, which it rebuilds one element at a time.
  • args...: Positional arguments. The leaf method ignores them, and the array method forwards them.
  • kwargs...: Keyword arguments. The leaf method ignores them, and the array method forwards them.

Returns

  • a: The input with no change, for the leaf method.
  • v::AbstractArray: The rebuilt elements, in an array of the shape of a, for the array method.

Examples

julia> factory(nothing, 1, 2; x = 3)julia> factory([1.0, 2.0], 1, 2; x = 3)2-element Vector{Float64}: 1.0 2.0julia> factory(MeanValue())MeanValue  w ┴ nothing

Related

source