canopy_factory package

Subpackages

Submodules

canopy_factory.arguments module

class canopy_factory.arguments.ArgumentDescription(keys, properties, prefix='', suffix='', description='', universal=False, **kwargs)[source]

Bases: ArgumentDescriptionABC

Base class for describing a CLI argument.

Parameters:
  • keys (tuple) – Set of CLI keys.

  • properties (dict) – Keyword arguments to parser add_argument describing the argument and how it should be interpreted.

  • prefix (str, optional) – Prefix that should be added to the argument name.

  • suffix (str, optional) – Suffix that should be added to the argument name.

  • description (str, optional) – Description string that should be used to format the help message.

  • universal (bool, optional) – If True, the argument should only be added to a parser if it dosn’t already have an argument of that name.

  • **kwargs – Additional keyword arguments are passed to the parent class.

add_class(cls, overwrite=False)[source]

Add a class that uses the argument(s).

Parameters:
  • cls (type) – Class that uses the argument(s).

  • overwrite (bool, optional) – If True, overwrite any existing class for the specified key.

add_to_parser(parser, only_subparsers=False, **kwargs)[source]

Add this argument to a parser.

Parameters:
  • parser (InstrumentedParser) – Parser that the argument should be added to.

  • only_subparsers (bool, optional) – If True, only add add subparsers.

  • **kwargs – Additional keyword arguments are passed to member’s add_to_parser methods.

property class_converter_method

Name of the class method that should be used to finalize the argument.

Type:

str

property default

Argument default.

Type:

object

property dest

Name of variable where the argument will be stored.

Type:

str

finalize(x, args=None, **kwargs)[source]

Finalize an argument.

Parameters:
  • x (object) – Argument value to finalize.

  • args (argparse.Namespace, optional) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to the base method.

Returns:

The finalized instance.

Return type:

object

from_args(args, default=<class 'canopy_factory.utils.NoDefault'>)[source]

Construct the argument from an argument namespace.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • default (object, optional) – Alternate default to use.

Returns:

Argument value.

Return type:

object

classmethod get_class_converter_method(src, name)[source]

Locate a class converter method on the source class.

Parameters:
  • src (type) – Source class.

  • name (str) – Conversion name.

Returns:

Converter method.

Return type:

callable

property keys

Set of keys for the argument.

Type:

tuple

property name

Name of the argument.

Type:

str

property prefix_arg

Prefix to add to argument keys.

Type:

str

property subparser

Name of subparser used in destination.

Type:

str

property suffix_arg

Suffix to add to argument keys.

Type:

str

class canopy_factory.arguments.ArgumentDescriptionABC(name, ignored=False, no_cli=False, no_dest=False, suffix_param=<class 'canopy_factory.utils.NoDefault'>, **kwargs)[source]

Bases: ABC

Abstract base class providing argument mixin methods.

Parameters:
  • name (str) – Argument name.

  • ignored (bool, optional) – If True, the argument will be set to None during adjustment.

  • no_cli (bool, optional) – If True, the argument will not be added to parsers.

  • no_dest (bool, optional) – If True, the argument does not have a destination.

  • suffix_param (dict, optional) – Parameters used to turn the argument into a file suffix.

  • **kwargs – Additional keyword arguments are passed to the parent class.

add_class(cls, overwrite=False)[source]

Add a class that uses the argument(s).

Parameters:
  • cls (type) – Class that uses the argument(s).

  • overwrite (bool, optional) – If True, overwrite any existing class for the specified key.

add_to_parser(parser, only_subparsers=False, **kwargs)[source]

Add this argument to a parser.

Parameters:
  • parser (InstrumentedParser) – Parser that the argument should be added to.

  • only_subparsers (bool, optional) – If True, only add add subparsers.

  • **kwargs – Additional keyword arguments are passed to member’s add_to_parser methods.

adjust_args(args, skip=None, skip_root=False, skip_members=False, members=None, overwrite=False, **kwargs)[source]

Adjust the parsed arguments including setting defaults that depend on other provided arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • skip (list, optional) – Arguments to skip.

  • skip_root (bool, optional) – If True, don’t adjust the base argument.

  • skip_members (bool, optional) – If True, don’t adjust the member arguments.

  • members (list, optional) – Subset of members to adjust arguments for.

  • overwrite (bool, optional) – If True, overwrite the existing argument value.

  • **kwargs – Additional keyword arguments are passed to from_args.

adjust_kwargs(kws, **kwargs)[source]

Adjust an arguments dictionary including setting defaults that depend on other provided arguments.

Parameters:
  • kws (dict) – Arguments.

  • **kwargs – Additional keyword arguments are passed to adjust_args.

any_arguments_set(args)[source]

Check if any arguments are set.

Parameters:

args (argparse.Namespace) – Parsed arguments.

Returns:

True if arguments are set.

Return type:

bool

classmethod args2kwargs(args, include=None)[source]

Convert arguments from an argument namespace to keyword arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • include (list, optional) – Names of arguments to include.

Returns:

Keyword arguments.

Return type:

dict

argument_names(include='dest', no_root=False)[source]

Get all fo the associated argument names.

Parameters:
  • include (str, optional) –

    Specifies what to include in the returned list. Supported options include:

    'dest': Full argument name with prefix/suffix.
    'name': Argument name without prefix/suffix.
    'both': Tuple of result from 'dest' & 'name'.
    'flag': Use the first CLI flag.
    

  • no_root (bool, optional) – If True, don’t include this argument.

Returns:

Argument names.

Return type:

list

arguments_set(args)[source]

Check which arguments are set.

Parameters:

args (argparse.Namespace) – Parsed arguments.

Returns:

Set of arguments that are set.

Return type:

list

property cls

Immediate class that uses this argument.

Type:

type

copy(**kwargs)[source]

Create a copy of this argument set with modifications.

Parameters:

**kwargs – Keyword arguments are passed to the modify method for the returned copy.

Returns:

New copy of the argument set with

modifications.

Return type:

ArgumentDescriptionSet

property dest

Name of variable where the argument will be stored.

Type:

str

extract_args(args, out=None)[source]

Extract arguments that are set into a dictionary.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • out (dict, optional) – Existing dictionary that arguments should be added to.

Returns:

Updated argument dictionary.

Return type:

dict

finalize(x, args=None)[source]

Finalize an argument.

Parameters:
  • x (object) – Argument value to finalize.

  • args (argparse.Namespace, optional) – Parsed arguments.

Returns:

The finalized instance.

Return type:

object

findnested(x, default=<class 'canopy_factory.utils.NoDefault'>, check_root=False)[source]

Find a member argument that matches the one provided.

Parameters:

x (ArgumentDescription) – Argument to find.

Returns:

Matching member argument.

Return type:

ArgumentDescription

flatten(no_root=False)[source]

Iterate over all basic arguments (non-containers).

Parameters:

no_root (bool, optional) – If True, don’t include this argument.

Yields:

ArgumentDescription – Arguments that are not a container.

abstractmethod from_args(args)[source]

Construct the argument from an argument namespace.

Parameters:

args (argparse.Namespace) – Parsed arguments.

Returns:

Argument value.

Return type:

object

from_args_for_suffix(args, output, wildcards=None, skipped=None)[source]

Get the argument in a form for generating the suffix.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • output (str) – Name of output to generate suffix for.

  • wildcards (list, optional) – List of arguments that wildcards should be used for in the generated output file name.

  • skipped (list, optional) – List of arguments that should be skipped in the generated output file name.

Returns:

Argument value.

Return type:

object

from_kwargs(kws, **kwargs)[source]

Construct the argument from a dictionary of keyword arguments.

Parameters:
  • kws (dict) – Keyword arguments.

  • **kwargs – Additional keyword arguments are passed to from_args.

Returns:

Argument value.

Return type:

object

generate_suffix(*args, **kwargs)[source]

Generate the suffix string for this argument by inspecting args.

Parameters:
  • *args – Additional arguments are passed to the suffix generator’s generate method.

  • **kwargs – Additional keyword arguments are passed to the suffix generator’s generate method.

Returns:

Generated suffix.

Return type:

str

property generates_suffix

True if the argument generates a suffix.

Type:

bool

getnested(k, default=<class 'canopy_factory.utils.NoDefault'>, check_root=False)[source]

Retrieve an argument that may be nested inside another argument set.

Parameters:
  • k (str) – Key name to find an argument for.

  • default (object, optional) – Value to return if an argument cannot be located.

  • check_root (bool, optional) – If True, check the root.

Returns:

Argument description instance.

Return type:

ArgumentDescription

hasnested(k, check_root=False)[source]

Check if an argument is nested inside a member argument set.

Parameters:
  • k (str) – Key name to find an argument for.

  • check_root (bool, optional) – If True, check the root.

Returns:

True if the argument is a nested member, False

otherwise.

Return type:

bool

property is_output

True if the argument describes an output.

Type:

bool

classmethod kwargs2args(kwargs, include=None)[source]

Convert from a set of keyword arguments to an argument namespace.

Parameters:
  • kwargs (dict) – Keyword arguments.

  • include (list, optional) – Names of arguments to include.

Returns:

Argument namespace.

Return type:

argparse.Namespace

matches(solf)[source]

Check if this argument matches another in terms of the destination(s).

Parameters:

solf (ArgumentDescription) – Argument to compare this one to.

Returns:

True if solf matches this argument, False otherwise.

Return type:

bool

property members

Set of subarguments.

Type:

iterable

modify(modifications=None, include=None, exclude=None, ignore=None, **kwargs)[source]

Modify this argument.

Parameters:
  • modifications (dict, optional) – Mapping between argument names and the modifications that should be made to the arguments.

  • include (list, optional) – Subset of arguments to retain. Other arguments will be removed.

  • exclude (list, optional) – Subset of arguments to remove.

  • ignore (list, optional) – Subset of arguments to ignore.

  • **kwargs – Additional keyword arguments are used to update member argument properties.

property name

Name of the argument.

Type:

str

parse(x, args=None, **kwargs)[source]

Parse an argument.

Parameters:
  • x (object) – Argument value to parse.

  • args (argparse.Namespace, optional) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to the from_args method.

Returns:

The parsed instance.

Return type:

object

remove_class(cls)[source]

Remove a class that uses the argument(s).

Parameters:

cls (type, str) – Class that uses the argument(s) or the registry key for the class type that should be removed.

reset_args(args, value=<class 'canopy_factory.utils.NoDefault'>)[source]

Reset the arguments for a variable.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • value (object, optional) – Value that the parsed variable should be reset to.

property suffix_generator

Suffix generator.

Type:

SuffixGenerator

property top_cls

Top level class that uses this argument.

Type:

type

class canopy_factory.arguments.ArgumentDescriptionSet(arguments=None, name=None, no_dest=True, dont_create=False, arg_kwargs=<class 'canopy_factory.utils.NoDefault'>, suffix_param=<class 'canopy_factory.utils.NoDefault'>, **kwargs)[source]

Bases: ArgumentDescriptionABC, SimpleWrapper

A set of CLI arguments.

Parameters:
  • arguments (list, optional) – Argument descriptions.

  • name (str, optional) – Name to give the argument set.

  • no_dest (bool, optional) – If True, the argument does not have a destination. Defaults to True for sets.

  • dont_create (bool, optional) – If True, don’t create an instance of the argument class containing this argument set during calls to from_args.

  • arg_kwargs (dict, optional) – Arguments to provided to each argument.

  • suffix_param (dict, optional) – Parameters used to turn the argument set into a file suffix.

  • prefix (str, optional) – Prefix that should be added to the names of all arguments in the set.

  • suffix (str, optional) – Suffix that should be added to the names of all arguments in the set.

  • description (str, optional) – Description string that should be used to format the help messages for arguments in the set.

  • ignore (list, optional) – Subset of arguments to ignore.

  • **kwargs – Additional keyword arguments will be passed to the parent class constructor in from_args.

add_class(cls, overwrite=False)[source]

Add a class that uses the argument(s).

Parameters:
  • cls (type) – Class that uses the argument(s).

  • overwrite (bool, optional) – If True, overwrite any existing class for the specified key.

append(x, dont_copy=False, **kwargs)[source]

Add an argument to the argument set.

Parameters:
  • x (ArgumentDescription, tuple, list) – Argument to add.

  • dont_copy (bool, optional) – If True, don’t copy the argument when it is added.

  • **kwargs – Additional keyword arguments will be used to modify a copy of x prior to adding it.

dest2key(dest)[source]

Convert an argument destination name to the key used in this set.

Parameters:

dest (str) – Argument destination name.

Returns:

Argument key.

Return type:

str

property dests

Mapping between destination variable name and argument.

Type:

dict

from_args(args, cls=None, **kwargs)[source]

Construct the argument from an argument namespace.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • cls (type, optional) – Class that should be constructed from the arguments. Defaults to the ‘cls’ attribute.

  • **kwargs – Additional keyword arguments are passed to cls if one is provided.

Returns:

Argument value or argument namespace

(if the argument set does not have a cls set).

Return type:

object

from_args_for_suffix(args, output, **kwargs)[source]

Get the argument in a form for generating the suffix.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • output (str) – Name of output to generate suffix for.

  • **kwargs – Additional keyword arguments are passed to the suffix generators for members.

Returns:

Argument value.

Return type:

object

getdest(k, default=<class 'canopy_factory.utils.NoDefault'>)[source]

Retrieve an argument based on the destination variable.

Parameters:
  • k (str) – Destination name to find an argument for.

  • default (object, optional) – Value to return if an argument cannot be located.

Returns:

Argument description instance.

Return type:

ArgumentDescription

getkey(k, default=<class 'canopy_factory.utils.NoDefault'>)[source]

Retrieve an argument based on a key value.

Parameters:
  • k (str) – Key name to find an argument for.

  • default (object, optional) – Value to return if an argument cannot be located.

Returns:

Argument description instance.

Return type:

ArgumentDescription

index(key)[source]

Find the index of an argument in this set.

Parameters:

key (str) – Argument key.

Returns:

Index of key.

Return type:

int

insert(pos, x, dont_copy=False, **kwargs)[source]

Insert one or more arguments into the argument set.

Parameters:
  • pos (int) – Position at which the new argument(s) should be inserted.

  • x (ArgumentDescription, tuple, list) – Argument to add.

  • dont_copy (bool, optional) – If True, don’t copy the argument when it is appended.

  • **kwargs – Additional keyword arguments will be used to modify a copy of x prior to adding it.

key2dest(key)[source]

Convert a the key for an argument in this set to the destination name.

Parameters:

key (str) – Argument key.

Returns:

Argument destination name.

Return type:

str

property members

Set of subarguments.

Type:

iterable

modify(modifications=None, include=None, exclude=None, **kwargs)[source]

Modify this argument.

