API¶
This part of the documentation lists the full API reference of all public classes and functions.
Decorators¶
-
click.
command
(name=None, cls=None, **attrs)¶ Creates a new
Command
and uses the decorated function as callback. This will also automatically attach all decoratedoption()
s andargument()
s as parameters to the command.The name of the command defaults to the name of the function. If you want to change that, you can pass the intended name as the first argument.
All keyword arguments are forwarded to the underlying command class.
Once decorated the function turns into a
Command
instance that can be invoked as a command line utility or be attached to a commandGroup
.Parameters: - name – the name of the command. This defaults to the function name.
- cls – the command class to instantiate. This defaults to
Command
.
-
click.
group
(name=None, **attrs)¶ Creates a new
Group
with a function as callback. This works otherwise the same ascommand()
just that the cls parameter is set toGroup
.
-
click.
argument
(*param_decls, **attrs)¶ Attaches an argument to the command. All positional arguments are passed as parameter declarations to
Argument
; all keyword arguments are forwarded unchanged (exceptcls
). This is equivalent to creating anArgument
instance manually and attaching it to theCommand.params
list.Parameters: cls – the argument class to instantiate. This defaults to Argument
.
-
click.
option
(*param_decls, **attrs)¶ Attaches an option to the command. All positional arguments are passed as parameter declarations to
Option
; all keyword arguments are forwarded unchanged (exceptcls
). This is equivalent to creating anOption
instance manually and attaching it to theCommand.params
list.Parameters: cls – the option class to instantiate. This defaults to Option
.
-
click.
password_option
(*param_decls, **attrs)¶ Shortcut for password prompts.
This is equivalent to decorating a function with
option()
with the following parameters:@click.command() @click.option('--password', prompt=True, confirmation_prompt=True, hide_input=True) def changeadmin(password): pass
-
click.
confirmation_option
(*param_decls, **attrs)¶ Shortcut for confirmation prompts that can be ignored by passing
--yes
as parameter.This is equivalent to decorating a function with
option()
with the following parameters:def callback(ctx, param, value): if not value: ctx.abort() @click.command() @click.option('--yes', is_flag=True, callback=callback, expose_value=False, prompt='Do you want to continue?') def dropdb(): pass
-
click.
version_option
(version=None, *param_decls, **attrs)¶ Adds a
--version
option which immediately ends the program printing out the version number. This is implemented as an eager option that prints the version and exits the program in the callback.Parameters: - version – the version number to show. If not provided Click attempts an auto discovery via setuptools.
- prog_name – the name of the program (defaults to autodetection)
- message – custom message to show instead of the default
(
'%(prog)s, version %(version)s'
) - others – everything else is forwarded to
option()
.
-
click.
help_option
(*param_decls, **attrs)¶ Adds a
--help
option which immediately ends the program printing out the help page. This is usually unnecessary to add as this is added by default to all commands unless suppressed.Like
version_option()
, this is implemented as eager option that prints in the callback and exits.All arguments are forwarded to
option()
.
-
click.
pass_context
(f)¶ Marks a callback as wanting to receive the current context object as first argument.
-
click.
pass_obj
(f)¶ Similar to
pass_context()
, but only pass the object on the context onwards (Context.obj
). This is useful if that object represents the state of a nested system.
-
click.
make_pass_decorator
(object_type, ensure=False)¶ Given an object type this creates a decorator that will work similar to
pass_obj()
but instead of passing the object of the current context, it will find the innermost context of typeobject_type()
.This generates a decorator that works roughly like this:
from functools import update_wrapper def decorator(f): @pass_context def new_func(ctx, *args, **kwargs): obj = ctx.find_object(object_type) return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) return decorator
Parameters: - object_type – the type of the object to pass.
- ensure – if set to True, a new object will be created and remembered on the context if it’s not there yet.
Utilities¶
-
click.
echo
(message=None, file=None, nl=True, err=False, color=None)¶ Prints a message plus a newline to the given file or stdout. On first sight, this looks like the print function, but it has improved support for handling Unicode and binary data that does not fail no matter how badly configured the system is.
Primarily it means that you can print binary data as well as Unicode data on both 2.x and 3.x to the given file in the most appropriate way possible. This is a very carefree function as in that it will try its best to not fail.
In addition to that, if colorama is installed, the echo function will also support clever handling of ANSI codes. Essentially it will then do the following:
- add transparent handling of ANSI color codes on Windows.
- hide ANSI codes automatically if the destination file is not a terminal.
Changed in version 2.0: Starting with version 2.0 of Click, the echo function will work with colorama if it’s installed.
New in version 3.0: The err parameter was added.
Changed in version 4.0: Added the color flag.
Parameters: - message – the message to print
- file – the file to write to (defaults to
stdout
) - err – if set to true the file defaults to
stderr
instead ofstdout
. This is faster and easier than callingget_text_stderr()
yourself. - nl – if set to True (the default) a newline is printed afterwards.
- color – controls if the terminal supports ANSI colors or not. The default is autodetection.
-
click.
echo_via_pager
(text, color=None)¶ This function takes a text and shows it via an environment specific pager on stdout.
Changed in version 3.0: Added the color flag.
Parameters: - text – the text to page.
- color – controls if the pager supports ANSI colors or not. The default is autodetection.
-
click.
prompt
(text, default=None, hide_input=False, confirmation_prompt=False, type=None, value_proc=None, prompt_suffix=': ', show_default=True, err=False)¶ Prompts a user for input. This is a convenience function that can be used to prompt a user for input later.
If the user aborts the input by sending a interrupt signal, this function will catch it and raise a
Abort
exception.New in version 4.0: Added the err parameter.
Parameters: - text – the text to show for the prompt.
- default – the default value to use if no input happens. If this is not given it will prompt until it’s aborted.
- hide_input – if this is set to true then the input value will be hidden.
- confirmation_prompt – asks for confirmation for the value.
- type – the type to use to check the value against.
- value_proc – if this parameter is provided it’s a function that is invoked instead of the type conversion to convert a value.
- prompt_suffix – a suffix that should be added to the prompt.
- show_default – shows or hides the default value in the prompt.
- err – if set to true the file defaults to
stderr
instead ofstdout
, the same as with echo.
-
click.
confirm
(text, default=False, abort=False, prompt_suffix=': ', show_default=True, err=False)¶ Prompts for confirmation (yes/no question).
If the user aborts the input by sending a interrupt signal this function will catch it and raise a
Abort
exception.New in version 4.0: Added the err parameter.
Parameters: - text – the question to ask.
- default – the default for the prompt.
- abort – if this is set to True a negative answer aborts the
exception by raising
Abort
. - prompt_suffix – a suffix that should be added to the prompt.
- show_default – shows or hides the default value in the prompt.
- err – if set to true the file defaults to
stderr
instead ofstdout
, the same as with echo.
-
click.
progressbar
(iterable=None, length=None, label=None, show_eta=True, show_percent=None, show_pos=False, item_show_func=None, fill_char='#', empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s', info_sep=' ', width=36, file=None, color=None)¶ This function creates an iterable context manager that can be used to iterate over something while showing a progress bar. It will either iterate over the iterable or length items (that are counted up). While iteration happens, this function will print a rendered progress bar to the given file (defaults to stdout) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal.
The context manager creates the progress bar. When the context manager is entered the progress bar is already displayed. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen.
No printing must happen or the progress bar will be unintentionally destroyed.
Example usage:
with progressbar(items) as bar: for item in bar: do_something_with(item)
Alternatively, if no iterable is specified, one can manually update the progress bar through the update() method instead of directly iterating over the progress bar. The update method accepts the number of steps to increment the bar with:
with progressbar(length=chunks.total_bytes) as bar: for chunk in chunks: process_chunk(chunk) bar.update(chunks.bytes)
New in version 2.0.
New in version 4.0: Added the color parameter. Added a update method to the progressbar object.
Parameters: - iterable – an iterable to iterate over. If not provided the length is required.
- length – the number of items to iterate over. By default the progressbar will attempt to ask the iterator about its length, which might or might not work. If an iterable is also provided this parameter can be used to override the length. If an iterable is not provided the progress bar will iterate over a range of that length.
- label – the label to show next to the progress bar.
- show_eta – enables or disables the estimated time display. This is automatically disabled if the length cannot be determined.
- show_percent – enables or disables the percentage display. The default is True if the iterable has a length or False if not.
- show_pos – enables or disables the absolute position display. The default is False.
- item_show_func – a function called with the current item which can return a string to show the current item next to the progress bar. Note that the current item can be None!
- fill_char – the character to use to show the filled part of the progress bar.
- empty_char – the character to use to show the non-filled part of the progress bar.
- bar_template – the format string to use as template for the bar.
The parameters in it are
label
for the label,bar
for the progress bar andinfo
for the info section. - info_sep – the separator between multiple info items (eta etc.)
- width – the width of the progress bar in characters, 0 means full terminal width
- file – the file to write to. If this is not a terminal then only the label is printed.
- color – controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are included anywhere in the progress bar output which is not the case by default.
-
click.
clear
()¶ Clears the terminal screen. This will have the effect of clearing the whole visible space of the terminal and moving the cursor to the top left. This does not do anything if not connected to a terminal.
New in version 2.0.
-
click.
style
(text, fg=None, bg=None, bold=None, dim=None, underline=None, blink=None, reverse=None, reset=True)¶ Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing
reset=False
.Examples:
click.echo(click.style('Hello World!', fg='green')) click.echo(click.style('ATTENTION!', blink=True)) click.echo(click.style('Some things', reverse=True, fg='cyan'))
Supported color names:
black
(might be a gray)red
green
yellow
(might be an orange)blue
magenta
cyan
white
(might be light gray)reset
(reset the color code only)
New in version 2.0.
Parameters: - text – the string to style with ansi codes.
- fg – if provided this will become the foreground color.
- bg – if provided this will become the background color.
- bold – if provided this will enable or disable bold mode.
- dim – if provided this will enable or disable dim mode. This is badly supported.
- underline – if provided this will enable or disable underline.
- blink – if provided this will enable or disable blinking.
- reverse – if provided this will enable or disable inverse rendering (foreground becomes background and the other way round).
- reset – by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.
-
click.
unstyle
(text)¶ Removes ANSI styling information from a string. Usually it’s not necessary to use this function as Click’s echo function will automatically remove styling if necessary.
New in version 2.0.
Parameters: text – the text to remove style information from.
-
click.
secho
(text, file=None, nl=True, err=False, color=None, **styles)¶ This function combines
echo()
andstyle()
into one call. As such the following two calls are the same:click.secho('Hello World!', fg='green') click.echo(click.style('Hello World!', fg='green'))
All keyword arguments are forwarded to the underlying functions depending on which one they go with.
New in version 2.0.
-
click.
edit
(text=None, editor=None, env=None, require_save=True, extension='.txt', filename=None)¶ Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, None is returned. In case a file is edited directly the return value is always None and require_save and extension are ignored.
If the editor cannot be opened a
UsageError
is raised.Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have
\n
as newline markers.Parameters: - text – the text to edit.
- editor – optionally the editor to use. Defaults to automatic detection.
- env – environment variables to forward to the editor.
- require_save – if this is true, then not saving in the editor will make the return value become None.
- extension – the extension to tell the editor about. This defaults to .txt but changing this might change syntax highlighting.
- filename – if provided it will edit this file instead of the provided text contents. It will not use a temporary file as an indirection in that case.
-
click.
launch
(url, wait=False, locate=False)¶ This function launches the given URL (or filename) in the default viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually,
0
indicates success.Examples:
click.launch('http://click.pocoo.org/') click.launch('/my/downloaded/file', locate=True)
New in version 2.0.
Parameters: - url – URL or filename of the thing to launch.
- wait – waits for the program to stop.
- locate – if this is set to True then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem.
-
click.
getchar
(echo=False)¶ Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in the terminal buffer or standard input was not actually a terminal.
Note that this will always read from the terminal, even if something is piped into the standard input.
New in version 2.0.
Parameters: echo – if set to True, the character read will also show up on the terminal. The default is to not show it.
-
click.
pause
(info='Press any key to continue ...', err=False)¶ This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch “pause” command. If the program is not run through a terminal, this command will instead do nothing.
New in version 2.0.
New in version 4.0: Added the err parameter.
Parameters: - info – the info string to print before pausing.
- err – if set to message goes to
stderr
instead ofstdout
, the same as with echo.
-
click.
get_terminal_size
()¶ Returns the current size of the terminal as tuple in the form
(width, height)
in columns and rows.
-
click.
get_binary_stream
(name)¶ Returns a system stream for byte processing. This essentially returns the stream from the sys module with the given name but it solves some compatibility issues between different Python versions. Primarily this function is necessary for getting binary streams on Python 3.
Parameters: name – the name of the stream to open. Valid names are 'stdin'
,'stdout'
and'stderr'
-
click.
get_text_stream
(name, encoding=None, errors='strict')¶ Returns a system stream for text processing. This usually returns a wrapped stream around a binary stream returned from
get_binary_stream()
but it also can take shortcuts on Python 3 for already correctly configured streams.Parameters: - name – the name of the stream to open. Valid names are
'stdin'
,'stdout'
and'stderr'
- encoding – overrides the detected default encoding.
- errors – overrides the default error mode.
- name – the name of the stream to open. Valid names are
-
click.
open_file
(filename, mode='r', encoding=None, errors='strict', lazy=False, atomic=False)¶ This is similar to how the
File
works but for manual usage. Files are opened non lazy by default. This can open regular files as well as stdin/stdout if'-'
is passed.If stdin/stdout is returned the stream is wrapped so that the context manager will not close the stream accidentally. This makes it possible to always use the function like this without having to worry to accidentally close a standard stream:
with open_file(filename) as f: ...
New in version 3.0.
Parameters: - filename – the name of the file to open (or
'-'
for stdin/stdout). - mode – the mode in which to open the file.
- encoding – the encoding to use.
- errors – the error handling for this file.
- lazy – can be flipped to true to open the file lazily.
- atomic – in atomic mode writes go into a temporary file and it’s moved on close.
- filename – the name of the file to open (or
-
click.
get_app_dir
(app_name, roaming=True, force_posix=False)¶ Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system.
To give you an idea, for an app called
"Foo Bar"
, something like the following folders could be returned:- Mac OS X:
~/Library/Application Support/Foo Bar
- Mac OS X (POSIX):
~/.foo-bar
- Unix:
~/.config/foo-bar
- Unix (POSIX):
~/.foo-bar
- Win XP (roaming):
C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar
- Win XP (not roaming):
C:\Documents and Settings\<user>\Application Data\Foo Bar
- Win 7 (roaming):
C:\Users\<user>\AppData\Roaming\Foo Bar
- Win 7 (not roaming):
C:\Users\<user>\AppData\Local\Foo Bar
New in version 2.0.
Parameters: - app_name – the application name. This should be properly capitalized and can contain whitespace.
- roaming – controls if the folder should be roaming or not on Windows. Has no affect otherwise.
- force_posix – if this is set to True then on any POSIX system the folder will be stored in the home folder with a leading dot instead of the XDG config home or darwin’s application support folder.
-
click.
format_filename
(filename, shorten=False)¶ Formats a filename for user display. The main purpose of this function is to ensure that the filename can be displayed at all. This will decode the filename to unicode if necessary in a way that it will not fail. Optionally, it can shorten the filename to not include the full path to the filename.
Parameters: - filename – formats a filename for UI display. This will also convert the filename into unicode without failing.
- shorten – this optionally shortens the filename to strip of the path that leads up to it.
Commands¶
-
class
click.
BaseCommand
(name, context_settings=None)¶ The base command implements the minimal API contract of commands. Most code will never use this as it does not implement a lot of useful functionality but it can act as the direct subclass of alternative parsing methods that do not depend on the Click parser.
For instance, this can be used to bridge Click and other systems like argparse or docopt.
Because base commands do not implement a lot of the API that other parts of Click take for granted, they are not supported for all operations. For instance, they cannot be used with the decorators usually and they have no built-in callback system.
Changed in version 2.0: Added the context_settings parameter.
Parameters: - name – the name of the command to use unless a group overrides it.
- context_settings – an optional dictionary with defaults that are passed to the context object.
-
allow_extra_args
= False¶ the default for the
Context.allow_extra_args
flag.
-
allow_interspersed_args
= True¶ the default for the
Context.allow_interspersed_args
flag.
-
context_settings
= None¶ an optional dictionary with defaults passed to the context.
-
ignore_unknown_options
= False¶ the default for the
Context.ignore_unknown_options
flag.
-
invoke
(ctx)¶ Given a context, this invokes the command. The default implementation is raising a not implemented error.
-
main
(args=None, prog_name=None, complete_var=None, standalone_mode=True, **extra)¶ This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted,
SystemExit
needs to be caught.This method is also available by directly calling the instance of a
Command
.New in version 3.0: Added the standalone_mode flag to control the standalone mode.
Parameters: - args – the arguments that should be used for parsing. If not
provided,
sys.argv[1:]
is used. - prog_name – the program name that should be used. By default
the program name is constructed by taking the file
name from
sys.argv[0]
. - complete_var – the environment variable that controls the
bash completion support. The default is
"_<prog_name>_COMPLETE"
with prog name in uppercase. - standalone_mode – the default behavior is to invoke the script
in standalone mode. Click will then
handle exceptions and convert them into
error messages and the function will never
return but shut down the interpreter. If
this is set to False they will be
propagated to the caller and the return
value of this function is the return value
of
invoke()
. - extra – extra keyword arguments are forwarded to the context
constructor. See
Context
for more information.
- args – the arguments that should be used for parsing. If not
provided,
-
make_context
(info_name, args, parent=None, **extra)¶ This function when given an info name and arguments will kick off the parsing and create a new
Context
. It does not invoke the actual command callback though.Parameters: - info_name – the info name for this invokation. Generally this is the most descriptive name for the script or command. For the toplevel script it’s usually the name of the script, for commands below it it’s the name of the script.
- args – the arguments to parse as list of strings.
- parent – the parent context if available.
- extra – extra keyword arguments forwarded to the context constructor.
-
name
= None¶ the name the command thinks it has. Upon registering a command on a
Group
the group will default the command name with this information. You should instead use theContext
‘sinfo_name
attribute.
-
parse_args
(ctx, args)¶ Given a context and a list of arguments this creates the parser and parses the arguments, then modifies the context as necessary. This is automatically invoked by
make_context()
.
-
class
click.
Command
(name, context_settings=None, callback=None, params=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True)¶ Commands are the basic building block of command line interfaces in Click. A basic command handles command line parsing and might dispatch more parsing to commands nested below it.
Changed in version 2.0: Added the context_settings parameter.
Parameters: - name – the name of the command to use unless a group overrides it.
- context_settings – an optional dictionary with defaults that are passed to the context object.
- callback – the callback to invoke. This is optional.
- params – the parameters to register with this command. This can
be either
Option
orArgument
objects. - help – the help string to use for this command.
- epilog – like the help string but it’s printed at the end of the help page after everything else.
- short_help – the short help to use for this command. This is shown on the command listing of the parent command.
- add_help_option – by default each command registers a
--help
option. This can be disabled by this parameter.
-
callback
= None¶ the callback to execute when the command fires. This might be None in which case nothing happens.
-
collect_usage_pieces
(ctx)¶ Returns all the pieces that go into the usage line and returns it as a list of strings.
-
format_epilog
(ctx, formatter)¶ Writes the epilog into the formatter if it exists.
-
format_help
(ctx, formatter)¶ Writes the help into the formatter if it exists.
This calls into the following methods:
-
format_help_text
(ctx, formatter)¶ Writes the help text to the formatter if it exists.
-
format_options
(ctx, formatter)¶ Writes all the options into the formatter if they exist.
-
format_usage
(ctx, formatter)¶ Writes the usage line into the formatter.
-
get_help
(ctx)¶ Formats the help into a string and returns it. This creates a formatter and will call into the following formatting methods:
-
get_help_option
(ctx)¶ Returns the help option object.
-
get_help_option_names
(ctx)¶ Returns the names for the help option.
-
invoke
(ctx)¶ Given a context, this invokes the attached callback (if it exists) in the right way.
-
make_parser
(ctx)¶ Creates the underlying option parser for this command.
-
params
= None¶ the list of parameters for this command in the order they should show up in the help page and execute. Eager parameters will automatically be handled before non eager ones.
-
class
click.
MultiCommand
(name=None, invoke_without_command=False, no_args_is_help=None, subcommand_metavar=None, chain=False, result_callback=None, **attrs)¶ A multi command is the basic implementation of a command that dispatches to subcommands. The most common version is the
Group
.Parameters: - invoke_without_command – this controls how the multi command itself is invoked. By default it’s only invoked if a subcommand is provided.
- no_args_is_help – this controls what happens if no arguments are
provided. This option is enabled by default if
invoke_without_command is disabled or disabled
if it’s enabled. If enabled this will add
--help
as argument if no arguments are passed. - subcommand_metavar – the string that is used in the documentation to indicate the subcommand place.
- chain – if this is set to True chaining of multiple subcommands is enabled. This restricts the form of commands in that they cannot have optional arguments but it allows multiple commands to be chained together.
- result_callback – the result callback to attach to this multi command.
-
format_commands
(ctx, formatter)¶ Extra format methods for multi methods that adds all the commands after the options.
-
get_command
(ctx, cmd_name)¶ Given a context and a command name, this returns a
Command
object if it exists or returns None.
-
list_commands
(ctx)¶ Returns a list of subcommand names in the order they should appear.
-
result_callback
= None¶ The result callback that is stored. This can be set or overridden with the
resultcallback()
decorator.
-
resultcallback
(replace=False)¶ Adds a result callback to the chain command. By default if a result callback is already registered this will chain them but this can be disabled with the replace parameter. The result callback is invoked with the return value of the subcommand (or the list of return values from all subcommands if chaining is enabled) as well as the parameters as they would be passed to the main callback.
Example:
@click.group() @click.option('-i', '--input', default=23) def cli(input): return 42 @cli.resultcallback() def process_result(result, input): return result + input
New in version 3.0.
Parameters: replace – if set to True an already existing result callback will be removed.
-
class
click.
Group
(name=None, commands=None, **attrs)¶ A group allows a command to have subcommands attached. This is the most common way to implement nesting in Click.
Parameters: commands – a dictionary of commands. -
add_command
(cmd, name=None)¶ Registers another
Command
with this group. If the name is not provided, the name of the command is used.
-
command
(*args, **kwargs)¶ A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as
command()
but immediately registers the created command with this instance by calling intoadd_command()
.
-
commands
= None¶ the registered subcommands by their exported names.
-
group
(*args, **kwargs)¶ A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as
group()
but immediately registers the created command with this instance by calling intoadd_command()
.
-
-
class
click.
CommandCollection
(name=None, sources=None, **attrs)¶ A command collection is a multi command that merges multiple multi commands together into one. This is a straightforward implementation that accepts a list of different multi commands as sources and provides all the commands for each of them.
-
add_source
(multi_cmd)¶ Adds a new multi command to the chain dispatcher.
-
sources
= None¶ The list of registered multi commands.
-
Parameters¶
-
class
click.
Parameter
(param_decls=None, type=None, required=False, default=None, callback=None, nargs=None, metavar=None, expose_value=True, is_eager=False, envvar=None)¶ A parameter to a command comes in two versions: they are either
Option
s orArgument
s. Other subclasses are currently not supported by design as some of the internals for parsing are intentionally not finalized.Some settings are supported by both options and arguments.
Changed in version 2.0: Changed signature for parameter callback to also be passed the parameter. In Click 2.0, the old callback format will still work, but it will raise a warning to give you change to migrate the code easier.
Parameters: - param_decls – the parameter declarations for this option or argument. This is a list of flags or argument names.
- type – the type that should be used. Either a
ParamType
or a Python type. The later is converted into the former automatically if supported. - required – controls if this is optional or not.
- default – the default value if omitted. This can also be a callable, in which case it’s invoked when the default is needed without any arguments.
- callback – a callback that should be executed after the parameter
was matched. This is called as
fn(ctx, param, value)
and needs to return the value. Before Click 2.0, the signature was(ctx, value)
. - nargs – the number of arguments to match. If not
1
the return value is a tuple instead of single value. The default for nargs is1
(except if the type is a tuple, then it’s the arity of the tuple). - metavar – how the value is represented in the help page.
- expose_value – if this is True then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped.
- is_eager – eager values are processed before non eager ones. This should not be set for arguments or it will inverse the order of processing.
- envvar – a string or list of strings that are environment variables that should be checked.
-
get_default
(ctx)¶ Given a context variable this calculates the default value.
-
human_readable_name
¶ Returns the human readable name of this parameter. This is the same as the name for options, but the metavar for arguments.
-
process_value
(ctx, value)¶ Given a value and context this runs the logic to convert the value as necessary.
-
type_cast_value
(ctx, value)¶ Given a value this runs it properly through the type system. This automatically handles things like nargs and multiple as well as composite types.
-
class
click.
Option
(param_decls=None, show_default=False, prompt=False, confirmation_prompt=False, hide_input=False, is_flag=None, flag_value=None, multiple=False, count=False, allow_from_autoenv=True, type=None, help=None, **attrs)¶ Options are usually optional values on the command line and have some extra features that arguments don’t have.
All other parameters are passed onwards to the parameter constructor.
Parameters: - show_default – controls if the default value should be shown on the help page. Normally, defaults are not shown.
- prompt – if set to True or a non empty string then the user will be prompted for input if not set. If set to True the prompt will be the option name capitalized.
- confirmation_prompt – if set then the value will need to be confirmed if it was prompted for.
- hide_input – if this is True then the input on the prompt will be hidden from the user. This is useful for password input.
- is_flag – forces this option to act as a flag. The default is auto detection.
- flag_value – which value should be used for this flag if it’s enabled. This is set to a boolean automatically if the option string contains a slash to mark two options.
- multiple – if this is set to True then the argument is accepted
multiple times and recorded. This is similar to
nargs
in how it works but supports arbitrary number of arguments. - count – this flag makes an option increment an integer.
- allow_from_autoenv – if this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context.
- help – the help string.
-
class
click.
Argument
(param_decls, required=None, **attrs)¶ Arguments are positional parameters to a command. They generally provide fewer features than options but can have infinite
nargs
and are required by default.All parameters are passed onwards to the parameter constructor.
Context¶
-
class
click.
Context
(command, parent=None, info_name=None, obj=None, auto_envvar_prefix=None, default_map=None, terminal_width=None, max_content_width=None, resilient_parsing=False, allow_extra_args=None, allow_interspersed_args=None, ignore_unknown_options=None, help_option_names=None, token_normalize_func=None, color=None)¶ The context is a special internal object that holds state relevant for the script execution at every single level. It’s normally invisible to commands unless they opt-in to getting access to it.
The context is useful as it can pass internal objects around and can control special execution features such as reading data from environment variables.
A context can be used as context manager in which case it will call
close()
on teardown.New in version 2.0: Added the resilient_parsing, help_option_names, token_normalize_func parameters.
New in version 3.0: Added the allow_extra_args and allow_interspersed_args parameters.
New in version 4.0: Added the color, ignore_unknown_options, and max_content_width parameters.
Parameters: - command – the command class for this context.
- parent – the parent context.
- info_name – the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it is usually the name of the script, for commands below it it’s the name of the script.
- obj – an arbitrary object of user data.
- auto_envvar_prefix – the prefix to use for automatic environment variables. If this is None then reading from environment variables is disabled. This does not affect manually set environment variables which are always read.
- default_map – a dictionary (like object) with default values for parameters.
- terminal_width – the width of the terminal. The default is inherit from parent context. If no context defines the terminal width then auto detection will be applied.
- max_content_width – the maximum width for content rendered by Click (this currently only affects help pages). This defaults to 80 characters if not overridden. In other words: even if the terminal is larger than that, Click will not format things wider than 80 characters by default. In addition to that, formatters might add some safety mapping on the right.
- resilient_parsing – if this flag is enabled then Click will parse without any interactivity or callback invocation. This is useful for implementing things such as completion support.
- allow_extra_args – if this is set to True then extra arguments at the end will not raise an error and will be kept on the context. The default is to inherit from the command.
- allow_interspersed_args – if this is set to False then options and arguments cannot be mixed. The default is to inherit from the command.
- ignore_unknown_options – instructs click to ignore options it does not know and keeps them for later processing.
- help_option_names – optionally a list of strings that define how
the default help parameter is named. The
default is
['--help']
. - token_normalize_func – an optional function that is used to normalize tokens (options, choices, etc.). This for instance can be used to implement case insensitive behavior.
- color – controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are used in texts that Click prints which is by default not the case. This for instance would affect help output.
-
abort
()¶ Aborts the script.
-
allow_extra_args
= None¶ Indicates if the context allows extra args or if it should fail on parsing.
New in version 3.0.
-
allow_interspersed_args
= None¶ Indicates if the context allows mixing of arguments and options or not.
New in version 3.0.
-
args
= None¶ the leftover arguments.
-
call_on_close
(f)¶ This decorator remembers a function as callback that should be executed when the context tears down. This is most useful to bind resource handling to the script execution. For instance, file objects opened by the
File
type will register their close callbacks here.Parameters: f – the function to execute on teardown.
-
close
()¶ Invokes all close callbacks.
-
color
= None¶ Controls if styling output is wanted or not.
-
command_path
¶ The computed command path. This is used for the
usage
information on the help page. It’s automatically created by combining the info names of the chain of contexts to the root.
-
ensure_object
(object_type)¶ Like
find_object()
but sets the innermost object to a new instance of object_type if it does not exist.
-
exit
(code=0)¶ Exits the application with a given exit code.
-
fail
(message)¶ Aborts the execution of the program with a specific error message.
Parameters: message – the error message to fail with.
-
find_object
(object_type)¶ Finds the closest object of a given type.
-
find_root
()¶ Finds the outermost context.
-
forward
(*args, **kwargs)¶ Similar to
invoke()
but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands.
-
get_help
()¶ Helper method to get formatted help page for the current context and command.
-
get_usage
()¶ Helper method to get formatted usage string for the current context and command.
-
help_option_names
= None¶ The names for the help options.
-
ignore_unknown_options
= None¶ Instructs click to ignore options that a command does not understand and will store it on the context for later processing. This is primarily useful for situations where you want to call into external programs. Generally this pattern is strongly discouraged because it’s not possibly to losslessly forward all arguments.
New in version 4.0.
-
info_name
= None¶ the descriptive information name
-
invoke
(*args, **kwargs)¶ Invokes a command callback in exactly the way it expects. There are two ways to invoke this method:
- the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function.
- the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults.
Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see Upgrading to 3.2.
-
invoked_subcommand
= None¶ This flag indicates if a subcommand is going to be executed. A group callback can use this information to figure out if it’s being executed directly or because the execution flow passes onwards to a subcommand. By default it’s None, but it can be the name of the subcommand to execute.
If chaining is enabled this will be set to
'*'
in case any commands are executed. It is however not possible to figure out which ones. If you require this knowledge you should use aresultcallback()
.
-
lookup_default
(name)¶ Looks up the default for a parameter name. This by default looks into the
default_map
if available.
-
make_formatter
()¶ Creates the formatter for the help and usage output.
-
max_content_width
= None¶ The maximum width of formatted content (None implies a sensible default which is 80 for most things).
-
meta
¶ This is a dictionary which is shared with all the contexts that are nested. It exists so that click utiltiies can store some state here if they need to. It is however the responsibility of that code to manage this dictionary well.
The keys are supposed to be unique dotted strings. For instance module paths are a good choice for it. What is stored in there is irrelevant for the operation of click. However what is important is that code that places data here adheres to the general semantics of the system.
Example usage:
LANG_KEY = __name__ + '.lang' def set_language(value): ctx = get_current_context() ctx.meta[LANG_KEY] = value def get_language(): return get_current_context().meta.get(LANG_KEY, 'en_US')
New in version 5.0.
-
obj
= None¶ the user object stored.
-
params
= None¶ the parsed parameters except if the value is hidden in which case it’s not remembered.
-
parent
= None¶ the parent context or None if none exists.
-
resilient_parsing
= None¶ Indicates if resilient parsing is enabled. In that case Click will do its best to not cause any failures.
-
scope
(*args, **kwds)¶ This helper method can be used with the context object to promote it to the current thread local (see
get_current_context()
). The default behavior of this is to invoke the cleanup functions which can be disabled by setting cleanup to False. The cleanup functions are typically used for things such as closing file handles.If the cleanup is intended the context object can also be directly used as a context manager.
Example usage:
with ctx.scope(): assert get_current_context() is ctx
This is equivalent:
with ctx: assert get_current_context() is ctx
New in version 5.0.
Parameters: cleanup – controls if the cleanup functions should be run or not. The default is to run these functions. In some situations the context only wants to be temporarily pushed in which case this can be disabled. Nested pushes automatically defer the cleanup.
-
terminal_width
= None¶ The width of the terminal (None is autodetection).
-
token_normalize_func
= None¶ An optional normalization function for tokens. This is options, choices, commands etc.
-
click.
get_current_context
(silent=False)¶ Returns the current click context. This can be used as a way to access the current context object from anywhere. This is a more implicit alternative to the
pass_context()
decorator. This function is primarily useful for helpers such asecho()
which might be interested in changing it’s behavior based on the current context.To push the current context,
Context.scope()
can be used.New in version 5.0.
Parameters: silent – is set to True the return value is None if no context is available. The default behavior is to raise a RuntimeError
.
Types¶
-
click.
STRING
= STRING¶ A unicode string parameter type which is the implicit default. This can also be selected by using
str
as type.
-
click.
INT
= INT¶ An integer parameter. This can also be selected by using
int
as type.
-
click.
FLOAT
= FLOAT¶ A floating point value parameter. This can also be selected by using
float
as type.
-
click.
BOOL
= BOOL¶ A boolean parameter. This is the default for boolean flags. This can also be selected by using
bool
as a type.
-
click.
UUID
= UUID¶ A UUID parameter.
-
click.
UNPROCESSED
= UNPROCESSED¶ A dummy parameter type that just does nothing. From a user’s perspective this appears to just be the same as STRING but internally no string conversion takes place. This is necessary to achieve the same bytes/unicode behavior on Python 2/3 in situations where you want to not convert argument types. This is usually useful when working with file paths as they can appear in bytes and unicode.
For path related uses the
Path
type is a better choice but there are situations where an unprocessed type is useful which is why it is is provided.New in version 4.0.
-
class
click.
File
(mode='r', encoding=None, errors='strict', lazy=None, atomic=False)¶ Declares a parameter to be a file for reading or writing. The file is automatically closed once the context tears down (after the command finished working).
Files can be opened for reading or writing. The special value
-
indicates stdin or stdout depending on the mode.By default, the file is opened for reading text data, but it can also be opened in binary mode or for writing. The encoding parameter can be used to force a specific encoding.
The lazy flag controls if the file should be opened immediately or upon first IO. The default is to be non lazy for standard input and output streams as well as files opened for reading, lazy otherwise.
Starting with Click 2.0, files can also be opened atomically in which case all writes go into a separate file in the same folder and upon completion the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.
See File Arguments for more information.
-
class
click.
Path
(exists=False, file_okay=True, dir_okay=True, writable=False, readable=True, resolve_path=False)¶ The path type is similar to the
File
type but it performs different checks. First of all, instead of returning an open file handle it returns just the filename. Secondly, it can perform various basic checks about what the file or directory should be.Parameters: - exists – if set to true, the file or directory needs to exist for this value to be valid. If this is not required and a file does indeed not exist, then all further checks are silently skipped.
- file_okay – controls if a file is a possible value.
- dir_okay – controls if a directory is a possible value.
- writable – if true, a writable check is performed.
- readable – if true, a readable check is performed.
- resolve_path – if this is true, then the path is fully resolved before the value is passed onwards. This means that it’s absolute and symlinks are resolved.
-
class
click.
Choice
(choices)¶ The choice type allows a value to be checked against a fixed set of supported values. All of these values have to be strings.
See Choice Options for an example.
-
class
click.
IntRange
(min=None, max=None, clamp=False)¶ A parameter that works similar to
click.INT
but restricts the value to fit into a range. The default behavior is to fail if the value falls outside the range, but it can also be silently clamped between the two edges.See Range Options for an example.
-
class
click.
Tuple
(types)¶ The default behavior of Click is to apply a type on a value directly. This works well in most cases, except for when nargs is set to a fixed count and different types should be used for different items. In this case the
Tuple
type can be used. This type can only be used if nargs is set to a fixed number.For more information see Tuples as Multi Value Options.
This can be selected by using a Python tuple literal as a type.
Parameters: types – a list of types that should be used for the tuple items.
-
class
click.
ParamType
¶ Helper for converting values through types. The following is necessary for a valid type:
- it needs a name
- it needs to pass through None unchanged
- it needs to convert from a string
- it needs to convert its result type through unchanged (eg: needs to be idempotent)
- it needs to be able to deal with param and context being None. This can be the case when the object is used with prompt inputs.
-
convert
(value, param, ctx)¶ Converts the value. This is not invoked for values that are None (the missing value).
-
envvar_list_splitter
= None¶ if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by
os.path.pathsep
by default (”:” on Unix and ”;” on Windows).
-
fail
(message, param=None, ctx=None)¶ Helper method to fail with an invalid value message.
-
get_metavar
(param)¶ Returns the metavar default for this param if it provides one.
-
get_missing_message
(param)¶ Optionally might return extra information about a missing parameter.
New in version 2.0.
-
name
= None¶ the descriptive name of this type
-
split_envvar_value
(rv)¶ Given a value from an environment variable this splits it up into small chunks depending on the defined envvar list splitter.
If the splitter is set to None, which means that whitespace splits, then leading and trailing whitespace is ignored. Otherwise, leading and trailing splitters usually lead to empty items being included.
Exceptions¶
-
exception
click.
ClickException
(message)¶ An exception that Click can handle and show to the user.
-
exception
click.
Abort
¶ An internal signalling exception that signals Click to abort.
-
exception
click.
UsageError
(message, ctx=None)¶ An internal exception that signals a usage error. This typically aborts any further handling.
Parameters: - message – the error message to display.
- ctx – optionally the context that caused this error. Click will fill in the context automatically in some situations.
-
exception
click.
BadParameter
(message, ctx=None, param=None, param_hint=None)¶ An exception that formats out a standardized error message for a bad parameter. This is useful when thrown from a callback or type as Click will attach contextual information to it (for instance, which parameter it is).
New in version 2.0.
Parameters: - param – the parameter object that caused this error. This can be left out, and Click will attach this info itself if possible.
- param_hint – a string that shows up as parameter name. This can be used as alternative to param in cases where custom validation should happen. If it is a string it’s used as such, if it’s a list then each item is quoted and separated.
-
exception
click.
FileError
(filename, hint=None)¶ Raised if a file cannot be opened.
-
exception
click.
NoSuchOption
(option_name, message=None, possibilities=None, ctx=None)¶ Raised if click attempted to handle an option that does not exist.
New in version 4.0.
-
exception
click.
BadOptionUsage
(option_name, message, ctx=None)¶ Raised if an option is generally supplied but the use of the option was incorrect. This is for instance raised if the number of arguments for an option is not correct.
New in version 4.0.
Formatting¶
-
class
click.
HelpFormatter
(indent_increment=2, width=None, max_width=None)¶ This class helps with formatting text-based help pages. It’s usually just needed for very special internal cases, but it’s also exposed so that developers can write their own fancy outputs.
At present, it always writes into memory.
Parameters: - indent_increment – the additional increment for each level.
- width – the width for the text. This defaults to the terminal width clamped to a maximum of 78.
-
dedent
()¶ Decreases the indentation.
-
getvalue
()¶ Returns the buffer contents.
-
indent
()¶ Increases the indentation.
-
indentation
(*args, **kwds)¶ A context manager that increases the indentation.
-
section
(*args, **kwds)¶ Helpful context manager that writes a paragraph, a heading, and the indents.
Parameters: name – the section name that is written as heading.
-
write
(string)¶ Writes a unicode string into the internal buffer.
-
write_dl
(rows, col_max=30, col_spacing=2)¶ Writes a definition list into the buffer. This is how options and commands are usually formatted.
Parameters: - rows – a list of two item tuples for the terms and values.
- col_max – the maximum width of the first column.
- col_spacing – the number of spaces between the first and second column.
-
write_heading
(heading)¶ Writes a heading into the buffer.
-
write_paragraph
()¶ Writes a paragraph into the buffer.
-
write_text
(text)¶ Writes re-indented text into the buffer. This rewraps and preserves paragraphs.
-
write_usage
(prog, args='', prefix='Usage: ')¶ Writes a usage line into the buffer.
Parameters: - prog – the program name.
- args – whitespace separated list of arguments.
- prefix – the prefix for the first line.
-
click.
wrap_text
(text, width=78, initial_indent='', subsequent_indent='', preserve_paragraphs=False)¶ A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the preserve_paragraphs parameter is provided it will intelligently handle paragraphs (defined by two empty lines).
If paragraphs are handled, a paragraph can be prefixed with an empty line containing the
\b
character (\x08
) to indicate that no rewrapping should happen in that block.Parameters: - text – the text that should be rewrapped.
- width – the maximum width for the text.
- initial_indent – the initial indent that should be placed on the first line as a string.
- subsequent_indent – the indent string that should be placed on each consecutive line.
- preserve_paragraphs – if this flag is set then the wrapping will intelligently handle paragraphs.
Parsing¶
-
class
click.
OptionParser
(ctx=None)¶ The option parser is an internal class that is ultimately used to parse options and arguments. It’s modelled after optparse and brings a similar but vastly simplified API. It should generally not be used directly as the high level Click classes wrap it for you.
It’s not nearly as extensible as optparse or argparse as it does not implement features that are implemented on a higher level (such as types or defaults).
Parameters: ctx – optionally the Context
where this parser should go with.-
add_argument
(dest, nargs=1, obj=None)¶ Adds a positional argument named dest to the parser.
The obj can be used to identify the option in the order list that is returned from the parser.
-
add_option
(opts, dest, action=None, nargs=1, const=None, obj=None)¶ Adds a new option named dest to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of
store
,store_const
,append
,appnd_const
orcount
.The obj can be used to identify the option in the order list that is returned from the parser.
-
allow_interspersed_args
= None¶ This controls how the parser deals with interspersed arguments. If this is set to False, the parser will stop on the first non-option. Click uses this to implement nested subcommands safely.
-
ignore_unknown_options
= None¶ This tells the parser how to deal with unknown options. By default it will error out (which is sensible), but there is a second mode where it will ignore it and continue processing after shifting all the unknown options into the resulting args.
-
parse_args
(args)¶ Parses positional arguments and returns
(values, args, order)
for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well.
-
Testing¶
-
class
click.testing.
CliRunner
(charset=None, env=None, echo_stdin=False)¶ The CLI runner provides functionality to invoke a Click command line script for unittesting purposes in a isolated environment. This only works in single-threaded systems without any concurrency as it changes the global interpreter state.
Parameters: - charset – the character set for the input and output data. This is UTF-8 by default and should not be changed currently as the reporting to Click only works in Python 2 properly.
- env – a dictionary with environment variables for overriding.
- echo_stdin – if this is set to True, then reading from stdin writes to stdout. This is useful for showing examples in some circumstances. Note that regular prompts will automatically echo the input.
-
get_default_prog_name
(cli)¶ Given a command object it will return the default program name for it. The default is the name attribute or
"root"
if not set.
-
invoke
(cli, args=None, input=None, env=None, catch_exceptions=True, color=False, **extra)¶ Invokes a command in an isolated environment. The arguments are forwarded directly to the command line script, the extra keyword arguments are passed to the
main()
function of the command.This returns a
Result
object.New in version 3.0: The
catch_exceptions
parameter was added.Changed in version 3.0: The result object now has an exc_info attribute with the traceback if available.
New in version 4.0: The
color
parameter was added.Parameters: - cli – the command to invoke
- args – the arguments to invoke
- input – the input data for sys.stdin.
- env – the environment overrides.
- catch_exceptions – Whether to catch any other exceptions than
SystemExit
. - extra – the keyword arguments to pass to
main()
. - color – whether the output should contain color codes. The application can still override this explicitly.
-
isolated_filesystem
(*args, **kwds)¶ A context manager that creates a temporary folder and changes the current working directory to it for isolated filesystem tests.
-
isolation
(*args, **kwds)¶ A context manager that sets up the isolation for invoking of a command line tool. This sets up stdin with the given input data and os.environ with the overrides from the given dictionary. This also rebinds some internals in Click to be mocked (like the prompt functionality).
This is automatically done in the
invoke()
method.New in version 4.0: The
color
parameter was added.Parameters: - input – the input stream to put into sys.stdin.
- env – the environment overrides as dictionary.
- color – whether the output should contain color codes. The application can still override this explicitly.
-
make_env
(overrides=None)¶ Returns the environment overrides for invoking a script.
-
class
click.testing.
Result
(runner, output_bytes, exit_code, exception, exc_info=None)¶ Holds the captured result of an invoked CLI script.
-
exc_info
= None¶ The traceback
-
exception
= None¶ The exception that happend if one did.
-
exit_code
= None¶ The exit code as integer.
-
output
¶ The output as unicode string.
-
output_bytes
= None¶ The output as bytes.
-
runner
= None¶ The runner that created the result
-


×
[App Name] is loading
Smooth animation plays while the app window is locked up and hidden from view.


SpectraProcessing¶
This routine calculates the radar moments for the RPG 94 GHz FMCW radar ‘LIMRAD94’ and generates a NetCDF4 file. The generated files can be used as input for the Cloudnet processing chain.
| param **date: | format YYYYMMDD |
|---|---|
| type **date: | string |
| param **path: | path where NetCDF file will be stored |
| type **path: | string |
Example
python spec2mom_limrad94.py date=20181201 path=/tmp/pycharm_project_626/scripts_Willi/cloudnet_input/
-
pyLARDA.SpectraProcessing.
replace_fill_value
(data, newfill)[source]¶ Replaces the fill value of an spectrum container by their time and range specific mean noise level.
Parameters: - data (numpy.array) – 3D spectrum array (time, range, velocity)
- newfill (numpy.array) – 2D new fill values for 3rd dimension (velocity)
Returns: spectrum with mean noise
Return type: var (numpy.array)
-
pyLARDA.SpectraProcessing.
estimate_noise_hs74
[source]¶ //github.com/ARM-DOE/pyart/blob/master/pyart/util/hildebrand_sekhon.py
Estimate noise parameters of a Doppler spectrum. Use the method of estimating the noise level in Doppler spectra outlined by Hildebrand and Sehkon, 1974.
Parameters: - spectrum (array) – Doppler spectrum in linear units.
- navg (int, optional) – The number of spectral bins over which a moving average has been taken. Corresponds to the p variable from equation 9 of the article. The default value of 1 is appropriate when no moving average has been applied to the spectrum.
- std_div (float, optional) – Number of standard deviations above mean noise floor to specify the signal threshold, default: threshold=mean_noise + 6*std(mean_noise)
- nnoise_min (int, optional) – Minimum number of noise samples to consider the estimation valid.
Returns: tuple with
- mean (float): Mean of points in the spectrum identified as noise.
- threshold (float): Threshold separating noise from signal. The point in the spectrum with this value or below should be considered as noise, above this value signal. It is possible that all points in the spectrum are identified as noise. If a peak is required for moment calculation then the point with this value should be considered as signal.
- var (float): Variance of the points in the spectrum identified as noise.
- nnoise (int): Number of noise points in the spectrum.
References
P. H. Hildebrand and R. S. Sekhon, Objective Determination of the Noise Level in Doppler Spectra. Journal of Applied Meteorology, 1974, 13, 808-811.
Type: REFERENCE TO ARM PYART GITHUB REPO Type: https
-
pyLARDA.SpectraProcessing.
find_peak_edges
[source]¶ Returns the indices of left and right edge of the main signal peak in a Doppler spectra.
Parameters: - signal (numpy.array) – 1D array Doppler spectra
- threshold – noise threshold
Returns: indices of signal minimum/maximum velocity
Return type: [index_left, index_right] (list)
-
pyLARDA.SpectraProcessing.
radar_moment_calculation
[source]¶ reflectivity, mean Doppler velocity, spectral width, skewness, and kurtosis of one Doppler spectrum. Optimized for the use of Numba.
Note
Divide the signal_sum by 2 because vertical and horizontal channel are added. Subtract half of of the Doppler resolution from mean Doppler velocity, because
Parameters: - signal (-) – detected signal from a Doppler spectrum
- vel_bins (-) – extracted velocity bins of the signal (same length as signal)
- DoppRes (-) – resolution of the Doppler spectra (different for each chirp)
Returns: dict containing
- Ze_lin (float array): reflectivity (0.Mom) over range of velocity bins [mm6/m3]
- VEL (float array): mean velocity (1.Mom) over range of velocity bins [m/s]
- sw (float array): spectrum width (2.Mom) over range of velocity bins [m/s]
- skew (float array): skewness (3.Mom) over range of velocity bins
- kurt (float array): kurtosis (4.Mom) over range of velocity bins
Type: Calculation of radar moments
-
pyLARDA.SpectraProcessing.
despeckle
[source]¶ Remove small patches (speckle) from any given mask by checking 5x5 box around each pixel, more than half of the points in the box need to be 1 to keep the 1 at current pixel
Parameters: - mask (numpy.array, integer) – 2D mask where 1 = an invalid/fill value and 0 = a data point (time, height)
- min_percentage (float) – minimum percentage of neighbours that need to be signal above noise
Returns: mask … speckle-filtered matrix of 0 and 1 that represents (cloud) mask [height x time]
-
pyLARDA.SpectraProcessing.
make_container_from_spectra
(spectra_all_chirps, values, paraminfo, invalid_mask, varname='')[source]¶ This routine will generate a larda container from calculated moments from spectra.
Parameters: - spectra_all_chirps (list of dicts) – dimension [nchirps], containing the spectrum values of the 94 GHz RPG cloud radar
- values (numpy array) – dimension [nrange, ntimes], values of calculated moments
- paraminfo (dict) – information from params_[campaign].toml for the specific variable
Returns: larda data container
Return type: container (dict)
-
pyLARDA.SpectraProcessing.
load_spectra_rpgfmcw94
(larda, time_span, rpg_radar='LIMRAD94', **kwargs)[source]¶ This routine will generate a list of larda containers including spectra of the RPG-FMCW 94GHz radar. The list-container at return will contain the additional information, for each chirp.
Parameters: - rpg_radar (string) – name of the radar system as defined in the toml file
- larda (class larda) – Initialized pyLARDA, already connected to a specific campaign
- time_span (list) – Starting and ending time point in datetime format.
- **noise_factor (float) – Noise factor, number of standard deviations from mean noise floor
- **ghost_echo_1 (bool) – Filters ghost echos which occur over all chirps during precipitation.
- **ghost_echo_2 (bool) – Filters ghost echos which occur over 1 chirps during precipitation.
- **estimate_noise (boal) –
If True, adds the following noise estimation values to the container:
- mean (2d ndarray): Mean noise level of the spectra.
- threshold (2d ndarray): Noise threshold, values above this threshold are consider as signal.
- variance (2d ndarray): The variance of the mean noise level.
- numnoise (2d ndarray): Number of Pixels that are cconsideras noise.
- signal (2d ndarray): Boolean array, a value is True if no signal was detected.
- bounds (3d ndarrax): Dimensions [n_time, n_range, 2] containing the integration boundaries.
Returns: list of larda data container
- spec[i_chirps][‘no_av’] (float): Number of spectral averages divided by the number of FFT points
- spec[i_chirps][‘DoppRes’] (float): Doppler resolution for
- spec[i_chirps][‘SL’] (2D-float): Sensitivity limit (dimensions: time, range)
- spec[i_chirps][‘NF’] (string): Noise factor, default = 6.0
- spec[i_chirps][‘rg_offsets’] (list): Indices, where chipr shifts
Return type: container (list)
-
pyLARDA.SpectraProcessing.
dealiasing_check
(masked3D)[source]¶ Checks for folding.
Parameters: - masked3D (numpy.array) – 3D (time, range, velocity)
- vel (list) – contains 1D numpy.arrays for each chirp
- mean_noise (numpy.array) –
- rg_offsets (numpy.array) –
Returns: Return type: alias_flag (numpy.array)
-
pyLARDA.SpectraProcessing.
dealiasing
(spectra: numpy.array, vel_bins_per_chirp: List[numpy.array], noisefloor: numpy.array, rg_offsets: List[int] = None, show_triple: bool = False, vel_offsets: List[int] = None, jump: int = None) → Union[numpy.array, List[numpy.array]][source]¶ Peaks exceeding the maximum unambiguous Doppler velocity range of ± v_Nyq in [m s-1] appear at the next upper (lower) range gate at the other end of the velocity spectrum. The dealiasing method presented here aims to correct for this and is applied to every time step.
Logging level INFO shows the de-aliasing progress bar.
Parameters: - spectra – dim = (n_time, n_range, n_velocity) in linear units!
- vel_bins_per_chirp – len = (n_chirp), each list element contains a numpy array of velocity bins
- noisefloor – dim = (n_time, n_range) in linear units!
- rg_offsets (optional) – dim = (n_chirp + 1), starting with 0, range indices where chirp shift occurs
- show_triple (optional) – if True, return dealiased spectra including the triplication
- vel_offsets (optional) – velocity window around the main peak [x1, x2], x1 < 0, x2 > 0 ! in [m s-1], default [-6.0, +9.0]
- jump (optional) – maximum number of Doppler bins a spectrum can change in two adjacent range bins
Returns: tuple containing
- dealiased_spectra: dim = (n_time, n_range, 3 * n_velocity), de-aliased Doppler spectrum
- dealiased_mask: dim = (n_time, n_range, 3 * n_velocity), True if no signal
- velocity_new: len = (n_chirp), each list element contains a numpy array of velocity bins for the respective chirp of ± 3*v_Nyq in [m s-1]
- signal_boundaries: indices of left and right edge of a signal, [-1, -1] if no signal
- search_path: indices of left and right edge of the search path, [-1, -1] if no signal
- idx_peak_matrix: indices of the main peaks, [NDbins / 2] if no signal
Todo
- add time–height mask for dealiasing
- search window relative to [m s-1]
- abs(idx_new_peak - mean_idx_last_ts) > 120: –> relativ
-
pyLARDA.SpectraProcessing.
noise_estimation_uncompressed_data
(data, n_std=6.0, **kwargs)[source]¶ Creates a dict containing the noise threshold, mean noise level, the variance of the noise, the number of noise values in the spectrum, and the boundaries of the main signal peak, if there is one
Parameters: - data (dict) – data container, containing data[‘var’] of dimension (n_ts, n_range, n_Doppler_bins)
- **n_std_deviations (float) – threshold = number of standard deviations above mean noise floor, default: threshold is the value of the first non-noise value
Returns: dict with noise floor estimation for all time and range points
-
pyLARDA.SpectraProcessing.
mira_noise_calculation
(radar_const, SNRCorFaCo, HSDco, noise_power_co, range_ka)[source]¶ Parameters: - radar_const –
- SNRCorFaCo –
- HSDco –
- noise_power_co –
- range_ka –
Returns: noise level in linear units
-
pyLARDA.SpectraProcessing.
despeckle2D
(data, min_perc=80.0)[source]¶ This function is used to remove all spectral lines for one time-range-pixel if surrounding% of the sourounding pixels are fill_values.
Parameters: data (numpy.array) – cloud radar Doppler spectra, dimensions: (time, range, velocity), unit: [mm6 mm-3 m s-1] Keyword Arguments: min_perc (float) – minimum percentage value of neighbouring pixel, that need to be above the noise threshold Returns: where True = fill_value, and False = signal, dimensions: (time, range, velocity) Return type: mask (numpy.array, bool)
-
pyLARDA.SpectraProcessing.
filter_ghost_1
(data, rg, vel, offset, dBZ_thresh=-20.0, reduce_by=1.5, **kwargs)[source]¶ This function is used to remove certain spectral lines “speckle ghost echoes” from all chirps of RPG FMCW 94GHz cloud radar spectra. The speckle occur usually near the maximum unambiguous Doppler velocity.
Parameters: - data (numpy.array) – cloud radar Doppler spectra, dimensions: (time, range, velocity), unit: [mm6 mm-3 m s-1]
- rg (numpy.array) – range values, unit [m]
- vel (list of numpy.arrays) – contains the Doppler velocity values for each chirp, dimension = n_chirps
- offset (list, integer) – range indices where the chirp changes takes place, dimension = n_chirps + 1 (starting with 0)
- dBZ_thresh (float) – values below will be considered as ghost echo
- reduce_by (float) – reduce the maximum unambiguous Doppler velocity by this amount in [m s-1]
- **ignore_chirp1 (bool) – Don’t filter ghost echos of this type for first chirp (set to True if not given)
- **Z_thresh (float) – Ze in dBZ to be exceeded in lowest 500 m range for filter to be activated
Returns: where True = fill_value, and False = signal, dimensions: (time, range, velocity)
Return type: mask (numpy.array, bool)
-
pyLARDA.SpectraProcessing.
filter_ghost_2
(data, rg, SL, first_offset, dBZ_thresh=-5.0, reduce_by=10.0)[source]¶ This function is used to remove curtain-like ghost echoes from the first chirp of RPG FMCW 94GHz cloud radar spectra.
Parameters: - data (numpy.array) – cloud radar Doppler spectra, dimensions: (time, range, velocity), unit: [mm6 mm-3 m s-1]
- rg (numpy.array) – range values, unit [m]
- SL (numpy.array) – sensitivity limit, dimension: (time, range), unit: [mm6 mm-3]
- first_offset (integer) – range index where the first chirp change takes place
- dBZ_thresh (float) – minimum threshold in [dBZ], where ghost echos can be assumed
- reduce_by (float) – reduce the sensitivity limit by this amount of [dBZ]
Returns: where True = fill_value, and False = signal, dimensions: (time, range, velocity)
Return type: mask (numpy.array, bool)
-
pyLARDA.SpectraProcessing.
spectra2moments
(ZSpec, paraminfo, **kwargs)[source]¶ This routine calculates the radar moments: reflectivity, mean Doppler velocity, spectrum width, skewness and kurtosis from the level 0 spectrum files of the 94 GHz RPG cloud radar.
Parameters: - ZSpec (dict) – list containing the dicts for each chrip of RPG-FMCW Doppler cloud radar
- paraminfo (dict) – information from params_[campaign].toml for the system LIMRAD94
Returns: dictionary of larda containers, including larda container for Ze, VEL, sw, skew, kurt
Return type: container_dict (dict)
-
pyLARDA.SpectraProcessing.
heave_correction
(moments, date, path_to_seapath='/projekt2/remsens/data_new/site-campaign/rv_meteor-eurec4a/instruments/RV-METEOR_DSHIP', mean_hr=True, only_heave=False, use_cross_product=True, transform_to_earth=True, add=False)[source]¶ Correct mean Doppler velocity for heave motion of ship (RV-Meteor) Calculate heave rate from seapath measurements and create heave correction array. If Doppler velocity is given as an input, correct it and return an array with the corrected Doppler velocities. Without Doppler Velocity input, only the heave correction array is returned.
Parameters: - moments – LIMRAD94 moments container as returned by spectra2moments in spec2mom_limrad94.py, C1/2/3_Range, SeqIntTime and Inc_ElA (for time (ts)) from LV1 file
- date (datetime.datetime) – object with date of current file
- path_to_seapath (string) – path where seapath measurement files (daily dat files) are stored
- mean_hr (bool) – whether to use the mean heave rate over the SeqIntTime or the heave rate at the start time of the chirp
- only_heave (bool) – whether to use only heave to calculate the heave rate or include pitch and roll induced heave
- use_cross_product (bool) – whether to use the cross product like Hannes Griesche https://doi.org/10.5194/amt-2019-434
- transform_to_earth (bool) – transform cross product to earth coordinate system as described in https://repository.library.noaa.gov/view/noaa/17400
- add (bool) – whether to add the heave rate or subtract it
Returns: A number of variables
- new_vel (ndarray); corrected Doppler velocities, same shape as moments[“VEL”][“var”] or list if no Doppler Velocity is given;
- heave_corr (ndarray): heave rate closest to each radar timestep for each height bin, same shape as moments[“VEL”][“var”];
- seapath_out (pd.DataFrame): data frame with all heave information from the closest time steps to the chirps
-
pyLARDA.SpectraProcessing.
heave_correction_spectra
(data, date, path_to_seapath='/projekt2/remsens/data_new/site-campaign/rv_meteor-eurec4a/instruments/RV-METEOR_DSHIP', mean_hr=True, only_heave=False, use_cross_product=True, transform_to_earth=True, add=False, **kwargs)[source]¶ Shift Doppler spectra to correct for heave motion of ship (RV-Meteor) Calculate heave rate from seapath measurements and create heave correction array. Translate the heave correction to a number spectra bins by which to move each spectra. If Spectra are given, shift them and return a 3D array with the shifted spectra. Without spectra input, only the heave correction array and the array with the number if bins to move is returned.
Parameters: - data – LIMRAD94 data container filled with spectra and C1/2/3_Range, SeqIntTime, MaxVel, DoppLen from LV1 file; for Claudia’s version the mean Doppler velocity is also needed
- date (datetime.datetime) – object with date of current file
- path_to_seapath (string) – path where seapath measurement files (daily dat files) are stored
- mean_hr (bool) – whether to use the mean heave rate over the SeqIntTime or the heave rate at the start time of the chirp
- only_heave (bool) – whether to use only heave to calculate the heave rate or include pitch and roll induced heave
- use_cross_product (bool) – whether to use the cross product like Hannes Griesche https://doi.org/10.5194/amt-2019-434
- transform_to_earth (bool) – transform cross product to earth coordinate system as described in https://repository.library.noaa.gov/view/noaa/17400
- add (bool) – whether to add the heave rate or subtract it
- **kwargs – shift (int): number of time steps to shift seapath data version (str): which version to use, ‘ca’ or ‘jr’
Returns: A number of variables
- new_spectra (ndarray); corrected Doppler velocities, same shape as data[“VHSpec”][“var”] or list if no Doppler Spectra are given;
- heave_corr (ndarray): heave rate closest to each radar timestep for each height bin, shape = (time x range);
- seapath_out (pd.DataFrame): data frame with all heave information from the closest time steps to the chirps
-
pyLARDA.SpectraProcessing.
read_seapath
(date, path='/projekt2/remsens/data_new/site-campaign/rv_meteor-eurec4a/instruments/RV-METEOR_DSHIP', **kwargs)[source]¶ Read in daily Seapath measurements from RV Meteor from .dat files to a pandas.DataFrame :param date: object with date of current file :type date: datetime.datetime :param path: path to seapath files :type path: str :param kwargs for read_csv: output_format (str): whether a pandas data frame or a xarray dataset is returned
Returns: DataFrame with Seapath measurements Return type: seapath (DataFrame)
-
pyLARDA.SpectraProcessing.
read_dship
(date, **kwargs)[source]¶ Read in 1 Hz DSHIP data and return pandas DataFrame
Parameters: - date (str) – yyyymmdd (eg. 20200210)
- **kwargs – kwargs for pd.read_csv (not all implemented) https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
Returns: pd.DataFrame with 1 Hz DSHIP data
-
pyLARDA.SpectraProcessing.
f_shiftTimeDataset
(dataset)[source]¶ author: Claudia Acquistapace date: 25 november 2020 goal : function to shift time variable of the dataset to the central value of the time interval of the time step input:
dataset: xarray dataset- output:
- dataset: xarray dataset with the time coordinate shifted added to the coordinates and the variables now referring to the shifted time array
-
pyLARDA.SpectraProcessing.
calc_heave_rate
(seapath, x_radar=-11, y_radar=4.07, z_radar=15.8, only_heave=False, use_cross_product=True, transform_to_earth=True)[source]¶ Calculate heave rate at a certain location of a ship with the measurements of the INS
Parameters: - seapath (pd.DataFrame) – Data frame with heading, roll, pitch and heave as columns
- x_radar (float) – x position of location with respect to INS in meters
- y_radar (float) – y position of location with respect to INS in meters
- z_radar (float) – z position of location with respect to INS in meters
- only_heave (bool) – whether to use only heave to calculate the heave rate or include pitch and roll induced heave
- use_cross_product (bool) – whether to use the cross product like Hannes Griesche https://doi.org/10.5194/amt-2019-434
- transform_to_earth (bool) – transform cross product to earth coordinate system as described in https://repository.library.noaa.gov/view/noaa/17400
Returns: Data frame as input with additional columns radar_heave, pitch_heave, roll_heave and “heave_rate”
Return type: seapath (pd.DataFrame)
-
pyLARDA.SpectraProcessing.
f_calcRMatrix
(rollShipArr, pitchShipArr, yawShipArr, NtimeShip)[source]¶ author: Claudia Acquistapace date : 27/10/2020 goal: function to calculate R matrix given roll, pitch, yaw input:
rollShipArr: roll array in degrees pitchShipArr: pitch array in degrees yawShipArr: yaw array in degrees NtimeShip: dimension of time array for the definition of R_inv as [3,3,dimTime]- output:
- R[3,3,Dimtime]: array of rotational matrices, one for each time stamp
-
pyLARDA.SpectraProcessing.
calc_heave_rate_claudia
(data, x_radar=-11, y_radar=4.07, z_radar=-15.8)[source]¶ Calculate heave rate at a certain location on a ship according to Claudia Acquistapace’s approach
Parameters: - data (xr.DataSet) – Data Set with heading, roll, pitch and heave as columns
- x_radar (float) – x position of location with respect to INS in meters
- y_radar (float) – y position of location with respect to INS in meters
- z_radar (float) – z position of location with respect to INS in meters
Returns: xr.DataSet with additional variable heave_rate
-
pyLARDA.SpectraProcessing.
find_mdv_time_series
(mdv_values, radar_time, n_ts_run)[source]¶ author: Claudia Acquistapace, Johannes Roettenbacher Identify, given a mean doppler velocity matrix, a sequence of length n_ts_run of values in the matrix at a given height that contains the minimum possible amount of nan values in it.
Parameters: - mdv_values (ndarray) – time x heigth matrix of Doppler Velocity
- radar_time (ndarray) – corresponding radar time stamps in seconds (unix time)
- n_ts_run (int) – number of timestamps needed in a mdv series
Returns: time series of Doppler velocity with length n_ts_run time_series (ndarray): corresponding time stamps to Doppler velocity time series i_height_sel (int): index of chosen height valuesColumnMean (ndarray): time series of mean Doppler velocity averaged over height with length n_ts_run
Return type: valuesTimeSerie (ndarray)
-
pyLARDA.SpectraProcessing.
calc_time_shift
(w_radar_meanCol, delta_t_min, delta_t_max, resolution, w_ship_chirp, timeSerieRadar, pathFig, chirp, hour, date)[source]¶ author: Claudia Acquistapace, Jan. H. Schween, Johannes Roettenbacher goal: calculate and estimation of the time lag between the radar time stamps and the ship time stamp
NOTE: adding or subtracting the obtained time shift depends on what you did during the calculation of the covariances: if you added/subtracted time _shift to t_radar you have to do the same for the ‘exact time’ Here is the time shift analysis as plot: <ww> is short for <w’_ship*w’_radar> i.e. covariance between vertical speeds from ship movements and radar its maximum gives an estimate for optimal agreement in vertical velocities of ship and radar <Delta w^2> is short for <(w[i]-w[i-1])^2> where w = w_rad - 2*w_ship - this is a measure for the stripeness. Its minimum gives an estimate how to get the smoothest w data :param w_radar_meanCol: time series of mean Doppler velocity averaged over height with no nan values :type w_radar_meanCol: ndarray :param delta_t_min: minimum time shift :type delta_t_min: float :param delta_t_max: maximum time shift :type delta_t_max: float :param resolution: time step by which to increment possible time shift :type resolution: float :param w_ship_chirp: vertical velocity of the radar at the exact chirp time step :type w_ship_chirp: ndarray :param timeSerieRadar: time stamps of the mean Doppler velocity time series (w_radar_meanCol) :type timeSerieRadar: ndarray :param pathFig: file path where figures should be stored :type pathFig: str :param chirp: which chirp is being processed :type chirp: int :param hour: which hour of the day is being processed (0-23) :type hour: int :param date: which day is being processed :type date: datetime
Returns: time shift between radar data and ship data in seconds, quicklooks for each calculation
-
pyLARDA.SpectraProcessing.
calc_chirp_timestamps
(radar_ts, date, version)[source]¶ Calculate the exact timestamp for each chirp corresponding with the center or start of the chirp The timestamp in the radar file corresponds to the end of a chirp sequence with an accuracy of 0.1 s
Parameters: - radar_ts (ndarray) – timestamps of the radar with milliseconds in seconds
- date (datetime.datetime) – date which is being processed
- version (str) – should the timestamp correspond to the ‘center’ or the ‘start’ of the chirp
Returns: dict with chirp timestamps
-
pyLARDA.SpectraProcessing.
calc_shifted_chirp_timestamps
(radar_ts, radar_mdv, chirp_ts, rg_borders_id, n_ts_run, Cs_w_radar, **kwargs)[source]¶ Calculates the time shift between each chirp time stamp and the ship time stamp for every hour and every chirp. :param radar_ts: radar time stamps in seconds (unix time) :type radar_ts: ndarray :param radar_mdv: time x height matrix of mean Doppler velocity from radar :type radar_mdv: ndarray :param chirp_ts: exact chirp time stamps :type chirp_ts: ndarray :param rg_borders_id: indices of chirp boundaries :type rg_borders_id: ndarray :param n_ts_run: number of time steps necessary for mean Doppler velocity time series :type n_ts_run: int :param Cs_w_radar: function of vertical velocity of radar against time :type Cs_w_radar: scipy.interpolate.CubicSpline :param **kwargs: no_chirps (int): number of chirps in radar measurement
plot_fig (bool): plot quicklookReturns: time shifted chirp time stamps, array with time shifts for each chirp and hour
-
pyLARDA.SpectraProcessing.
calc_corr_matrix_claudia
(radar_ts, radar_rg, rg_borders_id, chirp_ts_shifted, Cs_w_radar)[source]¶ Calculate the correction matrix to correct the mean Doppler velocity for the ship vertical motion. :param radar_ts: original radar time stamps in seconds (unix time) :type radar_ts: ndarray :param radar_rg: radar range gates :type radar_rg: ndarray :param rg_borders_id: indices of chirp boundaries :type rg_borders_id: ndarray :param chirp_ts_shifted: hourly shifted chirp time stamps :type chirp_ts_shifted: dict :param Cs_w_radar: function of vertical velocity of radar against time :type Cs_w_radar: scipy.interpolate.CubicSpline
Returns: correction matrix for mean Doppler velocity
-
pyLARDA.SpectraProcessing.
get_range_bin_borders
(no_chirps, container)[source]¶ get the range bins which correspond to the chirp borders of a FMCW radar
Parameters: - no_chirps (int) – Number of chirps
- container (dict) – Dictionary with C1/2/3Range variable from LV1 files
Returns: ndarray with chirp borders including 0 range_bins
-
pyLARDA.SpectraProcessing.
calc_heave_corr
(container, chirp_ts, seapath, mean_hr=True)[source]¶ Calculate heave correction for mean Doppler velocity
Parameters: - container (larda container) – LIMRAD94 C1/2/3_Range, SeqIntTime, ts
- chirp_ts (dict) – dictionary with exact radar chirp time stamps
- seapath (pd.DataFrame) – Data frame with heave rate column (“heave_rate_radar”)
- mean_hr (bool) – whether to use the mean heave rate over the SeqIntTime or the heave rate at the start time of the chirp
Returns: heave rate closest to each radar timestep for each height bin, time x range
Return type: heave_corr (ndarray)
-
pyLARDA.SpectraProcessing.
calc_dopp_res
(MaxVel, DoppLen, no_chirps, range_bins)[source]¶ Parameters: - MaxVel (ndarray) – Unambiguous Doppler velocity (+/-) m/s from LV1 file
- DoppLen (ndarray) – Number of spectral lines in Doppler spectra from LV1 file
- no_chirps (int) – Number of chirps
- range_bins (ndarray) – range bin number of lower chirp borders, starts with 0
Returns: 1D array with Doppler resolution for each height bin
-
pyLARDA.SpectraProcessing.
heave_rate_to_spectra_bins
(heave_corr, doppler_res)[source]¶ translate the heave correction to Doppler spectra bins
Parameters: - heave_corr (ndarray) – heave rate closest to each radar timestep for each height bin, time x range
- doppler_res (ndarray) – Doppler resolution of each chirp of LIMRAD94 for whole range 1 x range
Returns: ndarray with number of bins to move each Doppler spectrum
- n_dopp_bins_shift (ndarray): of same dimension as heave_corr
- heave_corr
-
pyLARDA.SpectraProcessing.
shift_seapath
(seapath, shift)[source]¶ Shift seapath values by given shift
Parameters: - seapath (pd.Dataframe) – Dataframe with heave motion of RV-Meteor
- shift (int) – number of time steps to shift data
Returns: shifted Dataframe
-
pyLARDA.SpectraProcessing.
find_closest_timesteps
(df, ts)[source]¶ Find closest time steps in a dataframe to a time series
Parameters: - df (pd.DataFrame) – DataFrame with DatetimeIndex
- ts (ndarray) – array with time stamps in unix format (seconds since 1-1-1970)
Returns: pd.DataFrame with only the closest time steps to ts
-
pyLARDA.SpectraProcessing.
spectra2sldr
(ZSpec, paraminfo, **kwargs)[source]¶ This routine calculates the
Parameters: - ZSpec (dict) – list containing the dicts for each chrip of RPG-FMCW Doppler cloud radar
- paraminfo (dict) – information from params_[campaign].toml for the system LIMRAD94
Returns: dictionary of larda containers, including larda container for Ze, VEL, sw, skew, kurt
Return type: container_dict (dict)
-
pyLARDA.SpectraProcessing.
spectra2polarimetry
(ZSpec, paraminfo, **kwargs)[source]¶ This routine calculates the
Parameters: - ZSpec (dict) – list containing the dicts for each chrip of RPG-FMCW Doppler cloud radar
- paraminfo (dict) – information from params_[campaign].toml for the system LIMRAD94
Returns: dictionary of larda containers, including larda container for Ze, VEL, sw, skew, kurt
Return type: container_dict (dict)