Parameters:
  • modifications (dict, optional) – Mapping between argument names and the modifications that should be made to the arguments.

  • include (list, optional) – Subset of arguments to retain. Other arguments will be removed.

  • exclude (list, optional) – Subset of arguments to remove.

  • (bool (strip_classes) – If True, remove the class associated with this set. If ‘all’, remove the classes associated with this set and all of it’s members.

  • optional – If True, remove the class associated with this set. If ‘all’, remove the classes associated with this set and all of it’s members.

  • **kwargs – Additional keyword arguments are used to update individual argument properties.

move(key, pos)[source]

Move an argument to the designated position.

Parameters:
  • key (str) – Argument key.

  • pos (int) – Position that the argument should be moved to.

prepend(x, dont_copy=False, **kwargs)[source]

Add an argument to the argument set at the beginning.

Parameters:
  • x (ArgumentDescription, tuple, list) – Argument to add.

  • dont_copy (bool, optional) – If True, don’t copy the argument when it is added.

  • **kwargs – Additional keyword arguments will be used to modify a copy of x prior to adding it.

remove_class(cls)[source]

Remove a class that uses the argument(s).

Parameters:

cls (type, str) – Class that uses the argument(s) or the registry key for the class type that should be removed.

reset_keys()[source]

Reinitialize the member arguments to allow the regeneration of argument keys (destination names).

sort_by_suffix()[source]

Sort the arguments by suffix.

property unsplitable

True if the set cannot be split.

Type:

bool

class canopy_factory.arguments.ClassSubparserArgumentDescription(name, properties=None, subparser_properties=None, subparser_arguments=None, modifications=None, include=None, exclude=None, dont_create=False, **kwargs)[source]

Bases: SubparserArgumentDescription

Class for adding arguments associated with a set of registered classes as subparsers.

Parameters:
  • name (str) – Name of the registered class set to create subparsers for.

  • properties (dict, optional) – Keyword arguments for creating the subparser group.

  • subparser_properties (dict, optional) – Mapping between subparser names and properties specific to the creation of that subparser.

  • subparser_arguments (dict, optional) – Mapping between subparser names and sets of arguments for that subparser.

  • modifications (dict, optional) – Mapping between argument names and the modifications that should be made to the arguments.

  • include (list, optional) – Subset of arguments to retain. Other arguments will be removed.

  • exclude (list, optional) – Subset of arguments to remove.

  • dont_create (bool, optional) – If True, the argument will not be created when it is parsed via from_args.

  • **kwargs – Additional keyword arguments are passed to the parent class.

class canopy_factory.arguments.CompositeArgumentDescription(name, composite_type=None, prefix='', suffix='', arguments=None, **kwargs)[source]

Bases: ArgumentDescriptionSet

Composite argument.

Parameters:
  • name (str) – Name of the composite argument.

  • composite_type (str, optional) – Name of the registered composite class that should be created for this argument. Defaults to name if not provided.

  • **kwargs – Additional keyword arguments will be passed to the ArgumentDescriptionSet constructor.

argument_names(include='dest')[source]

Get all fo the associated argument names.

Parameters:

include (str, optional) –

Specifies what to include in the returned list. Supported options include:

'dest': Full argument name with prefix/suffix.
'name': Argument name without prefix/suffix.
'both': Tuple of result from 'dest' & 'name'.
'flag': Use the first CLI flag.

Returns:

Argument names.

Return type:

list

from_args_for_suffix(args, output, wildcards=None, skipped=None)[source]

Get the argument in a form for generating the suffix.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • output (str) – Name of output to generate suffix for.

  • wildcards (list, optional) – List of arguments that wildcards should be used for in the generated output file name.

  • skipped (list, optional) – List of arguments that should be skipped in the generated output file name.

Returns:

Argument value.

Return type:

object

property is_output

True if the argument describes an output.

Type:

bool

class canopy_factory.arguments.DimensionArgumentDescription(*args, **kwargs)[source]

Bases: ArgumentDescriptionSet

A set of arguments that specifies dimensions.

exception canopy_factory.arguments.MissingSourceError(name, value=True)[source]

Bases: BaseException

Error to raise when source does not exist.

class canopy_factory.arguments.RegisteredArgumentClassAttributes(**kwargs)[source]

Bases: RegisteredArgumentClassKwargsBase

Base class with arguments assigned as attributes on the class.

Parameters:

**kwargs – Keyword arguments are treated as arguments.

class canopy_factory.arguments.RegisteredArgumentClassBase(args=None, args_overwrite=None)[source]

Bases: RegisteredClassBase

Base class for a class with CLI arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • args_overwrite (dict, optional) – Arguments to overwrite.

Class Attributes:

_arguments (ArgumentDescriptionSet) – Descriptions of arguments used by this class.

classmethod adjust_args(args, **kwargs)[source]

Adjust the parsed arguments including setting defaults that depend on other provided arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to the argument description’s adjust_args method.

classmethod argument_names(**kwargs)[source]

Get the argument names used by this class.

Parameters:

**kwargs – Additional keyword arguments are passed to _arguments.argument_names.

Returns:

Argument names.

Return type:

list

classmethod from_args(args, overwrite=False, **kwargs)[source]

Construct the class from a argument namespace.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • overwrite (bool, optional) – If True, overwrite the existing instance.

  • **kwargs – Additional keyword arguments are passed to the class constructor.

Returns:

Instance of class.

Return type:

cls

classmethod from_kwargs(kws, **kwargs)[source]

Construct the class from a dictionary of keyword arguments.

Parameters:
  • kws (dict) – Keyword arguments.

  • **kwargs – Additional keyword arguments are passed to the class constructor.

Returns:

Instance of class.

Return type:

cls

getarg(name, default=<class 'canopy_factory.utils.NoDefault'>)[source]

Get an argument value.

Parameters:
  • name (str) – Argument name.

  • default (object, optional) – Value to return if argument does not exist.

Returns:

Argument value.

Return type:

object

Raises:

KeyError – If the argument does not exist and default is not provided.

classmethod ignored(name)[source]

Check if an argument is ignored.

Parameters:

name (str) – Argument name.

Returns:

True if the argument is ignored, False otherwise.

Return type:

bool

classmethod parse(x, args, name=None, **kwargs)[source]

Parse an argument.

Parameters:
  • x (object) – Instance to parse.

  • args (argparse.Namespace) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to the from_args method.

Returns:

The parsed instance.

Return type:

object

reset(args, args_overwrite=None)[source]

Reinitialize the arguments used by this instance.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • args_overwrite (dict, optional) – Arguments to overwrite.

setarg(name, value)[source]

Set an argument value.

Parameters:
  • name (str) – Argument name.

  • value (object) – Argument value.

property string

String representation of this variable.

Type:

str

property value

Parsed base argument value.

Type:

object

class canopy_factory.arguments.RegisteredArgumentClassDict(args=None, args_overwrite=None)[source]

Bases: RegisteredArgumentClassBase

Base class with arguments stored in a dict called args.

Parameters:

args (argparse.Namespace) – Parsed arguments.

args

Set of parsed arguments.

Type:

dict

class canopy_factory.arguments.RegisteredArgumentClassKwargsBase(**kwargs)[source]

Bases: RegisteredArgumentClassBase

Base class that is initialized by a set of keyword arguments.

Parameters:

**kwargs – Keyword arguments are treated as arguments.

classmethod from_args(args, **kwargs)[source]

Construct the class from a argument namespace.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to the class constructor.

Returns:

Instance of class.

Return type:

cls

class canopy_factory.arguments.SubparserArgumentDescription(name, properties, subparser_properties=None, subparser_arguments=None, using_flag=False, **kwargs)[source]

Bases: ArgumentDescription

Subparser argument set.

Parameters:
  • name (str) – Name of the subparser.

  • properties (dict) – Keyword arguments for creating the subparser group.

  • subparser_properties (dict, optional) – Mapping between subparser names and properties specific to the creation of that subparser.

  • subparser_arguments (dict, optional) – Mapping between subparser names and sets of arguments for that subparser.

  • using_flag (bool, optional) – If True, a standard option argument should be used as a switch for the different subparsers.

  • **kwargs – Additional keyword arguments are passed to the parent class.

add_to_parser(parser, only_subparsers=False, **kwargs)[source]

Add this argument to a parser.

Parameters:
  • parser (InstrumentedParser) – Parser that the argument should be added to.

  • only_subparsers (bool, optional) – If True, only add add subparsers.

  • **kwargs – Additional keyword arguments are passed to member’s add_to_parser methods.

adjust_args(args, **kwargs)[source]

Adjust the parsed arguments including setting defaults that depend on other provided arguments.

Parameters:

**kwargs – Additional keyword arguments are passed to the parent class’s method.

append(x, dont_copy=False, **kwargs)[source]

Append one or more arguments to each subparser argument set.

Parameters:
  • x (ArgumentDescription, tuple, list) – Argument to add.

  • dont_copy (bool, optional) – If True, don’t copy the argument when it is added.

  • **kwargs – Additional keyword arguments will be used to modify a copy of x prior to adding it.

from_args(args, **kwargs)[source]

Construct the argument from an argument namespace.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to subparser from_args method.

Returns:

Argument value.

Return type:

object

from_args_for_suffix(args, output, **kwargs)[source]

Get the argument in a form for generating the suffix.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • output (str) – Name of output to generate suffix for.

  • **kwargs – Additional keyword arguments are passed to the base class and calls to suffix generate for the selected subparser.

Returns:

Argument value.

Return type:

object

property members

Set of subarguments.

Type:

iterable

prepend(x, dont_copy=False, **kwargs)[source]

Prepend one or more arguments to each subparser argument set.

Parameters:
  • x (ArgumentDescription, tuple, list) – Argument to add.

  • dont_copy (bool, optional) – If True, don’t copy the argument when it is added.

  • **kwargs – Additional keyword arguments will be used to modify a copy of x prior to adding it.

class canopy_factory.arguments.SuffixGenerator(arg=<class 'canopy_factory.utils.NoDefault'>, value=<class 'canopy_factory.utils.NoDefault'>, prefix=<class 'canopy_factory.utils.NoDefault'>, suffix=<class 'canopy_factory.utils.NoDefault'>, cond=<class 'canopy_factory.utils.NoDefault'>, noteq=<class 'canopy_factory.utils.NoDefault'>, default=<class 'canopy_factory.utils.NoDefault'>, title=<class 'canopy_factory.utils.NoDefault'>, conv=<class 'canopy_factory.utils.NoDefault'>, sep='_', outputs=<class 'canopy_factory.utils.NoDefault'>, skip_outputs=<class 'canopy_factory.utils.NoDefault'>, require_all=False, disabled=False, index=0)[source]

Bases: object

Class for generating a suffix from an argument.

Parameters:
  • arg (ArgumentDescription, optional) – Argument description.

  • value (object, optional) – Value to use in the suffix when the argument is set.

  • prefix (str, optional) – Prefix to use with value.

  • suffix (str, optional) – Suffix to use with value.

  • cond (bool, optional) – Condition under which the argument is considered set. If not provided, the boolean value of the argument will be used.

  • noteq (object, optional) – Set the cond to when the value is not equal to this.

  • default (object, optional) – Value to use when cond is False.

  • title (bool, optional) – If True, use title case for the value.

  • conv (callable, optional) – Function that should be used to convert the argument value to a string.

  • sep (str, optional) – Separator to use between list/array arguments.

  • outputs (list, optional) – Outputs that this suffix is valid for.

  • skip_outputs (list, optional) – Outputs that this suffix is not valid for.

  • require_all (bool, optional) – If True, require that all arguments in a set have values.

  • disabled (bool, optional) – If True, the suffix is disabled.

  • index (int, optional) – Index that should be used for ordering suffixes.

depends(output)[source]

Determine what arguments this suffix depends on for the provided output.

Parameters:

output (str) – Name of output to check.

Returns:

Names of arguments that the suffix depends on.

Return type:

list

eval_condition(value)[source]

Evaluate the condition that determines if the suffix should be generated or default (if provided) should be used.

Parameters:

value (object) – Argument value.

Returns:

Value of the evaluated condition. If True, the suffix

should be generated from the argument value. If False and a default is provided, the default should be used. If False and a default is not provided, an empty suffix should be returned.

Return type:

bool

generate(args, output, wildcards=None, skipped=None, value=<class 'canopy_factory.utils.NoDefault'>, **kwargs)[source]

Generate the suffix.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • output (str) – Name of output to generate suffix for.

  • wildcards (list, optional) – List of arguments that wildcards should be used for in the generated output file name.

  • skipped (list, optional) – List of arguments that should be skipped in the generated output file name.

  • value (object, optional) – Value that should be used instead of the args attribute.

  • **kwargs – Additional keyword arguments are passed to the suffix generator’s generate method.

Returns:

Generated suffix.

Return type:

str

is_valid(output)[source]

Check if the suffix is valid for the provided output(s).

Parameters:

output (str, list) – Name of output(s) to check.

Returns:

True if the suffix is valid, False otherwise.

Return type:

bool

value2suffix(value, args, wildcards=None, force=False)[source]

Generate the suffix string for this argument by inspecting args.

Parameters:
  • value (object) – Argument value.

  • args (argparse.Namespace) – Parsed arguments.

  • wildcards (list, optional) – List of arguments that wildcards should be used for in the generated output file name.

  • force (bool, optional) – If True, force the condition to be True.

Returns:

Generated suffix.

Return type:

str

canopy_factory.cli module

class canopy_factory.cli.ActionSet(parent, members)[source]

Bases: SetBase

Simple wrapper for a set of actions.

class canopy_factory.cli.AgeArgument(args, **kwargs)[source]

Bases: CompositeArgument

Container for parsing age arguments.

property age

Days since planting.

Type:

units.Quantity

property crop_age_string

Crop-based age string.

Type:

str

get_crop_age(x, return_quantity=False)[source]

Get a named crop age as a timedelta.

Parameters:

x (str) – Named crop age.

Returns:

Age as a time delta.

Return type:

timedelta

classmethod is_crop_age(x)[source]

Check if a string is a named crop age.

Parameters:

x (str) – Value to check.

Returns:

True if x is a named crop age.

Return type:

bool

name = 'age'
property parameter_inst

Instance for calculating ages.

Type:

ParametrizeCropTask

property requires_parameter_inst

True if a parameter instance is required.

Type:

bool

reset(args, **kwargs)[source]

Reinitialize the arguments used by this instance.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to the base method.

property string

String representation of the age.

Type:

str

class canopy_factory.cli.AxisArgument(args, name_base=None, defaults=None, optional=False, args_overwrite=None)[source]

Bases: CompositeArgument

Container for parsing an axis argument.

name = 'axis'
property string

String representation of this variable.

Type:

str

property value

Parsed base argument value.

Type:

object

class canopy_factory.cli.ColorArgument(args, name_base=None, defaults=None, optional=False, args_overwrite=None)[source]

Bases: CompositeArgument

Container for color arguments.

property color

RGBA color tuple.

Type:

tuple

name = 'color'
class canopy_factory.cli.ColorMapArgument(args, name_base=None, defaults=None, optional=False, args_overwrite=None)[source]

Bases: CompositeArgument

Container for colormap arguments.

property colormap

Colormap name.

Type:

str

property limits_defined

True if the limits are defined.

Type:

bool

name = 'colormap'
property scaling

Colormap scaling.

Type:

str

property vmax

Maximum value mapped to colormap.

Type:

units.Quantity

property vmin

Minimum value mapped to colormap.

Type:

units.Quantity

class canopy_factory.cli.CompositeArgument(args, name_base=None, defaults=None, optional=False, args_overwrite=None)[source]

Bases: RegisteredArgumentClassDict

Container for parsing related arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • name_base (str) – Name of the base variable that should be used to set defaults.

  • defaults (dict, optional) – Defaults that should be used for time arguments before the class _defauls.

  • optional (bool, optional) – If True, defaults from the class will not be set when the argument is not defined.

  • args_overwrite (dict, optional) – Arguments to overwrite.

Class Attributes:
  • _name (str) – Name of the base variables that should be used to determine the prefix/suffix and where the instance should be stored on the parsed arguments.

  • _defaults (dict) – Argument defaults.

  • _arguments_prefixed (list) – Arguments that should be prefixed.

  • _arguments_universal (list) – Arguments that should not be prefixed/suffixed.

any_set(names)[source]

Check if any of the specified arguments were set.

Parameters:

names (list) – Argument names to check.

Returns:

True if any of the arguments were set.

Return type:

bool

check_unused(name, output=<class 'canopy_factory.utils.NoDefault'>, matches=None, invalid=None)[source]

Assert that unused arguments were not set.

Parameters:
  • name (str, list) – Argument name(s) to check.

  • output (object, optional) – Output to try to extract arguments from.

  • matches (dict, optional) – Existing dictionary that matches should be added to.

  • invalid (list, optional) – Existing list that used arguments should be added to.

Raises:

AssertionError – If unused arguments were set and matches or invalid was not provided.

classmethod class_factory(name, registry_name=None, **kwargs)[source]

Create a new class for a modified version of the arguments.

Parameters:
  • name (str) – Composite argument name.

  • registry_name (str, optional) – Name that should be used to register the generated class. If not provided, one will be generated.

  • **kwargs – Additional keyword arguments are used to modify the set of arguments for the new class.

Returns:

Composite argument class.

Return type:

type

classmethod composite_argument()[source]
description = ''
extract_unused(out, name)[source]

Extract the equivalent value from an output.

Parameters:
  • out (object) – Output.

  • name (str) – Argument to extract from out.

Returns:

Argument value.

Return type:

object

classmethod from_args(args, name=None, overwrite=False, dont_update=False, **kwargs)[source]

Create an instance on the provided arguments, first checking if one already exists.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • name (str, optional) – Name that should be used for the composite argument.

  • overwrite (bool, optional) – If True, overwrite the existing instance.

  • dont_update (bool, optional) – If True, don’t set the argument attributes.

  • **kwargs – Additional keyword arguments are passed to the class constructor.

Returns:

New or existing instance.

Return type:

CompositeArgument

classmethod from_other(other, **kwargs)[source]

Create an argument instance from an existing instance of any CompositeArgument subclass.

Parameters:
  • other (CompositeArgument) – Instance to copy.

  • **kwargs – Additional keyword arguments are passed to the class constructor.

Returns:

Copy as this class.

Return type:

CompositeArgument

classmethod get_prefix(name)[source]

Get the prefix used for a variable.

Parameters:

name (str) – Variable name.

Returns:

Variable prefix.

Return type:

str

classmethod get_suffix(name)[source]

Get the suffix used for a variable.

Parameters:

name (str) – Variable name.

Returns:

Variable suffix.

Return type:

str

classmethod is_factory_analogue(other)[source]

Check if an instance is an analagous factory class.

Parameters:

other (CompositeArgument)

Returns:

True if the instance is of an analagous class.

Return type:

bool

is_wildcard(k)[source]

Check if an argument is a wildcard.

Parameters:

k (str, list) – Argument(s) to check.

Returns:

True if argument is wildcard.

Return type:

bool

name = None
classmethod parse(x, args, name=None, **kwargs)[source]

Parse an argument.

Parameters:
  • x (object) – Instance to parse.

  • args (argparse.Namespace) – Parsed arguments.

  • name (str, optional) – Name that should be used for the composite argument.

  • **kwargs – Additional keyword arguments are passed to the from_args method.

Returns:

The parsed instance.

Return type:

CompositeArgument

prefix = ''
raw_args(name=None)[source]

dict: Set of name/value pairs for arguments related to this argument.

reset(args, args_overwrite=None)[source]

Reinitialize the arguments used by this instance.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • args_overwrite (dict, optional) – Arguments to overwrite.

setarg(name, value)[source]

Set an argument value.

Parameters:
  • name (str) – Argument name.

  • value (object) – Argument value.

setdefaults(names)[source]

Set defaults for missing arguments that were not set.

Parameters:

names (list) – Argument names to set defaults for.

Returns:

True if all defaults could be initialized, False

otherwise.

Return type:

bool

property string

String representation of this variable.

Type:

str

suffix = ''
update_args(args, name=None)[source]

Update a namespace with the parsed arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • name (str, optional) – Alternate name where the argument should be stored.

property value

Parsed base argument value.

Type:

object

class canopy_factory.cli.InstrumentedParser(*args, parent=None, positional_index=0, **kwargs)[source]

Bases: ArgumentParser

Class for parsing arguments allowing arguments to be added to multiple subparsers.

add_argument(*args, **kwargs)[source]

Add an argument to the parser.

Parameters:
  • *args – All arguments are passed to the add_argument method of the subparsers (if there are any) or the parent class (if there are not any subparsers).

  • **kwargs – All arguments are passed to the add_argument method of the subparsers (if there are any) or the parent class (if there are not any subparsers).

add_subparser(group, name, add_missing_group=True, **kwargs)[source]

Add a subparser to a subparsers group.

Parameters:
  • group (str) – Name of the subparser group that the parser belongs to.

  • name (str) – Name of the subparser.

  • add_missing_group (bool, dict, optional) – If True or dictionary, the subparser group will be added if it is missing. If a dictionary is provided it will be passed as keyword arguments to the add_subparsers method.

  • **kwargs – Additional keyword argumetns are passed to the add_parser method of the wrapped subparsers group.

Returns:

Parser.

Return type:

InstrumentedParser

add_subparser_defaults(args)[source]
add_subparsers(group, **kwargs)[source]

Add a subparsers group to this parser.

Parameters:
  • group (str) – Name of the subparser group. Used to set the default ‘title’ & ‘dest’ subparser properties.

  • **kwargs – Additional keyword arguments are passed to the base class’s method.

Returns:

Wrapped subparsers group.

Return type:

InstrumentedSubparsers

construct_subparser(group, args, **kwargs)[source]

Construct the subparser selected by a subparser group.

Parameters:
  • group (str) – Name of the subparser group to construct.

  • args (argparse.Namespace) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to the class constructor.

Returns:

Subparser instance.

Return type:

SubparserBase

find_argument(name, default=<class 'canopy_factory.utils.NoDefault'>)[source]

Find the action that will handle an argument.

Parameters:
  • name (str) – Argument name or flag.

  • default (object, optional) – Object that should be returned if the arguments cannot be located.

Returns:

Argument action.

Return type:

Action

Raises:

KeyError – If the argument cannot be located and a default is not provided.

get_subparser(group, name, default=<class 'canopy_factory.utils.NoDefault'>, add_missing=False, add_missing_group=None)[source]

Get a single subparser from a subparser group.

Parameters:
  • group (str) – Name of the subparser group that the parser belongs to.

  • name (str) – Name of the subparser.

  • default (object, optional) – Default to return if the subparser instance does not exist.

  • add_missing (bool, dict, optional) – If True or dictionary, add the subparser if it does not exist. If a dictionary is provided, it will be passed as keyword arguments to the add_subparser method.

  • add_missing_group (bool, dict, optional) – If True or dictionary, the subparser group will be added if it is missing. If a dictionary is provided it will be passed as keyword arguments to the add_subparsers method. If not provided, add_missing_group will be set to True only if add_missing is True or a dictionary.

Returns:

Parser.

Return type:

InstrumentedParser

Raises:

KeyError – If default not provided and the subparser object does not exist.

get_subparsers(group, default=<class 'canopy_factory.utils.NoDefault'>, add_missing=False)[source]

Get the subparsers object with the specified group name.

Parameters:
  • group (str) – Name of the subparsers instance to retrieve.

  • default (object, optional) – Default to return if the subparsers instance does not exist.

  • add_missing (bool, dict, optional) – If True or dictionary, add the subparser group if it does not exist. If a dictionary is provided, it will be passed as keyword arguments to the add_subparsers method.

Returns:

Subparsers instance.

Return type:

InstrumentedSubparsers

Raises:

KeyError – If default not provided and the subparsers object does not exist.

has_argument(name)[source]

Check to see if the parser has an argument.

Parameters:

name (str) – Argument name or flag.

Returns:

True if the parser has an argument matching the name,

False otherwise.

Return type:

bool

has_subparser(group, name)[source]

Check if there is a named subparser within a subparsers group.

Parameters:
  • group (str) – Name of the subparsers group to check for.

  • name (str) – Name of the parser within the subparsers group to check for.

Returns:

True if the named parser within the subparsers group

exists.

Return type:

bool

has_subparsers(group)[source]

Check if there is a subparsers group associated with the specified name.

Parameters:

group (str) – Name of the subparsers group to check for.

Returns:

True if the named subparsers group exists.

Return type:

bool

local_subparsers(subparsers=None)[source]

Get the subparser instances for the subparser group directly managed by this parser (if there is one).

Parameters:

subparsers (list, optional) – Names of subparsers that should be included in the returned list. If not provided, all subparsers in the group will be returned.

Returns:

Subparser instances.

Return type:

list

parse_known_args(args=None, namespace=None, **kwargs)[source]

Parse known arguments.

Parameters:
  • args (list, optional) – Arguments to parse. Defaults to sys.argv if not provided.

  • namespace (argparse.Namespace, optional) – Existing namespace that arguments should be added to.

  • **kwargs – Additional keyword arguments are passed to the parent class’s method.

Returns:

Parsed and unparsed

arguments.

Return type:

tuple(argparse.Namespace, list)

prune_irrelevant_args(args)[source]

Remove dependent arguments from the parser that are not valid for the provided arguments.

Parameters:

args (argparse.Namespace) – Arguments parsed so far.

Returns:

True if arguments were pruned, False otherwise.

Return type:

bool

remove_argument(name)[source]

Remove an argument from the parser.

Parameters:

name (str) – Name of the argument to remove.

run_subparser(group, args, return_func=False)[source]

Run the subparser selected by a subparser group.

Parameters:
  • group (str) – Name of the subparser group to run.

  • args (argparse.Namespace) – Parsed arguments.

  • return_func (bool, optional) – If True, return the subparser run function without calling it.

subparser_class(group, args)[source]

Get the subparser class selected by a subparser group.

Parameters:
  • group (str) – Name of the subparser group to get the class for.

  • args (argparse.Namespace) – Parsed arguments.

Returns:

Subparser class.

Return type:

type

subparsers(group=None, subparsers=None, yield_roots=False)[source]

Iterate over all subparser instances within this parser.

Parameters:
  • group (str, optional) – Group that subparsers should be returned for. If not provided, all leaf level subparsers will be yielded.

  • subparsers (dict, optional) – Maps between the names of subparser groups and the names of subparsers within those groups that should be included.

  • yield_roots (bool, optional) – If True, yield the highest level parser that matches the group.

Yields:

InstrumentedParser – Subparsers.

class canopy_factory.cli.InstrumentedParserSet(parent, members)[source]

Bases: SetBase

Simple wrapper for a set of parsers.

Parameters:
  • members (list) – Set of parsers.

  • parent (ArgumentParser, optional) – Parser containing this group.

add_argument(*args, **kwargs)[source]

Add an argument to the parser.

Parameters:
  • *args – All arguments are passed to the add_argument method of the subparsers (if there are any) or the parent class (if there are not any subparsers).

  • **kwargs – All arguments are passed to the add_argument method of the subparsers (if there are any) or the parent class (if there are not any subparsers).

add_subparsers(group, **kwargs)[source]

Add a subparsers group to this parser.

Parameters:
  • group (str) – Name of the subparser group. Used to set the default ‘title’ & ‘dest’ subparser properties.

  • **kwargs – Additional keyword arguments are passed to the base class’s method.

Returns:

Wrapped subparsers group.

Return type:

InstrumentedParserSet

class canopy_factory.cli.InstrumentedSubparserSet(parent, members)[source]

Bases: InstrumentedParserSet

Simple wrapper for a set of subparsers.

add_parser(name, *args, **kwargs)[source]

Add a parser to the subparser group.

Parameters:
  • name (str) – ID string for the parser.

  • *args – Additional arguments are passed to the add_parser method for the underlying subparser group.

  • **kwargs – Additional keyword arguments are passed to the add_parser method for the underlying subparser group.

Returns:

New subparser.

Return type:

ArgumentParser

property choices

Set of subparsers in the group.

Type:

dict

get_parser(name, *args, **kwargs)[source]

Get a parser for an option in the subparser group.

Parameters:
  • name (str) – ID string for the parser.

  • default (object, optional) – Default to return if the subparser instance does not exist.

  • add_missing (bool, dict, optional) – If True or dictionary, add the subparser if it does not exist. If a dictionary is provided, it will be passed as keyword arguments to the add_parser method.

  • *args – Additional arguments are passed to the get_parser method for the underlying subparser group.

  • **kwargs – Additional keyword arguments are passed to the get_parser method for the underlying subparser group.

Returns:

Subparser.

Return type:

ArgumentParser

has_parser(name)[source]

Check if there is a parser for a given name within this subparser group.

Parameters:

name (str) – ID string for the parser.

Returns:

True if the name parser exists, False otherwise.

Return type:

bool

class canopy_factory.cli.IterationTaskBase(*args, **kwargs)[source]

Bases: TaskBase

Base class for iterating over a task.

property args_overwrite

Arguments to overwrite for each step.

Type:

dict

finalize_step(x)[source]

Finalize the output from a step.

Parameters:

x (object) – Result of step.

Returns:

Finalized step result.

Return type:

object

join_steps(xlist)[source]

Join the output form all of the steps.

Parameters:

xlist (list) – Result of all steps.

Returns:

Joined output from all steps.

Return type:

object

overwrite_outputs(downstream=None, wildcards=None, skipped=None)[source]

Remove existing files that should be overwritten.

Parameters:
  • downstream (list, optional) – Existing list that output names should be added to that downstream files need to be removed for.

  • wildcards (list, optional) – List of arguments that wildcards should be used for in the generated output file names.

  • skipped (list, optional) – List of arguments that should be skipped in the generated output file name.

run_steps(output_name='instance')[source]

Run the steps.

Parameters:

output_name (str, optional) – Step output that should be passed to finalize_step for each step.

Returns:

Output from each step.

Return type:

list

step_args()[source]

Yield the updates that should be made to the arguments for each step.

Yields:

dict – Step arguments.

step_args_full()[source]

Yield the full updates that will be made to the arguments for each step including class level updates.

Yields:

dict – Step arguments.

class canopy_factory.cli.LightArgument(args, name_base=None, defaults=None, optional=False, args_overwrite=None)[source]

Bases: CompositeArgument

Container for parsing light arguments.

check_available(name, others=None)[source]

Check if a variable is available.

Parameters:
  • name (str) – Variable to check.

  • others (list, optional) – Auxillary variables to check via setdefaults.

classmethod integrate_spectrum(spectrum, start, stop)[source]
property irradiance

Flux density.

Type:

units.Quantity

property luminous_flux

Perceived amount of visible light.

Type:

units.Quantity

name = 'light'
property par_flux

Photosynthetically active flux.

Type:

units.Quantity

property par_irradiance

Photosynthetically active flux density.

Type:

units.Quantity

classmethod parse_spectrum(fname)[source]
property ppf

Photosynthetically active photon flux.

Type:

units.Quantity

property ppfd

Photosynthetically active photon flux density.

Type:

units.Quantity

property radiant_flux

Radiated power.

Type:

units.Quantity

reset(args, **kwargs)[source]

Reinitialize the arguments used by this instance.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to the base method.

class canopy_factory.cli.LocationArgument(args, **kwargs)[source]

Bases: CompositeArgument

Container for parsing location arguments.

create_solar_model(time, **kwargs)[source]

Create a solar model for this location.

Parameters:
  • time (datetime.datetime) – Time that the model should be created for.

  • **kwargs – Additional keyword arguments are passed to the utils.SolarModel constructor after being augmented with missing location data from this argument.

Returns:

Solar model.

Return type:

utils.SolarModel

property is_northern_hemisphere

True if the latitude is in the norther hemisphere.

Type:

bool

name = 'location'
reset(args, **kwargs)[source]

Reinitialize the arguments used by this instance.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to the base method.

property string

String representation of the location.

Type:

str

class canopy_factory.cli.OptimizationTaskBase(*args, **kwargs)[source]

Bases: IterationTaskBase

Base class for tasks that iterate to achieve a result.

property args_overwrite

Arguments to overwrite for each step.

Type:

dict

final_output_args(name)[source]

Get the arguments that should be used generate the final output.

Parameters:

name (str) – Name of the final output to generate.

Returns:

Arguments to use.

Return type:

dict

property goal

Value that should be achieved.

Type:

units.Quantity

property goal_units

Goal units.

Type:

str

objective(x)[source]

Objective function for use with scipy.optimize.minimize.

Parameters:

x (np.ndarray) – Input arguments.

Returns:

Result.

Return type:

float

run_steps(output_name='instance')[source]

Run the steps.

Parameters:

output_name (str, optional) – Step output that should be passed to finalize_step for each step.

Returns:

Output from each step.

Return type:

list

step_args()[source]

Yield the updates that should be made to the arguments for each step.

Yields:

dict – Step arguments.

property vary_units

Units of argument to vary.

Type:

str

class canopy_factory.cli.OutputArgument(args, ext=None, base_output=None, base_prefix=None, base_suffix=None, directory=None, upstream=None, downstream=None, composite_param=None, merge_all=None, merge_all_output=None, exclude_dynamic_suffix_param=None, parts_generators=None, **kwargs)[source]

Bases: CompositeArgument

Container for output arguments.

assert_age_in_name(args)[source]

Assert that the file name contains age information.

Parameters:

args (argparse.Namespace) – Parsed arguments containing age.

Raises:

AssertionError – If the age string is not present.

clear_overwrite(args=None)[source]

Clear the overwrite parameter.

Parameters:

args (argparse.Namespace, optional) – Parsed arguments to clear.

complete_output(fname, created=False)[source]

Perform tasks to finalize output.

Parameters:
  • fname (str) – Full path to created file.

  • created (bool, optional) – If True, the output has just been created.

classmethod create_test(fname, overwrite=False)[source]

Create a test by copying the provided output file to the corresponding test data directory.

Parameters:
  • fname (str) – Output file to copy to the test directory.

  • overwrite (bool, optional) – If True, overwrite the existing file.

property default_args

Default arguments.

Type:

argparse.Namespace

depends(arguments)[source]

Check if the generated path depends on any of the listed arguments.

Parameters:

arguments (list) – Set of arguments to check dependence on.

Returns:

True if the path depends on any of the listed

arguments.

Return type:

bool

property directory

Directory where the generated file name should reside.

Type:

str

property dont_write

True if dont_write set.

Type:

bool

property enabled

Output file

Type:

str

property exists

True if the file exists.

Type:

bool

generate(args, reset=False, wildcards=None, skipped=None)[source]

Generate the file name.

Parameters:
  • args (argparse.Namespace) – Parsed arguments that file name should be generated from.

  • reset (bool, optional) – If True, reset the generated path on the instance.

  • wildcards (list, optional) – List of arguments that wildcards should be used for in the generated output file name.

  • skipped (list, optional) – List of arguments that should be skipped in the generated output file name.

Returns:

Generated file name.

Return type:

str

property generated

True if the file name is generated.

Type:

bool

is_iterating(k)[source]

Check if a parameter’s value indicates the output is an composite of other outputs.

Parameters:

k (str) – Parameter name.

Returns:

True if the output is an composite of other outputs.

Return type:

bool

is_merged(k)[source]

Check if a parameter’s value indicates the output is an merged composite of other outputs.

Parameters:

k (str) – Parameter name.

Returns:

True if the output is an merged composite of other

outputs.

Return type:

bool

property is_test

True if the output points to the test directory.

Type:

bool

is_unmerged(k)[source]

Check if a parameter’s value indicates the output is an unmerged composite of other outputs.

Parameters:

k (str) – Parameter name.

Returns:

True if the output is an unmerged composite of other

outputs.

Return type:

bool

property iterating_param

Set of parameters that the output is a composite of.

Type:

list

property make_test

True if the output is used as test_data.

Type:

bool

property merged_param

Set of parameters that the output is merged for.

Type:

list

name = 'output'
property overwrite

True if overwrite set.

Type:

bool

property overwrite_downstream

True if downstream files should be overwritten.

Type:

bool

property parts_defaults

Defaults for file name parts.

Type:

dict

property parts_generators

Generator methods for file name parts.

Type:

dict

property path

File name.

Type:

str

classmethod record_tests(fname)[source]

Record any tests associated with the provided file.

Parameters:

fname (str) – File or file pattern to check for test counterparts.

Returns:

True if there is a corresponding test.

Return type:

bool

remove(args=None, wildcards=None, skipped=None, force=False, skip_test_output=False)[source]

Remove the output file.

Parameters:
  • args (argparse.Namespace, optional) – Parsed arguments. Only required if the path has not been set or wildcards are provided.

  • wildcards (list, optional) – List of arguments that wildcards should be used for in the generated output file name.

  • skipped (list, optional) – List of arguments that should be skipped in the generated output file name.

  • force (bool, optional) – If True, remove without asking for user input.

  • skip_test_output (bool, optional) – If True, don’t include both test output and generated file name.

remove_downstream(args, removed=None, wildcards=None, args_copied=False, **kwargs)[source]

Remove downstream outputs.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • removed (list, optional) – List of outputs that have already been removed (to prevent duplication of effort).

  • wildcards (list, optional) – List of arguments that wildcards should be used for in the generated output file name.

  • args_copied (bool, optional) – If True, the arguments have already been copied.

  • **kwargs – Additional keyword arguments are passed to nested calls to ‘remove’ for downstream outputs.

reset(args, **kwargs)[source]

Reinitialize the arguments used by this instance.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to the base method.

reset_generated(value=None)[source]

Reset the generated path.

Parameters:

value (str, optional) – New value for the generated path.

property task_class

The task class that produces this output.

Type:

type

property unmerged_param

Set of parameters that the output is unmerged for.

Type:

list

property value

Parsed base argument value.

Type:

object

exception canopy_factory.cli.RepeatIterationError(args_overwrite=None)[source]

Bases: BaseException

Error can be raised if a step should be repeated.

class canopy_factory.cli.SetBase(parent, members)[source]

Bases: object

Simple wrapper for a set of classes.

Parameters:
  • members (list) – Set of instances of the same class.

  • parent (object, optional) – Instance containing this group.

class canopy_factory.cli.SubParsersAction(*args, default=None, choices=None, func=None, positional_index=0, subparser_name=None, **kwargs)[source]

Bases: _SubParsersAction

add_argument(*args, **kwargs)[source]

Add an argument to the parser.

Parameters:
  • *args – All arguments are passed to the add_argument method of the subparsers (if there are any) or the parent class (if there are not any subparsers).

  • **kwargs – All arguments are passed to the add_argument method of the subparsers (if there are any) or the parent class (if there are not any subparsers).

add_parser(name, *args, **kwargs)[source]

Add a parser to the subparser group.

Parameters:
  • name (str) – ID string for the parser.

  • *args – Additional arguments are passed to the add_parser method for the underlying subparser group.

  • **kwargs – Additional keyword arguments are passed to the add_parser method for the underlying subparser group.

Returns:

New subparser.

Return type:

ArgumentParser

add_subparsers(group, **kwargs)[source]

Add a subparsers group to each parser in this subparser group.

Parameters:
  • group (str) – Name of the subparser group. Used to set the default ‘title’ & ‘dest’ subparser properties.

  • **kwargs – Additional keyword arguments are passed to the base class’s method.

Returns:

Set of subparsers for each parser.

Return type:

InstrumentedParserSet

find_argument(name, default=<class 'canopy_factory.utils.NoDefault'>)[source]

Find the action that will handle an argument.

Parameters:
  • name (str) – Argument name or flag.

  • default (object, optional) – Object that should be returned if the arguments cannot be located.

Returns:

Argument action.

Return type:

Action

Raises:

KeyError – If the argument cannot be located and a default is not provided.

get_parser(name, default=<class 'canopy_factory.utils.NoDefault'>, add_missing=False)[source]

Get a parser for an option in the subparser group.

Parameters:
  • name (str) – ID string for the parser.

  • default (object, optional) – Default to return if the subparser instance does not exist.

  • add_missing (bool, dict, optional) – If True or dictionary, add the subparser if it does not exist. If a dictionary is provided, it will be passed as keyword arguments to the add_parser method.

Returns:

Subparser.

Return type:

ArgumentParser

has_argument(name)[source]

Check to see if the parser has an argument.

Parameters:

name (str) – Argument name or flag.

Returns:

True if the parser has an argument matching the name,

False otherwise.

Return type:

bool

has_parser(name)[source]

Check if there is a parser for a given name within this subparser group.

Parameters:

name (str) – ID string for the parser.

Returns:

True if the name parser exists, False otherwise.

Return type:

bool

remove_argument(name)[source]

Remove an argument from the parser.

Parameters:

name (str) – Name of the argument to remove.

class canopy_factory.cli.SubparserBase(args=None, args_overwrite=None)[source]

Bases: RegisteredArgumentClassBase

Base class for tasks associated with subparsers.

Parameters:
  • args (argparse.Namespace, optional) – Parsed arguments. If not provided, additional keyword arguments are parsed to create args and keyword arguments that are not used by the parser are passed to the run method.

  • **kwargs – Additional keyword arguments are passed to the run method.

class canopy_factory.cli.TaskBase(args=None, root=None, cached_outputs=None)[source]

Bases: SubparserBase

Base class for tasks.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • root (TaskBase, optional) – Top level task.

  • cached_outputs (dict, optional) – Outputs that have been cached in memory.

Class Attributes:
  • _output_info (dict) – Properties of task outputs.

  • _outputs_local (list) – Outputs produced by this task.

  • _outputs_required (list) – Required local outputs.

  • _outputs_optional (list) – Optional local outputs.

  • _outputs_external (dict) – Mapping between outputs produced by external tasks that are used by this task and the external task that produces it.

  • _outputs_total (list) – All outputs produced by this task or the external tasks that are used by this task.

  • _external_tasks (dict) – Mapping of external tasks used by this task and information about how arguments should be adopted by this task.

  • _dont_inherit_base (bool) – If True, arguments of the base class will not be inherited.

classmethod adjust_args(args, subset=None)[source]

Adjust the parsed arguments including setting defaults that depend on other provided arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • subset (list, optional) –

    Set of arguments that should be adjusted. If not provided, all of the available arguments identified by the available options will be performed.:

    'internal': Internal arguments will be adjusted by
        this task.
    'external': External arguments will be adjusted by
        external tasks.
    'outputs': Output arguments will be adjusted.
    

classmethod adjust_args_external(args, **kwargs)[source]

Adjust the parsed arguments including setting defaults that depend on other provided arguments for external tasks.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to adjust_args for each external task.

classmethod adjust_args_internal(args, skip=None)[source]

Adjust the parsed arguments including setting defaults that depend on other provided arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • skip (list, optional) – Set of arguments to skip.

classmethod adjust_args_output(args)[source]

Create the output arguments (assumes that adjust_args has already been called to initialize the other arguments.

Parameters:

args (argparse.Namespace) – Parsed arguments.

property all_data_years

All data years for current crop.

Type:

list

property all_ids

All crop classes for current data.

Type:

list

property axes

Matplotlib axes.

cache_output(name=None)[source]

Cache output on the root task for later use.

Parameters:

name (str, list, optional) – Name(s) of one or more outputs to remove.

classmethod complete_external_args(args)[source]

Add missing arguments to the provided argument set.

Parameters:

args (argparse.Namespace) – Parsed arguments to complete.

classmethod copy_external_args(args=None, args_overwrite=None, args_external=None, set_defaults=False, initialize=False, return_dict=False, verbose=False)[source]

Extract arguments for this task from a set for another task.

Parameters:
  • args (argparse.Namespace, optional) – Parsed arguments to copy.

  • args_overwrite (dict, optional) – Arguments to overwrite.

  • args_external (list, optional) – External arguments that should be preserved.

  • set_defaults (bool, optional) – If True, don’t set missing arguments to defaults.

  • initialize (bool, optional) – If True, initialize arguments by applying adjust_args (implies set_defaults == True).

  • return_dict (bool, optional) – Return a dictionary instead of argparse.Namespace.

  • verbose (bool, optional) – If True, write copied arguments to a log message.

Returns:

Arguments.

Return type:

argparse.Namespace

copy_matching_outputs(other)[source]

Copy existing outputs from another task to prevent repeated I/O when the files match.

Parameters:

other (TaskBase) – Instance to copy from.

enabled_outputs(for_write=False)[source]

Get the set of outputs enabled by the provided arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • for_write (bool, optional) – If True, only return outputs for which write is enabled.

Returns:

Names of enabled outputs.

Return type:

list

property figure

Matplotlib figure.

finalize(dont_overwrite=False)[source]

Perform steps to finalize the class for use.

Parameters:

dont_overwrite (bool, optional) – If True, don’t remove overwritten files.

classmethod from_external_args(args, args_overwrite=None, args_external=None, copy_outputs_from=None, verbose=False, **kwargs)[source]

Create an instance from a set of external arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • args_ovewrite (dict, optional) – Argument values to set for the run after copying the current argument namespace.

  • args_external (list, optional) – External arguments that should be preserved.

  • copy_outputs_from (TaskBase, optional) – Existing instance that matching outputs should be copied from.

  • verbose (bool, optional) – If True, write copied arguments to a log message.

  • **kwargs – Additional keyword arguments are passed to the class constructor.

Returns:

New task instance.

Return type:

TaskBase

classmethod from_kwargs(kws, **kwargs)[source]

Create an instance from the provided arguments.

Parameters:
  • kws (dict) – Keyword arguments that should be parsed into arguments via the parse function.

  • **kwargs – Additional keyword arguments are passed to the class constructor.

generate_output(name)[source]

Generate the specified output value.

Parameters:

name (str) – Name of the output to generate.

Returns:

Generated output.

Return type:

object

get_iteration_values(k)[source]

Get the set of parameter values that should be iterated over when ‘all’ is specified.

Parameters:

k (str) – Parameter name to get values for.

Returns:

Iteration values.

Return type:

list

classmethod get_line_properties(args, **kws)[source]

Get keyword arguments for a line plot based on properties passed via the command line arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • **kws – Additional keyword arguments are properties that should be used when selecting line styles & colors.

Returns:

Keyword arguments for line plot.

Return type:

dict

get_output(name=None)[source]

Get a task output, generating or loading it if necessary.

Parameters:

name (str, list, optional) – Name(s) of one or more outputs to return.

Returns:

Output.

Return type:

object

classmethod get_output_task(name, default=<class 'canopy_factory.utils.NoDefault'>)[source]

Determine which task class produces the named output.

Parameters:
  • name (str) – Output name.

  • default (object, optional) – Value to return if the task class cannot be located.

Returns:

Task class.

Return type:

type

get_parameter_inst()[source]

Get the instance of ParametrizeCropTask used by this task.

Returns:

Instance that parametrizes geometries.

Return type:

ParametrizeCropTask

property is_root

True if this is the root task.

Type:

bool

output_argument(name=None)[source]

Get the OutputArgument instance for an output.

Parameters:

name (str, optional) – Name of the output to return the argument instance for.

Returns:

Argument instance controling output.

Return type:

OutputArgument

output_depends(name, variables)[source]

Determine if an output is dependent on a variable.

Parameters:
  • name (str) – Name of output to check dependency of.

  • variables (list) – List of arguments to check if the affect the named output.

Returns:

True if the output depends on the named variables.

Return type:

bool

output_enabled(name=None, for_write=False)[source]

Check if an output is enabled by the current arguments.

Parameters:
  • name (str, list, optional) – Name(s) of one or more outputs to check.

  • for_write (bool, optional) – If True, only return True if output is enabled and write is not disabled.

Returns:

True if the output is enabled, False otherwise.

Return type:

bool

output_exists(name=None)[source]

Check if a task output exists.

Parameters:

name (str, list, optional) – Name(s) of one or more outputs to check for.

Returns:

True if the output file exists.

Return type:

bool

output_file(name=None, return_disabled=False, regenerate=False, wildcards=None, skipped=None, copy_args=False)[source]

Get the filename for an output.

Parameters:
  • name (str, list, optional) – Name(s) of one or more outputs to get the files for.

  • return_disabled (bool, optional) – If True, return the generated filename even if the output is disabled.

  • regenerate (bool, optional) – If True, regenerate all output file names.

  • wildcards (list, optional) – List of arguments that wildcards should be used for in the generated output file name.

  • skipped (list, optional) – List of arguments that should be skipped in the generated output file name.

  • copy_args (bool, optional) – If True, the args should be copied and initialized.

Returns:

Name of output file. If True, this indicates the output

should be generated, but not written. If False, the output should not be generated.

Return type:

str

output_missing(name=None)[source]

Check if a task output is enabled, but does not exist.

Parameters:

name (str, list, optional) – Name(s) of one or more outputs to check for.

Returns:

True if the output file exists.

Return type:

bool

output_names(**kwargs)[source]

Get the list of outputs that will be generated.

Parameters:

**kwargs – Keyword arguments are passed to _output_names.

Returns:

Output names.

Return type:

list

output_task(name, default=<class 'canopy_factory.utils.NoDefault'>, from_root=False)[source]

Get the task instance responsible for producing an output.

Parameters:
  • name (str) – Name of output to get task for.

  • default (object, optional) – Value to return if the task instance cannot be located.

  • from_root (bool, optional) – If True, start from the root task.

Returns:

Task that produces the output.

Return type:

TaskBase

overwrite_output(name=None, wildcards=None, skipped=None)[source]

Prepare an output for a run. If overwrite specified, any existing data/files for the output will be removed. If the output file is not fully specified on the args, it will be set.

Parameters:
  • name (str, list, optional) – Name(s) of one or more outputs to handle overwrite for.

  • wildcards (list, optional) – List of arguments that wildcards should be used for in the generated output file names.

  • skipped (list, optional) – List of arguments that should be skipped in the generated output file name.

Returns:

True if downstream outputs should be removed.

Return type:

bool

overwrite_outputs(downstream=None, wildcards=None, skipped=None)[source]

Remove existing files that should be overwritten.

Parameters:
  • downstream (list, optional) – Existing list that output names should be added to that downstream files need to be removed for.

  • wildcards (list, optional) – List of arguments that wildcards should be used for in the generated output file names.

  • skipped (list, optional) – List of arguments that should be skipped in the generated output file name.

property raw_figure_data

Raw pixel data for the current figure.

Type:

np.ndarray

read_output(name=None, fname=None)[source]

Load an output file produced by this task.

Parameters:
  • name (str, optional) – Name of the output to read.

  • fname (str, optional) – File to read if different than the generated file name.

Returns:

Contents of the output file.

Return type:

object

remove_output(name=None, remove_local=False, **kwargs)[source]

Remove existing output file.

Parameters:
  • name (str, list, optional) – Name(s) of one or more outputs to remove.

  • remove_local (bool, optional) – If True, remove any in-memory output.

  • **kwargs – Additional keyword arguments are passed to _remove_output.

run(output_name=None)[source]

Run the process associated with this subparser.

Parameters:

output_name (str, optional) – Name of output that should be returned. Defaults to the output with the same name as the task.

Returns:

Output named by output_name.

Return type:

object

classmethod run_class(args, output_name=None, args_preserve=None, cache_outputs=None, **kwargs)[source]

Run the process associated with this subparser.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • output_name (str, optional) – Name of output that should be returned. Defaults to the output with the same name as the task. If ‘instance’ is provided, the created task instance will be returned.

  • args_preserve (list, optional) – Set of argument names to preserve following a run.

  • cache_outputs (list, optional) – Set of outputs that should be cached.

  • **kwargs – Additional keyword arguments are passed to from_external_args.

Returns:

Result of the run.

Return type:

object

run_iteration(cls=None, **kwargs)[source]

Run an iteration, regenerating output file names.

Parameters:
  • cls (type, optional) – Task class that should be run in iteration. Defaults to the type of the current task.

  • **kwargs – Additional keyword arguments are passed to run_iteration_class.

Returns:

Result of the run.

Return type:

object

classmethod run_iteration_class(args, **kwargs)[source]

Run an iteration, regenerating output file names.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to run_class.

Returns:

Result of the run (defaults to the task instance).

Return type:

object

run_series(cls=None, **kwargs)[source]

Run the process for a series of arguments.

Parameters:
  • cls (type, optional) – Task class that should be run in iteration. Defaults to the type of the current task.

  • **kwargs – Additional keyword arguments are passed to cls.run_series_class.

Yields:

object – Results from each step.

classmethod run_series_class(args, over=None, per_iter=None, args_overwrite=None, **kwargs)[source]

Run the process for a series of arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • over (dict, optional) – Mapping between argument names and values that should be iterated over.

  • per_iter (dict, optional) – Dictionary of argument values that should be added for each iteration. This can be updated between iterations.

  • args_overwrite (dict, optional) – Arguments to overwrite.

  • **kwargs – Additional keyword arguments are passed to cls.run_iteration.

Yields:

object – Results from each step.

set_output(name, output, overwrite=False)[source]

Set an output value for the task.

Parameters:
  • name (str) – Name of the output to set.

  • output (object) – Output instance.

  • overwrite (bool, optional) – If True, overwrite existing output.

classmethod task_hierarchy()[source]

list: Order that outputs should be initialized in.

write_output(name, output, overwrite=False)[source]

Write to an output file.

Parameters:
  • name (str) – Name of the output to write.

  • output (object) – Output object to write to file.

  • overwrite (bool, optional) – If True, overwrite existing output.

class canopy_factory.cli.TemporalTaskBase(*args, **kwargs)[source]

Bases: IterationTaskBase

Base class for tasks that iterate over another class.

classmethod adjust_args_internal(args, **kwargs)[source]

Adjust the parsed arguments including setting defaults that depend on other provided arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to the parent class’s method.

step_args()[source]

Yield the updates that should be made to the arguments for each step.

Yields:

dict – Step arguments.

class canopy_factory.cli.TimeArgument(args, **kwargs)[source]

Bases: AgeArgument

Container for parsing time arguments.

property age

Days since planting.

Type:

units.Quantity

property date

Parsed date instance.

Type:

datetime.datetime

extract_unused(out, name)[source]

Extract the equivalent value from an output.

Parameters:
  • out (object) – Output.

  • name (str) – Argument to extract from out.

Returns:

Argument value.

Return type:

object

getarg(name, default=<class 'canopy_factory.utils.NoDefault'>)[source]

Get an argument value.

Parameters:
  • name (str) – Argument name.

  • default (object, optional) – Value to return if argument does not exist.

Returns:

Argument value.

Return type:

object

Raises:

KeyError – If the argument does not exist and default is not provided.

classmethod is_solar_date(x)[source]

Check if a string is a named solar date.

Parameters:

x (str) – Time to check.

Returns:

True if x is a named solar date.

Return type:

bool

classmethod is_solar_time(x)[source]

Check if a string is a named solar time.

Parameters:

x (str) – Time to check.

Returns:

True if x is a named solar time.

Return type:

bool

iteration_args(dt=None, include_bookends=False, dont_age=False)[source]

Arguments that should be passed to represent this time in an iteration.

Parameters:
  • dt (units.Quantity, optional) – Time interval to apply.

  • include_bookends (bool, optional) – If True, the keys in the returned arguments should include the prefix & suffix.

  • dont_age (bool, optional) – If True, don’t change the age.

Returns:

Arguments.

Return type:

dict

name = 'time'
property planting_date

Planting date.

Type:

datetime.datetime

reset(args, **kwargs)[source]

Reinitialize the arguments used by this instance.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • **kwargs – Additional keyword arguments are passed to the base method.

classmethod reset_args(name, args, value=<class 'canopy_factory.utils.NoDefault'>)[source]

Reset the arguments for a variable.

Parameters:
  • name (str) – Variable name.

  • args (argparse.Namespace) – Parsed arguments.

  • value (object, optional) – Value that the parsed variable should be reset to.

setarg(name, value)[source]

Set an argument value.

Parameters:
  • name (str) – Argument name.

  • value (object) – Argument value.

property solar_date_string

Solar date string.

Type:

str

property solar_model

Solar model.

Type:

SolarModel

property solar_time_string

Solar time string.

Type:

str

property string

String representation of the time.

Type:

str

property time

Parsed time instance.

Type:

datetime.datetime

update_args(args, name=None)[source]

Update a namespace with the parsed time arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • name (str, optional) – Alternate name where the argument should be stored.

canopy_factory.cli.main(**kwargs)[source]

Parse arguments provided via the command line or keyword arguments and run the parsed task.

Parameters:

**kwargs – If any keyword args are passed, they are parsed instead of the command line arguments.

Returns:

Argument namespace and keyword

keyword arguments that were not parsed.

Return type:

argparse.Namespace, dict

canopy_factory.cli.parse(**kwargs)[source]

Parse arguments provided via the command line or keyword arguments

Parameters:

**kwargs – If any keyword args are passed, they are parsed instead of the command line arguments.

Returns:

Argument namespace and keyword

keyword arguments that were not parsed.

Return type:

argparse.Namespace, dict

canopy_factory.config module

class canopy_factory.config.PackageConfig(package, ext='.ini', schema=None, defaults=None)[source]

Bases: ConfigParser, object

Config parser that initializes a default for a package.

Parameters:
  • package (str) – Name of the package the config file is for.

  • ext (str, optional) – File extension for config files.

  • schema (dict, optional) – JSON schema that should be used to parse the loaded result.

  • defaults (dict, optional) – Default values that should be preloaded.

property json

JSON representation of the config options.

Type:

dict

read(fnames=None, reset=False)[source]

Read config options from the default file locations.

Parameters:
  • fnames (str, list, optional) – One or more paths to files that should be read instead of the default files. If not provided the default files will be read.

  • reset (bool, optional) – If True, existing values will be cleared.

reset()[source]

Clear the current parameters.

set(section, option, value=None)[source]

Set an option in a section.

Parameters:
  • section (str) – Section name.

  • option (str) – Option name.

  • value (object, optional) – Option value. None indicates an empty option value.

setdefaults(**kwargs)[source]

Add sections/options that do not already exist.

Parameters:

**kwargs – Section/options pairs that should be added if they don’t exist.

write(fname=None)[source]

Write the config options to a file.

Parameters:

fname (str, optional) – Path to the file that the values should be written to. If not provided, the local file will be used.

canopy_factory.light_sources module

class canopy_factory.light_sources.ArtificalLightSourceBase(args=None, args_overwrite=None)[source]

Bases: LightSourceBase

Base class for artifical light source.

class canopy_factory.light_sources.BulbShapeBase(args=None, args_overwrite=None)[source]

Bases: SubparserBase

Base class for different bulb shapes.

property surface_area

The bulb surface area.

Type:

units.Quantity

property volume

The bulb volume.

Type:

units.Quantity

class canopy_factory.light_sources.BulbTypeBase(args=None, args_overwrite=None)[source]

Bases: SubparserBase

Base class for different bulb types.

class canopy_factory.light_sources.FluorescentBulb(args=None, args_overwrite=None)[source]

Bases: BulbTypeBase

Fluorescent bulb.

class canopy_factory.light_sources.IncandescentBulb(args=None, args_overwrite=None)[source]

Bases: BulbTypeBase

Incandescent bulb.

class canopy_factory.light_sources.LEDBulb(args=None, args_overwrite=None)[source]

Bases: BulbTypeBase

LED bulb.

class canopy_factory.light_sources.LightSourceBase(args=None, args_overwrite=None)[source]

Bases: SubparserBase

Base class for light sources.

property geometry

Light geometry.

Type:

str

property ppf_diffuse

Diffuse photosynthetic photon flux.

Type:

units.Quantity

property ppf_direct

Direct photosynthetic photon flux.

Type:

units.Quantity

class canopy_factory.light_sources.PointBulb(args=None, args_overwrite=None)[source]

Bases: BulbShapeBase

Single point source.

class canopy_factory.light_sources.SolarLightSource(args=None, args_overwrite=None)[source]

Bases: LightSourceBase

Solar light source.

classmethod adjust_args(args, skip=None)[source]

Adjust the parsed arguments including setting defaults that depend on other provided arguments.

Parameters:
  • args (argparse.Namespace) – Parsed arguments.

  • skip (list, optional) – Arguments to skip.

property ppfd_diffuse

Diffuse photosynthetic photon flux density

Type:

units.Quantity

property ppfd_direct

Direct photosynthetic photon flux density

Type:

units.Quantity

property solar_model

Model for the sun using pvlib.

Type:

SolarModel

class canopy_factory.light_sources.SphereBulb(args=None, args_overwrite=None)[source]

Bases: BulbShapeBase

Spherical bulb.

property bulb_radius

The bulb radius.

Type:

units.Quantity

property surface_area

The bulb surface area.

Type:

units.Quantity

property volume

The bulb volume.

Type:

units.Quantity

class canopy_factory.light_sources.StandardBulb(args=None, args_overwrite=None)[source]

Bases: BulbShapeBase

Standard bulb.

class canopy_factory.light_sources.TubeBulb(args=None, args_overwrite=None)[source]

Bases: BulbShapeBase

Tube bulb.

property surface_area

The bulb surface area.

Type:

units.Quantity

property volume

The bulb volume.

Type:

units.Quantity

canopy_factory.simulate module

class canopy_factory.simulate.PhotosynthesisTask(args=None, root=None, cached_outputs=None)[source]

Bases: TaskBase

Class for computing photosynthesis properties from intercepted light.

ePhotosynthesis(args)[source]
property ePhotosynthesis_driver

Driver for the simulation.

Type:

ePhotosynthesis.driver

property ePhotosynthesis_vars

Variables for the simulation.

Type:

ePhotosynthesis.Variables

run_ePhoto(flux_density, area, dont_convert=False)[source]

Run ePhotosynthesis.

Parameters:
  • flux_density (units.Quantity) – Flux density to pass to ePhotosynthesis as TestLi parameters. Should be in units compatible with umol s**-1 m**-2.

  • area (units.Quantity) – Area over which the flux density should be applied.

  • dont_convert (bool, optional) – If True, don’t convert flux density to umol s**-1 m**-2 (assumes it is already converted).

Returns:

Photosynthesis properties.

Return type:

dict

canopy_factory.utils module

class canopy_factory.utils.ChoiceArgument(parser, named_choices=None, type=None)[source]

Bases: object

Wrapper for argument type that allows for named choices.

Parameters:
  • parser (callable) – Type or argument parser that should be applied if the argument is not one of the named choices.

  • named_choices (list, optional) – Set of string values that should also be allowed.

class canopy_factory.utils.ClassRegistry[source]

Bases: object

A place to register classes.

clear_cached_properties(instance, exclude=None, include=None, cls=None, args=False)[source]

Clear the cached properties for an instance.

Parameters:
  • instance (object) – Registered class instance to clear the cached properties of.

  • exclude (list, optional) – Set of cached properties that should be preserved.

  • include (list, optional) – Subset of cached properties that should be cleared.

  • cls (type, optional) – Base class that cached properties should be cleared for.

  • args (bool, optional) – If true, only args cached properties should be cleared.

get(key, name, default=<class 'canopy_factory.utils.NoDefault'>)[source]

Get a registry entry.

Parameters:
  • key (str) – Sub-registry that should be accessed.

  • name (str) – Name of entry that should be returned.

  • default (type, optional) – Value that should be returned if the requested entry is not present.

Returns:

Registry entry.

Return type:

type

Raises:

KeyError – If the requested entry is not present and a default is not provided.

get_cached_properties(instance, exclude=None, include=None, cls=None)[source]

Get the set of cached properties for an instance.

Parameters:
  • instance (object) – Registered class instance to get the cached properties of.

  • exclude (list, optional) – Set of cached properties that should not be included in the returned dictionary.

  • include (list, optional) – Set of cached properties that should be included in the returned dictionary.

  • cls (type, optional) – Base class that cached properties should be returned for.

Returns:

Cached properties.

Return type:

dict

getbase(key, default=<class 'canopy_factory.utils.NoDefault'>)[source]

Get a base class for a registry key.

Parameters:
  • key (str) – Sub-registry that should be accessed.

  • default (type, optional) – Value that should be returned if the requested entry is not present.

Returns:

Registry entry.

Return type:

type

Raises:

KeyError – If the requested entry is not present and a default is not provided.

has_cached_property(instance, k, cls=None)[source]

Check if a cached property has been initialized.

Parameters:
  • instance (object) – Registered class instance to check the cached properties of.

  • k (str) – Name of the cached property to check.

  • cls (type, optional) – Base class that cached properties should be returned for.

Returns:

True if the cached property has been initialized.

Return type:

bool

items(key=None)[source]

Get the registry items.

Parameters:

key (str, optional) – Key for sub-registry that items should be returned for.

Returns:

Registry key/value pairs.

Return type:

iterable

keys(key=None)[source]

Get the registry keys.

Parameters:

key (str, optional) – Key for sub-registry that keys should be returned for.

Returns:

Registry keys.

Return type:

iterable

register(cls)[source]

Register a class.

Parameters:

cls (type) – Class to register.

register_cached_property(method, args=None, readonly=False, classname=None)[source]

Register a cached property.

Parameters:
  • method (function) – Method being registered.

  • args (bool, optional) – If True, the property will be reset when the args for the class are updated.

  • readonly (bool, optional) – If True, the property can only be read, not set.

  • classname (str, optional) – Unique name that should be used to register the property in place of the classname from the method’s __qualname__.

registry(key=None)[source]

Get the registry dictionary.

Parameters:

key (str, optional) – Key for sub-registry that should be returned.

Returns:

Registry.

Return type:

dict

registry_cached_properties(instance, cls=None)[source]

Get the registry of cached properties for an instance.

Parameters:
  • instance (object) – Registered class instance to get the registry for.

  • cls (type, optional) – Base class that registry should be returned for.

set_cached_properties(instance, properties, cls=None)[source]

Set cached properties.

Parameters:
  • instance (object) – Registered class instance to set the cached properties of.

  • properties (dict) – Cached properties to update.

  • cls (type, optional) – Base class that cached properties should be set for.

values(key=None)[source]

Get the registry values.

Parameters:

key (str, optional) – Key for sub-registry that values should be returned for.

Returns:

Registry values.

Return type:

iterable

class canopy_factory.utils.DataProcessor(crop=None, year=None, metadata=None, units=None)[source]

Bases: object

Class for processing crop data into parameters.

Parameters:
  • crop (str) – Crop name.

  • metadata (dict, optional) – Metadata for the crop.

  • units (dict, optional) – Unit system that data will be stored in.

classmethod available_files(crop=None, id=None, year=None)[source]

Locate files containing data for a certain crop and/or year.

Parameters:
  • crop (str, optional) – Crop name.

  • id (str, optional) – ID string to find files for.

  • year (str, optional) – Year that data was collected in.

Returns:

Matching files.

Return type:

list

classmethod available_ids(crop, **kwargs)[source]

Determine the IDs for which there is data available for a given crop.

Parameters:
  • crop (str) – Crop name.

  • **kwargs – Additional keyword arguments are passed to available_files.

Returns:

Available ids.

Return type:

list

classmethod available_param(names, **kwargs)[source]

Get a list of available data set parameters.

Parameters:
  • names (list) – Names of data parameters to include.

  • **kwargs – Additional keyword arguments are passed to available_files and used to select a subset of the available data sets.

Returns:

Set of tuples containing available named parameters.

Return type:

list

classmethod available_years(crop, **kwargs)[source]

Determine the years in which there is data available for a given crop.

Parameters:
  • crop (str) – Crop name.

  • **kwargs – Additional keyword arguments are passed to available_files.

Returns:

Available years.

Return type:

list

classmethod base_id_from_file(*args, **kwargs)[source]

Get the base ID from a datafile.

Parameters:
  • *args – Additional arguments are passed to ids_from_file.

  • **kwargs – Additional keyword arguments are passed to ids_from_file.

Returns:

Base id.

Return type:

str

property crop

Crop that data pertains to.

Type:

str

classmethod extract_parameter_data(df, regex=None, component=None, parameter=None, noffset=-1, debug=False)[source]

Extract data for crop class parameters.

Parameters:
  • df (pandas.DataFrame) – Data frame to extract parameters from.

  • regex (str, optional) – Regular expression that should be used to identify columns and extract parameter names.

  • component (str, optional) – Component that the data pertains to.

  • parameter (str, optional) – Parameter that the data pertains to.

  • noffset (int, optional) – Offset that should be applied to the parsed n value.

  • debug (bool, optional) – If True, turn on debugging.

Returns:

Extracted parameters.

Return type:

dict

classmethod from_file(fname, **kwargs)[source]

Create a DataProcessor instance from a file name.

Parameters:
  • fname (str) – File containing parameter measurements in JSON.

  • **kwargs – Additional keyword arguments are passed to the class constructor.

Returns:

Processory instance with data loaded.

Return type:

DataProcessor

property ids

Set of IDs for genotypes that have data.

Type:

list

classmethod ids_from_file(fname, **kwargs)[source]

Get available ids from a datafile.

Parameters:
  • fname (str) – File containing parameter measurements in JSON.

  • **kwargs – Additional keyword arguments are passed to from_file.

Returns:

ID strings.

Return type:

list

classmethod output_name(crop, year)[source]

Create an output file name for a given crop and year.

Parameters:
  • crop (str) – Crop name.

  • year (str) – Year that data was collected in.

Returns:

Data file name.

Return type:

str

property param

Parameters saved to file.

Type:

dict

parameter_names(idstr=None)[source]

Get the set of parameters present in the data for the provided ID string.

Parameters:

idstr (str, optional) – ID string for the genotype. If not provided all of the parameters present in any of the genotype data will be used.

Returns:

Parameter names.

Return type:

list

parametrize(idstr, args=None, generator=None, default_profile='normal')[source]

Create crop parameters from the raw data collected for those parameters.

Parameters:
  • idstr (str) – ID string for the genotype that should be parametrized.

  • args (ParsedArguments, optional) – Parsed arguments that can be used to specify profiles that should be parametrized for different fields.

  • generator (PlantGenerator, optional) – Crop generator that should be parametrized. If not provided, the generator for the crop specified by the data will be used.

  • default_profile (str, optional) – Default profile that should be used if one is not specified by args.

Returns:

Parameters.

Return type:

dict

plot(fname=None, other=None, parameters=None)[source]

Plot the dependence of parameters on phytomer number.

Parameters:
  • fname (str, optional) – File where the plot should be saved.

  • other (DataProcessor, optional) – Other set of parameters to include.

  • parameters (list, optional) – Set of parameters to plot.

plot_var(ax, idstr, var, nlimits=None)[source]

Add data for a single variable to an axes.

Parameters:
  • ax (matplotlib.axes.Axes) – Axes.

  • idstr (str) – ID string for the genotype that should be plot.

  • var (str) – Name of variable to plot.

  • nlimits (list) – Existing list that should be updated with limits on n.

process_csv(fname, genotype=None, **kwargs)[source]

Process data from a file.

Parameters:
  • fname (str) – Path to CSV file that data should be loaded from.

  • genotype (str, optional) – Name of the genotype that the data in fname pertain to or that should be processed. Required if genotype is not specified in the data.

  • **kwargs – Additional keyword arguments are passed to extract_parameter_data.

read(fname=None)[source]

Read processed data from a JSON file.

Parameters:

fname (str, optional) – Name of the file to read. If not provided, one will be generated using output_name.

classmethod select_data(df, genotype=None, genotypic_class=None, parameter=None, n=None, regex=None)[source]

Select a subset of observed data.

Parameters:
  • df (pandas.DataFrame) – Data frame that should be filtered.

  • genotype (str, optional) – Genotype that should be selected.

  • genotypic_class (str, optional) – Genotypic class that should be selected

  • parameter (str, optional) – Parameter that should be selected.

  • n (int, optional) – Phytomer count that should be selected.

  • regex (str, optional) – Regex to use for data selection.

Returns:

Selected data.

Return type:

pandas.DataFrame

write(fname=None)[source]

Write the processed data to a file as a JSON.

Parameters:

fname (str, optional) – Name of the file to output. If not provided, one will be generated using output_name.

property year

Year that the data was collected.

Type:

str

class canopy_factory.utils.DatetimeArgument(named_choices=None)[source]

Bases: ChoiceArgument

Wrapper for argument type that produces a datetime.

Parameters:

named_choices (list, optional) – Set of string values that should also be allowed.

class canopy_factory.utils.DependentIterationParam(name, value, **depends)[source]

Bases: object

Class for managing interdependency of iteration parameters.

Parameters:
  • name (str) – Parameter name.

  • value (object) – Parameter value.

  • **depends – Additional keyword arguments should be parameters name/value pairs that this parameter is valid for.

classmethod check_param(param)[source]

Check a set of parameters for dependencies.

Parameters:

param (dict) – Set of iteration parameters.

Returns:

True if the parameters are valid, False otherwise.

Return type:

bool

is_valid(param)[source]

Check if the current set of iteration parameters is valid for this parameter value.

Parameters:

param (dict) – Set of iteration parameters.

Returns:

True if the value is valid, False otherwise.

Return type:

bool

class canopy_factory.utils.DictSet(members, **kwargs)[source]

Bases: DictWrapper

Container for chaining multiple dictionaries.

Parameters:
  • members (list) – Set of dictionaries that should be accessed in the order provided.

  • **kwargs – Additional keyword arguments are passed to the parent constructor.

append(member, **kwargs)[source]

Add a new member to the end of the set.

Parameters:
  • member (dict) – New member.

  • **kwargs – Additional keyword arguments are passed to coerce_member.

classmethod coerce_member(x, add_prefix=False, **kwargs)[source]

Coerce an object to a DictWrapper instance.

Parameters:
  • x (object) – Dictionary-like object.

  • add_prefix (str, optional) – Prefix that should be added to the keys in x.

  • **kwargs – Additional keyword arguments are passed to DictWrapper.coerce.

insert(idx, member, **kwargs)[source]

Add a new member to the set.

Parameters:
  • idx (index) – Index to insert the new member add.

  • member (dict) – New member.

  • **kwargs – Additional keyword arguments are passed to coerce_member.

property storage

Destination dictionary for added keys.

Type:

DictWrapper

temporary_prefix(prefix, per_member=False, **kwargs)[source]

Temporarily set a prefix for the dictionary with the context. When the context exits, any previous prefix will be restored and any added parameters will be maintained.

Parameters:
  • prefix (str) – Prefix to use within the context.

  • per_member (bool, optional) – If True, add prefixes on a member-by-member basis.

  • **kwargs – Additional keyword arguments are passed to temporary_prefix for each member if per_member is True, and the parent method otherwise.

Yields:

DictWrapper – View of the dictionary with the provided prefix.

class canopy_factory.utils.DictWrapper(logger=None, logger_prefix='')[source]

Bases: MutableMapping

Abstract base class for dictionary wrappers.

property added

Keys added to the dictionary.

Type:

set

classmethod assert_keys_match(x, keys0, logger=None)[source]
classmethod coerce(x, **kwargs)[source]

Coerce an object to be a DictWrapper compatible instance.

Parameters:
  • x (dict, DictWrapper, tuple, list) – Object that can be interpreted as a DictWrapper instance.

  • **kwargs – Additional keyword arguments are passed to the constructor for the interpreted instance.

Returns:

Coerced instance.

Return type:

DictWrapper

copy_src2dst(kdst, ksrc=<class 'canopy_factory.utils.NoDefault'>, overwrite=False)[source]

Copy a key/value pair from the source dictionary to the destination dictionary if it is present in the source dictionary and not present in the destination dictionary.

Parameters:
  • kdst (str) – Key that should be assigned to in the destination.

  • ksrc (str, optional) – Key that should be copyied from the source dictionary. If not provided, kdst is used.

  • overwrite (bool, optional) – If True, overwrite any existing value in the destination dictionary.

count_prefix(prefix, raw=False)[source]

Count the number of keys that start with a prefix.

Parameters:
  • prefix (str) – Prefix to count.

  • raw (bool, optional) – If True, the raw dictionary keys will be checked for the provided prefix.

property flattened

Flattened version of the members.

Type:

dict

items(raw=False)[source]

Wrapped dictionary items with prefixes removed from keys.

Parameters:

raw (bool, optional) – If True, the raw dictionary items will be returned without the prefix removed.

Returns:

Items view.

Return type:

dict_items

keys(raw=False, prefix=None)[source]

Wrapped dictionary keys with prefixes removed.

Parameters:
  • raw (bool, optional) – If True, the raw dictionary keys will be returned without the prefix removed.

  • prefix (str, optional) – If True, only return keys that start with this prefix.

Returns:

Keys view.

Return type:

dict_keys

property logger_prefix

Prefix for log messages.

Type:

str

property mutable

True if keys can be added to the dictionary.

Type:

bool

property raw_flattened

Copy of raw destination dictionary (with prefix)

Type:

dict

remove_cond(fcond)[source]

Remove key/value pairs from this dictionary based on the value of a provided function.

Parameters:

fcond (callable) – Function that takes a single raw key/value pair and returns True when the pair should be removed.

remove_prefix(prefix, **kwargs)[source]

Remove keys that start with the provided prefix.

Parameters:
  • prefix (str) – Prefix to remove keys with.

  • **kwargs – Additional keyword arguments are passed to remove_cond.

classmethod remove_prefixed_keys(x, prefix)[source]
property removed

Keys removed from the dictionary.

Type:

set

report_change(prefix='', suffix='', assert_no_change=False, **kwargs)[source]

Report on how the dictionary changed within the context.

Parameters:
  • prefix (str, optional) – Prefix for report message.

  • suffix (str, optional) – Suffix for report message.

  • assert_no_change (bool, optional) – If True, assert that the keys did not change.

  • **kwargs – Additional keyword arguments are passed to the keys method to get the set of keys before & after the context.

report_diff(keys0, keys1, prefix='', suffix='')[source]

Report on a difference between two key sets.

Parameters:
  • keys0 (set) – Set of keys from a prior state.

  • keys1 (set) – Set of keys from a state after keys0.

  • prefix (str, optional) – Prefix for report message.

  • suffix (str, optional) – Suffix for report message.

select_cond(fcond, transform=False, deepcopy=False)[source]

Create a new PrefixedDict instance that only includes key/value pairs selected by the provided function.

Parameters:
  • fcond (callable) – Selection function that takes a single key/value pair and returns True or False to indicate if the pair is selected.

  • transform (bool, callable, optional) – A function that should be used to transform raw keys for inclusion in the returned dictionary. If True, self._reverse_key will be used.

  • deepcopy (bool, optional) – If True, deepcopy values.

Returns:

Dictionary containing selected members.

Return type:

dict

classmethod select_keys(x, prefix='')[source]
select_prefix(prefix, strip=False, **kwargs)[source]

Create a new PrefixedDict instance that only includes keys that start with a given prefix.

Parameters:
  • prefix (str) – Prefix to filter on.

  • strip (bool, optional) – If True, the prefix should be stripped in the returned dictionary.

  • **kwargs – Additional keyword arguments are passed to select_cond.

Returns:

Dictionary containing selected members.

Return type:

dict

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D[source]
abstract property storage

Destination dictionary for added keys.

Type:

DictWrapper

strip_prefix(prefix, keys=None)[source]

Remove a prefix from keys in the dictionary.

Parameters:
  • prefix (str) – Prefix to strip.

  • keys (list, optional) – Set of keys to remove the prefix from. If not provided, all keys will be used and an error will be raised if any keys do not start with the prefix.

temporary_prefix(prefix, append=False, report_change=False)[source]

Temporarily set a prefix for the dictionary with the context. When the context exits, any previous prefix will be restored and any added parameters will be maintained.

Parameters:
  • prefix (str) – Prefix to use within the context.

  • append (bool, optional) – If True, the prefix should be appended to the end of the current prefix.

  • report_change (str, bool, optional) – If True, changes that occur in the context will be reported. If a string is provided, it will be used as a prefix for the log message.

Yields:

DictWrapper – View of the dictionary with the provided prefix.

update_missing(other)[source]

Update the dictionary only will values that are not present.

Parameters:

other (dict) – Values to update the dictionary with.

exception canopy_factory.utils.FilenameGenerationError[source]

Bases: BaseException

Error to raise when a file name cannot be generated.

exception canopy_factory.utils.ImmutableDictException[source]

Bases: BaseException

class canopy_factory.utils.NoDefault[source]

Bases: object

Stand-in for identifying if a default is passed.

class canopy_factory.utils.PrefixedDict(wrapped=None, prefix=None, **kwargs)[source]

Bases: SimpleWrapper

Dictionary wrapper that allows for adding a prefix to keys when accessing the wrapped dictionary.

Parameters:
  • wrapped (dict, optional) – Wrapped dictionary.

  • prefix (str, optional) – Prefix to add to keys.

  • **kwargs – Additional keyword arguments are passed to the parent constructor.

property logger_prefix

Prefix for log messages.

Type:

str

select_prefix(prefix=None, strip=False, **kwargs)[source]

Create a new PrefixedDict instance that only includes keys that start with a given prefix.

Parameters:
  • prefix (str, optional) – Prefix to filter on. If not provided, the prefix for the target will be used.

  • strip (bool, optional) – If True, the prefix should be stripped in the returned dictionary.

  • **kwargs – Additional keyword arguments are passed to the parent method.

Returns:

Dictionary containing selected members.

Return type:

PrefixedDict

temporary_prefix(prefix, append=False, report_change=False)[source]

Temporarily set a prefix for the dictionary with the context. When the context exits, any previous prefix will be restored and any added parameters will be maintained.

Parameters:
  • prefix (str) – Prefix to use within the context.

  • append (bool, optional) – If True, the prefix should be appended to the end of the current prefix.

  • report_change (str, bool, optional) – If True, changes that occur in the context will be reported. If a string is provided, it will be used as a prefix for the log message.

Yields:

DictWrapper – View of the dictionary with the provided prefix.

class canopy_factory.utils.QuantityArgument(default_units=None, named_choices=None)[source]

Bases: object

Wrapper for argument type that produces a quantity with the specified default units.

Parameters:
  • default_units (str, optional) – Units that should be added to the returned value if x does not have units or that x should be converted to if it has units.

  • named_choices (list, optional) – Set of string values that should also be allowed.

class canopy_factory.utils.RegisteredClassBase[source]

Bases: object

Base class for classes that should be registered.

calculating(name)[source]

Context for handling circular calculation dependencies.

Parameters:

name (str) – Name of the property being calculated.

check_calculating(name)[source]

Check if a variable is being calculated.

Parameters:

name (str) – Name of the property to check.

Returns:

True if the variable is being calculated.

Return type:

bool

clear_cached_properties(exclude=None, include=None, args=False)[source]

Clear the cached properties.

Parameters:
  • exclude (list, optional) – Set of cached properties that should be preserved.

  • include (list, optional) – Subset of cached properties that should be cleared.

  • args (bool, optional) – If true, only args cached properties should be cleared.

debug(message='', **kwargs)[source]

Set a pdb break point if debugging is active.

Parameters:
  • message (str, optional) – Log message to show before setting break point.

  • **kwargs – Additional keyword arguments are passed to the log method if it is called.

error(error_cls, message='', **kwargs)[source]

Raise an error, adding context to the message.

Parameters:
  • error_cls (type) – Error class.

  • message (str, optional) – Error message.

  • **kwargs – Additional keyword arguments are passed to log.

classmethod format_log(message='', prefix=None, border=False, source=None, exception=None)[source]

Format a log message.

Parameters:
  • message (str, optional) – Log message.

  • prefix (str, optional) – Prefix to use.

  • border (bool, optional) – If True, add a border before and after the message.

  • source (str, optional) – Source class that the message was emitted by.

  • exception (BaseException, optional) – Error that traceback should be reported for.

get_cached_properties(exclude=None, include=None)[source]

Get the set of cached properties.

Parameters:
  • exclude (list, optional) – Set of cached properties that should not be included in the returned dictionary.

  • include (list, optional) – Set of cached properties that should be included in the returned dictionary.

Returns:

Cached properties.

Return type:

dict

has_cached_property(k)[source]

Check if a cached property has been initialized.

Parameters:

k (str) – Name of the cached property to check.

Returns:

True if the cached property has been initialized.

Return type:

bool

log(message='', force=False, cls=None, **kwargs)[source]

Emit a log message.

Parameters:
  • message (str, optional) – Log message.

  • force (bool, optional) – If True, print the log message even if self.verbose is False.

  • **kwargs – Additional keyword arguments are passed to the log_class method.

classmethod log_class(message='', debug=False, **kwargs)[source]

Emit a log message.

Parameters:
  • message (str, optional) – Log message.

  • debug (bool, optional) – If True, set a Python debugger breakpoint after emitting the message.

  • **kwargs – Additional keyword arguments are passed to the format_log method.

Returns:

Log message.

Return type:

str

property log_prefix

Prefix to add to messages emitted by this instance.

Type:

str

pop_cached_properties(preserve=None, exclude=None, include=None, args=False)[source]

Clear the cached properties and return their values (before they are cleared).

Parameters:
  • preserve (list, optional) – Set of cached properties that should not be cleared.

  • exclude (list, optional) – Set of cached properties that should not be included in the returned dictionary.

  • include (list, optional) – Set of cached properties that should be included in the returned dictionary.

  • args (bool, optional) – If True, only args cached properties should be cleared.

Returns:

Cached properties.

Return type:

dict

reset_cached_properties(properties, preserve=None, args=False)[source]

Set cached properties after clearing the existing cache.

Parameters:
  • properties (dict) – Cached properties to update.

  • preserve (list, optional) – Set of cached properties that should not be cleared.

  • args (bool, optional) – If True, only args cached properties should be cleared.

set_cached_properties(properties)[source]

Set cached properties.

Parameters:

properties (dict) – Cached properties to update.

class canopy_factory.utils.RegisteredMetaClass(name, bases, class_dict)[source]

Bases: type

Metaclass for registering classes.

class canopy_factory.utils.SimpleWrapper(wrapped=None, immutable=False, ordered=False, **kwargs)[source]

Bases: DictWrapper

Dictionary wrapper that only allows certain keys.

Parameters:
  • wrapped (dict, optional) – Wrapped dictionary.

  • immutable (bool, optional) – If True, the dictionary should not be modified.

  • ordered (bool, optional) – If True and wrapped not provided, an OrderedDict will be used.

  • **kwargs – Additional keyword arguments are passed to the parent constructor.

append(member, add_prefix=False, **kwargs)[source]

Add a new member to the end of the set.

Parameters:
  • member (dict) – New member.

  • add_prefix (str, bool, optional) – Prefix that should be added to the keys in x. If True, the current prefix should be added.

  • **kwargs – Additional keyword arguments are passed to coerce_member.

insert(idx, member, add_prefix=False, **kwargs)[source]

Add a new member to the set.

Parameters:
  • idx (index) – Index to insert the new member add.

  • member (dict) – New member.

  • add_prefix (str, bool, optional) – Prefix that should be added to the keys in x. If True, the current prefix should be added.

  • **kwargs – Additional keyword arguments are passed to coerce_member.

property members

Members of the wrapped dictionary. Only valid if the wrapped dictionary is a DictSet.

Type:

list

move_to_end(key, last=True)[source]

Move a key to the end of a sorted ordered dictionary.

Parameters:
  • key (str) – Key to move.

  • last (bool, optional) – If True, move the key to the beginning instead of the end.

property storage

Destination dictionary for added keys.

Type:

DictWrapper

class canopy_factory.utils.SolarModel(latitude, longitude, time, altitude=None, pressure=None, temperature=12.0, eta_par=0.368, eta_photon=4.56, method_solar_position='nrel_numpy', method_airmass='kastenyoung1989', method_irradiance='ineichen')[source]

Bases: object

Solar model using pvlib. For quantities with units, values can be provided as floats (in which case the default units will be assumed) or units.Quantity instances.

Parameters:
  • latitude (float) – Location latitude (in degrees).

  • longitude (float) – Location latitude (in degrees).

  • time (datetime.datetime) – Time.

  • altitude (float, optional) – Altitude (in meters) used to compute solar position. If not provided, but pressure is, pressure will be used to calculate altitude.

  • pressure (float, optional) – Pressure (in Pa) used to compute solar position. If not provided, but altitude is, altitude will be used to calculate pressure.

  • temperature (float, optional) – Air temperature (in degrees C) used to compute solar position.

  • eta_par (float, optional) – Fraction of solar radiation (assuming black-body spectrum of 5800 K) that is photosynthetically active (wavelengths 400–700 nm).

  • eta_photon (float, optional) – Average number of photons per photosynthetically activate unit of radiation (in µmol s−1 W−1).

  • method_solar_position (str, optional) – Method that should be used by pvlib to determine the solar position.

  • method_airmass (str, optional) – Model that should be used by pvlib to determine the relative air mass.

  • method_irradiance (str, optional) – Model that should be used by pvlib to determine the solar irradiance.

property absolute_airmass

Absolute (pressure-adjusted) airmass.

Type:

float

property apparent_elevation

Apparent elevation of the sun.

Type:

units.Quantity

property azimuth

Azimuth angle of the sun.

Type:

units.Quantity

property dhi

Diffuse horizontal irradiance

Type:

units.Quantity

property dni

Direct normal irradiance

Type:

units.Quantity

property dni_extra

Extraterrestrial radiation incident on a surface normal to the sun (in W/m**2).

Type:

units.Quantity

property ghi

Global horizontal irradiance

Type:

units.Quantity

property irradiance

Solar irradiance.

Type:

pandas.DataFrame

classmethod is_solar_date(x)[source]

Check if a string is a named solar date.

Parameters:

x (str) – Time to check.

Returns:

True if x is a named solar date.

Return type:

bool

classmethod is_solar_time(x)[source]

Check if a string is a named solar time.

Parameters:

x (str) – Time to check.

Returns:

True if x is a named solar time.

Return type:

bool

property linke_turbidity

Linke Turibidity for the time/location.

Type:

float

property ppfd_diffuse

Diffuse photosynthetic photon flux density

Type:

units.Quantity

property ppfd_direct

Direct photosynthetic photon flux density

Type:

units.Quantity

property relative_airmass

Relative (not pressure-adjusted) airmass at sea level.

Type:

float

relative_direction(up, north)[source]

Get the direction from the scene to the sun.

Parameters:
  • up (np.ndarray) – Unit vector for up in the scene.

  • north (np.ndarray) – Unit vector for north in the scene.

Returns:

Unit vector from scene to sun.

Return type:

np.ndarray

solar_date(x, method='spa', date=None)[source]

Parse an input string as a solar date.

Parameters:
  • x (str) – Input string. Can be ‘summer_solstice’, ‘june_solstice’, ‘spring_equinox’, ‘march_equinox’, ‘winter_solstice’, ‘december_solstice’, ‘fall_equinox’, or ‘september_equinox’. For those values specifying seasons, the latitude will be used to determine the month when that season occurs.

  • method (str, optional) – Method that pvlib should use to determine the solar times.

  • date (datetime.datetime, optional) – Date from which the year and timezone should be taken.

Returns:

Date determined from solar position.

Return type:

datetime.datetime

property solar_position

Solar position information.

Type:

dict

solar_time(x, method='spa', horizon_buffer=5.0, date=None)[source]

Parse an input string as a solar time.

Parameters:
  • x (str) – Input string. Can be ‘sunrise’, ‘noon’, or ‘sunset’.

  • method (str, optional) – Method that pvlib should use to determine the solar times.

  • horizon_buffer (float, optional) – Time (in minutes) that should be added or subtracted to times when the sun is at the horizon.

  • date (datetime.datetime, optional) – Date on which the solar time should be computed.

Returns:

Time determined from solar position.

Return type:

datetime.datetime

exception canopy_factory.utils.SuffixGenerationError[source]

Bases: FilenameGenerationError

Error to raise when an argument cannot be converted into a suffix.

class canopy_factory.utils.UnitSet(**kwargs)[source]

Bases: object

Container for a unit set.

Parameters:
  • time (str, yggdrasil.units.Unit, optional) – Time unit.

  • length (str, yggdrasil.units.Unit, optional) – Length unit.

  • mass (str, yggdrasil.units.Unit, optional) – Mass unit.

  • angle (str, yggdrasil.units.Unit, optional) – Angle unit.

  • area (str, yggdrasil.units.Unit, optional) – Area unit. If not provided, this unit will be calculated from the other provided units.

  • density (str, yggdrasil.units.Unit, optional) – Density unit. If not provided, this unit will be calculated from the other provided units.

classmethod add_unit_arguments(dest, prefix, help_template=None, defaults=None)[source]
add_units(x, dimension)[source]

Add units to a quantity with the specified dimensionality.

Parameters:
  • x (units.QuantityArray) – Quantity with units.

  • dimension (str) – Dimensions of units that should be added.

Returns:

x converted to this unit system.

Return type:

units.QuantityArray

property area
as_dict(prefix='', suffix='', include_missing=False, as_strings=False)[source]

Get a dictionary of units in the set.

Parameters:
  • prefix (str, optional) – Prefix that should be added to units in the returned dictionary.

  • suffix (str, optional) – Suffix that should be added to units in the returned dictionary.

  • include_missing (bool, optional) – If True, include missing units in the returned dictionary as None.

  • as_strings (bool, optional) – If True, units in the output dictionary should be strings.

Returns:

Units dictionary.

Return type:

dict

convert(x, strip=False)[source]

Convert a quantity to this unit system.

Parameters:
  • x (units.QuantityArray) – Quantity with units.

  • strip (bool, optional) – If True, return a float version with the units stripped.

Returns:

x converted to this unit system.

Return type:

units.QuantityArray

property density
property dimensions
classmethod from_attr(inst, prefix='', suffix='')[source]

Create the class by extracting units from attributes of the provided instance.

Parameters:
  • inst (object) – Instance whose attributes should be checked for units.

  • prefix (str, optional) – Prefix that should be added to units when search kwargs.

  • suffix (str, optional) – Suffix that should be added to units when search kwargs.

Returns:

New unit set.

Return type:

UnitSet

classmethod from_kwargs(kwargs, prefix='', suffix='', pop=False)[source]

Create the class by extracting units from the provided kwargs.

Parameters:
  • kwargs (dict) – Dictionary that should be searched for units.

  • prefix (str, optional) – Prefix that should be added to units when search kwargs.

  • suffix (str, optional) – Suffix that should be added to units when search kwargs.

  • pop (bool, optional) – If True, units should be removed from kwargs if they are used to create the class.

Returns:

New unit set.

Return type:

UnitSet

property units
canopy_factory.utils.apply_color_map(values, color_map=None, vmin=None, vmax=None, scaling='linear', highlight=None, highlight_color=(255, 0, 255), mask_invalid=False, include_alpha=False)[source]

Apply a color map to a set of scalar.

Parameters:
  • values (arr) – Scalar values that should be mapped to colors for each face.

  • color_map (str, optional) – The name of the color map that should be used. Defaults to ‘plasma’.

  • vmin (float, optional) – Value that should map to the minimum of the colormap. Defaults to min(values).

  • vmax (float, optional) – Value that should map to the maximum of the colormap. Defaults to max(values).

  • scaling (str, optional) – Scaling that should be used to map the scalar array onto the colormap. Defaults to ‘linear’.

  • highlight (int, optional) – Index of a value that should be highlighted.

  • highlight_color (tuple, optional) – RGB values for color that should be used for the highlighted value.

  • mask_invalid (bool, optional) – If True, mask invalid values (e.g. values that are <= 0 for scaling == ‘log’),

  • include_alpha (bool, optional) – If True, include the alpha channel in the returned array.

Returns:

RGB colors for each scalar in the provided array.

Return type:

np.ndarray

canopy_factory.utils.cached_args_property(method)[source]

Cached property decorator that should be reset when arguments are modified.

Parameters:

method (function) – Method who’s output should be cached.

Returns:

Decorated method.

Return type:

function

canopy_factory.utils.cached_factory_property(classname)[source]

Cached property decorator for inside a class factory.

Parameters:

classname (str) – Unique name that should be used to register the property for the factory produced class.

Returns:

Decorator for method.

Return type:

function

canopy_factory.utils.cached_property(method, args=None, classname=None)[source]

Cached property decorator.

Parameters:
  • method (function) – Method who’s output should be cached.

  • args (bool, optional) – If True, the property will be reset when the args for the class are updated.

  • classname (str, optional) – Unique name that should be used to register the property in place of the classname from the method’s __qualname__.

Returns:

Decorated method.

Return type:

function

canopy_factory.utils.correct_obj_color(fname, verbose=False)[source]

Convert colors to be floats rather than integers.

Parameters:
  • fname (str) – Name of the file that should be corrected.

  • verbose (bool, optional) – If True, print log messages when the file does not need to be converted.

canopy_factory.utils.create_organ_symbol(name, fname, scale=None)[source]

Read a 3D geometry for an organ from a file.

Parameters:
  • name (str) – Name of the organ described by the 3D geometry.

  • fname (str) – Path to 3D geometry file that should be loaded. The file type is determined by inspecting the file extension.

  • scale (str, float, optional) – Scaling that should be applied when loading the 3D geometry. If ‘max’ is provided, the geometry will be scaled such that it’s maximum width along the x, y, or z axis is 1.0. If ‘min’ is provided the geometry will be scaled such that it’s minimum width along the x, y, or z axis is 1.0.

Returns:

Geometry.

Return type:

PlantGL.FaceSet

canopy_factory.utils.format_list_for_help(vals, sep=', ')[source]

Format a list in a help friendly way.

Parameters:
  • vals (list) – Values to format.

  • sep (str, optional) – Separator to use.

Returns:

Formatted list.

Return type:

str

canopy_factory.utils.generate_filename(basefile, ext=None, prefix=None, suffix=None, directory=None)[source]

Generate a filename using the base name from another file.

Parameters:
  • basefile (str) – Base file name that new file should be based on.

  • ext (str, optional) – File extension that should be used for the generated file name.

  • prefix (str, optional) – Prefix that should be added to the base file name in the generated file name.

  • suffix (str, optional) – Suffix that should be added to the base file name in the generated file name.

  • directory (str, optional) – Directory that the generated file name should be in if different than the base file name.

Returns:

New file name.

Return type:

str

canopy_factory.utils.get_3D_format(fname, dont_raise=False)[source]

Determine the format of a 3D geometry file by inspecting the extension of a file.

Parameters:
  • fname (str) – Filename to inspect.

  • dont_raise (bool, optional) – If True, don’t raise an error if the format cannot be determined.

Returns:

Name of the format that the extension indicates.

Return type:

str

Raises:

ValueError – If the format cannot be determined and dont_raise is False.

canopy_factory.utils.get_class_registry()[source]
canopy_factory.utils.get_mesh_dict(x)[source]

Convert a ObjDict/PlyDict instance to a dictionary.

Parameters:

x (ObjDict, PlyDict) – Mesh to convert.

Returns:

Mapping between face/vertices and arrays.

Return type:

dict

canopy_factory.utils.get_periodic_shifts(period, direction, count, include_origin=False, dont_reflect=False, dont_center=False)[source]

Get the shifts that should be applied to plants.

Parameters:
  • period (np.ndarray) – Length of the period along each direction.

  • direction (np.ndarray) – Unit vector for the directions along which the period should be applied.

  • count (np.ndarray) – Number of times the period should be repeated in each direction.

  • include_origin (bool, optional) – If True, include the origin in the returned shifts.

  • dont_reflect (bool, optional) – If True, the shifts will only occur in the positive direction along each axis.

  • dont_center (bool, optional) – If True, this shifts will not be centered on the origin.

Returns:

Shifts in each coordinate that should be applied.

Return type:

np.ndarray

canopy_factory.utils.input_yes_or_no(question, default=True)[source]

Ask for user response to a yes or no question.

Parameters:
  • question (str) – Question to ask.

  • default (bool, optional) – If True, the default response will be True if no input is provided.

Returns:

True if the user responds in the affirmative.

Return type:

bool

canopy_factory.utils.is_date(x)[source]

Check if datetime instance is purely a date without time information.

Parameters:

x (datetime.datetime) – Datetime instance to check.

Returns:

True if x is purely a date.

Return type:

bool

canopy_factory.utils.jsonschema2argument(json, no_defaults=False)[source]

Contruct a argparser argument from a jsonschema description.

Parameters:
  • json (dict) – JSON schema.

  • no_defaults (bool, optional) – If True, don’t include defaults.

Returns:

Keyword arguments for adding an argument to an argument

parser.

Return type:

dict

canopy_factory.utils.parse_axis(x)[source]

Parse an input string containing an axis tuple.

Parameters:

x (str) – Input string.

Returns:

Axis vector.

Return type:

np.ndarray

canopy_factory.utils.parse_color(x, convert_names=False)[source]

Parse an input string containing a color tuple.

Parameters:
  • x (str) – Input string.

  • convert_names (bool, optional) – If True, color names (e.g. ‘green’) will be converted to their tuple version.

Returns:

Color tuple.

Return type:

tuple

canopy_factory.utils.parse_datetime(x)[source]

Parse an input that is a datetime.datetime object or a string representation of a datetime.datetime object that can be parsed via datetime.fromisoformat.

Parameters:

x (str) – String containing datetime.

Returns:

Date time.

Return type:

datetime.datetime

canopy_factory.utils.parse_existing_file(x)[source]

Parse an existing file.

Parameters:

x (str) – String containing the path to an existing file.

Returns:

File name.

Return type:

str

canopy_factory.utils.parse_quantity(x, default_units=None)[source]

Parse a quanity with units.

Parameters:
  • x (str, float, units.Quantity) – Quantity value with or without units.

  • default_units (str, optional) – Units that should be added to the returned value if x does not have units or that x should be converted to if it has units.

Returns:

Value with units.

Return type:

units.Quantity

canopy_factory.utils.parse_solar_date(x)[source]

Parse an input for a doy allowing for name-based times.

Parameters:

x (str) – String containing doy.

Returns:

Day of year.

Return type:

int, str

canopy_factory.utils.parse_solar_time(x)[source]

Parse an input for an hour allowing for name-based times.

Parameters:

x (str) – String containing hour.

Returns:

Hour.

Return type:

int, str

canopy_factory.utils.parse_units(x)[source]

Parse a units string.

Parameters:

x (str) – String containing units.

Returns:

Units instance.

Return type:

units.Units

canopy_factory.utils.project_onto_ground(pos, xaxis, yaxis, ray=False)[source]

Project a 3D point onto the ground.

Parameters:
  • pos (np.ndarray) – Set of one or more 3D positions.

  • xaxis (np.ndarray) – Unit vector for the x axis.

  • yaxis (np.ndarray) – Unit vector for the y axis.

  • ray (bool, optional) – If True, treat pos as a ray and normalize the returned projection.

Returns:

x & y components of pos projected onto the

scene ground.

Return type:

np.ndarray

canopy_factory.utils.prune_empty_faces(mesh, area_min=None)[source]

Remove faces with very small areas from a mesh.

Parameters:
  • mesh (ObjDict) – Mesh.

  • area_min (float, optional) – Minimum area that should be allowed. If not provided the resolution of np.float32 will be used.

Returns:

Mesh with the empty faces removed.

Return type:

ObjDict

canopy_factory.utils.quantity2timedelta(x)[source]

Convert a quantity to a datetime timedelta difference.

Parameters:

x (units.Quantity) – Quantity with time units.

Returns:

Time difference.

Return type:

datetime.timedelta

canopy_factory.utils.read_3D(fname, file_format=None, file_units=None, mesh_units=None, scale=1.0, verbose=False)[source]

Read data from a 3D geometry file.

Parameters:
  • fname (str) – Path to 3D geometry file that should be loaded. The file type is determined by inspecting the file extension.

  • file_format (str, optional) – The format that the geometry is in. If not provided, the format will be determined by inspecting the file extension.

  • file_units (str, optional) – Units that the mesh in the file is in.

  • mesh_units (str, optional) – Units that the returned mesh should be in.

  • scale (float, optional) – Scale factor that should be applied.

  • verbose (bool, optional) – If True, log messages will be emitted.

Returns:

3D geometry mesh.

Return type:

ObjDict, PlyDict

Raises:

RuntimeErrror – If the file does not exist.

canopy_factory.utils.read_csv(fname, select=None, verbose=False, include_units=True)[source]

Read data from a CSV file.

Parameters:
  • fname (str) – Path to file that should be read.

  • select (str, list, optional) – One or more fields that should be selected.

  • verbose (bool, optional) – If True, log messages will be emitted.

  • include_units (bool, optional) – If True, units contained in the header names will be added to the returned columns.

Returns:

CSV contents with colums as key/value pairs.

Return type:

dict

canopy_factory.utils.read_locations(fname=None, verbose=False)[source]

Read location data from a CSV file.

Parameters:
  • fname (str, optional) – Path to file containing location data. If not provided cfg[‘files’][‘locations’] will be used.

  • verbose (bool, optional) – If True, log messages will be emitted.

Returns:

Mapping between location name and location parameters.

Return type:

dict

canopy_factory.utils.read_png(fname, verbose=False)[source]

Read image data from a PNG file.

Parameters:
  • fname (str) – Path to file the image should be read from.

  • verbose (bool, optional) – If True, log messages will be emitted.

Returns:

Image data.

Return type:

np.ndarray

canopy_factory.utils.readonly_cached_args_property(method)[source]

Read-only cached property decorator.

Parameters:

method (function) – Method who’s output should be cached.

Returns:

Decorated method.

Return type:

function

canopy_factory.utils.readonly_cached_property(method, args=None, **kwargs)[source]

Read-only cached property decorator.

Parameters:
  • method (function) – Method who’s output should be cached.

  • args (bool, optional) – If True, the property will be reset when the args for the class are updated.

  • **kwargs – Additional keyword arguments are passed to _class_registry.register_cached_property.

Returns:

Decorated method.

Return type:

function

canopy_factory.utils.rotate_axes(axis_x=None, axis_y=None, axis_z=None, check=False)[source]

Get the rotation matrix for going from the standard axes set to another. At least two input axes are required.

Parameters:
  • axis_x (np.ndarray, optional) – New x-axis after rotation.

  • axis_y (np.ndarray, optional) – New y-axis after rotation.

  • axis_z (np.ndarray, optional) – New z-axis after rotation.

  • check (bool, optional) – If True, the rotation matrix should be checked that it produces the desired result.

Returns:

3D rotation matrix.

Return type:

np.ndarray

canopy_factory.utils.rotation_matrix(theta, u)[source]

Get the rotation matrix necessary to rotate a 3D point around a unit vector by a specified angle.

Parameters:
  • theta (float) – Angle to rotate by (in radians).

  • u (array) – Vector to rotate around.

Returns

np.ndarray: Rotation matrix.

canopy_factory.utils.safe_op(method, x, value_on_empty=<class 'canopy_factory.utils.NoDefault'>, **kwargs)[source]

Compute an operation, safely taking units and empty lists/arrays into account.

Parameters:
  • method (callable) – Operation to apply.

  • x (list, np.array, units.QuantityArray) – Values to perform operation on.

  • value_on_empty (float, optional) – Value to return if x is empty.

  • **kwargs – Additional keyword arguments are passed to the method.

Returns:

Result w/ units if x has units.

Return type:

object

canopy_factory.utils.scale_factor(from_units=None, to_units=None)[source]

Get a scale factor for going from one set of units to another.

Parameters:
  • from_units (str, optional) – Starting units.

  • to_units (str, optional) – Ending units.

Returns:

Scale factor.

Return type:

float

canopy_factory.utils.scale_mesh(mesh, scale, from_units=None, to_units=None)[source]

Scale a 3D mesh.

Parameters:
  • mesh (ObjDict) – Mesh to shift.

  • scale (float) – Scale factor.

  • from_units (str, optional) – Units that mesh is currently in.

  • to_units (str, optional) – Units that the mesh should be converted to.

Returns:

Scaled mesh.

Return type:

ObjDict

canopy_factory.utils.scene2geom(scene, cls, d=None, verbose=False, colormap=None, components=None, **kwargs)[source]

Convert a PlantGL scene to a 3D geometry mesh.

Parameters:
  • scene (plantgl.Scene) – Scene to convert.

  • cls (type, str) – Name of the type of mesh that should be returned or the dictionary class that should be created.

  • d (plantgl.Tesselator, optional) – PlantGL discretizer.

  • verbose (bool, optional) – If True, display log messages about tasks.

  • colormap (str, dict, optional) – Name of matplotlib colormap or a dictionary mapping IDs to colors for each scene ID.

  • components (dict, optional) – Dictionary that component face face ranges should be added to.

  • **kwargs – Additional keyword arguments are passed to shape2dict for each shape in the scene.

Returns:

3D geometry mesh for the scene.

Return type:

cls

canopy_factory.utils.shape2dict(shape, d=None, conversion=1.0, as_obj=False, color=None, verbose=False, axis_up=array([0., 0., 1.]), axis_x=array([1., 0., 0.]))[source]

Convert a PlantGL shape to a 3D geometry dictionary.

Parameters:
  • shape (plantgl.Shape) – Shape to convert.

  • d (plantgl.Tesselator, optional) – PlantGL discretizer.

  • conversion (float, optional) – Conversion that should be applied to the returned geometry.

  • as_obj (bool, optional) – If True, the returned dictionary should be compatible with ObjWavefront meshes.

  • color (tuple, optional) – RGB values that should be applied to each vertex in the shape if the shape does not have colors.

  • verbose (bool, optional) – If True, display log messages about tasks.

  • axis_up (np.ndarray, optional) – Direction that should be considered “up” for the shape. The generated positions will be rotated to satisfy this and axis_x.

  • axis_x (np.ndarray, optional) – Direction that x coordinates in the shape should be mapped to. The generated positions will be rotated to satisfy this and axis_up.

Returns:

Dictionary of 3D geometry components.

Return type:

dict

canopy_factory.utils.shift_mesh(mesh, x, y, axis_up=array([0., 0., 1.]), axis_x=array([1., 0., 0.]), plantids_in_blue=False, plantid=None)[source]

Shift a 3D mesh.

Parameters:
  • mesh (ObjDict) – Mesh to shift.

  • x (float) – Amount to shift the plant in the x direction.

  • y (float) – Amount to shift the plant in the y direction.

  • axis_up (np.ndarray, optional) – Direction that should be considered “up” for the mesh. The shifts will be performed perpendicular to this direction.

  • axis_x (np.ndarray, optional) – Direction that shifts in the x direction should be performed. The y axis will be determined from the cross product of axis_up & axis_x.

  • plantids_in_blue (bool, optional) – If True, plant IDs are stored in the blue color channel for the vertices and should be shifted.

  • plantid (int, optional) – Amount that colors should be shifted in the blue channel to account for plant ID.

Returns:

Shifted mesh.

Return type:

ObjDict

canopy_factory.utils.temporary_prefix(x, prefix, **kwargs)[source]

Create a wrapper around a dictionary with a temporary prefix that should be added when accessing dictionary elements.

Parameters:
  • x (dict, DictWrapper) – Dictionary to wrap with a prefix.

  • prefix (str) – Prefix to use within the context.

  • **kwargs – Additional keyword arguments are passed to the temporary_prefix PrefixedDict method.

Yields:

PrefixedDict – Dictionary with prefix wrapper.

canopy_factory.utils.timedelta2quantity(x)[source]

Convert a datetime.timedelta instance into a quantity.

Parameters:

x (datetime.timedelta) – Time difference.

Returns:

Quantity with time units.

Return type:

units.Quantity

canopy_factory.utils.to_date(x)[source]

Convert a datetime instance to a form that is purely a date.

Parameters:

x (datetime.datetime) – Datetime instance to convert.

Returns:

Version with time information removed.

Return type:

datetime.datetime

canopy_factory.utils.verify_3D_format(fname, file_format)[source]

Check a 3D geometry files extension against a file_format.

Parameters:
  • fname (str) – Filename to inspect.

  • file_format (str) – 3D geometry format to check against.

canopy_factory.utils.write_3D(mesh, fname, file_format=None, dont_correct_color=False, mesh_units=None, file_units=None, scale=1.0, verbose=False)[source]

Write data to a 3D geometry file.

Parameters:
  • mesh (ObjDict, PlyDict) – 3D geometry mesh.

  • fname (str) – Path to file where the geometry should be saved.

  • file_format (str, optional) – Name of the format that the file should be in. If not provided, the format will be determined from the file extension.

  • dont_correct_color (str, optional) – If True, dont correct the vertex colors from [0, 255] integers to [0.0, 1.0] floats.

  • mesh_units (str, optional) – Units that mesh vertices are in.

  • file_units (str, optional) – Units that the mesh should be written in.

  • scale (float, optional) – Scale factor that should be applied.

  • verbose (bool, optional) – If True, log messages will be emitted.

canopy_factory.utils.write_csv(data, fname, verbose=False, comments=None)[source]

Write columns to a CSV file.

Parameters:
  • data (dict) – Table columns.

  • fname (str) – Path to file where the CSV should be saved.

  • verbose (bool, optional) – If True, log messages will be emitted.

  • comments (list, optional) – Comments to add at the beginning of the file.

canopy_factory.utils.write_movie(frames, fname, frame_rate=1, verbose=False)[source]

Create a movie from a list of frames.

Parameters:
  • frames (list) – List of image frames.

  • fname (str) – Name of file to write to.

  • frame_rate (int, optional) – Frame rate in frames per second.

  • verbose (bool, optional) – If True, log messages will be emitted.

canopy_factory.utils.write_png(data, fname, fmt=None, verbose=False)[source]

Write image data to a file in PNG format.

Parameters:
  • data (np.ndarray) – Image data.

  • fname (str) – Path to file where the image should be saved.

  • verbose (bool, optional) – If True, log messages will be emitted.

canopy_factory.utils.xy_axes(upaxis, verbose=False)[source]

Determine the x & y axes from the up axis.

Parameters:
  • upaxis (str, int) – Name or index of the up axis.

  • verbose (bool, optional) – If True, print information about the transformation.

Returns:

Indices of x & y axes.

Return type:

tuple(2)

Module contents