bin.MarsVars

The MarsVars executable is for performing variable manipulations in existing files. Most often, it is used to derive and add variables to existing files, but it also differentiates variables with respect to (w.r.t) the Z axis, column-integrates variables, converts aerosol opacities from opacity per Pascal to opacity per meter, removes and extracts variables from files, and enables scaling variables or editing variable names, units, etc.

The executable requires:

  • [input_file] The file to be transformed

and optionally accepts:

  • [-add --add_variable] Derive and add variable to file

  • [-zdiff --differentiate_wrt_z] Differentiate variable w.r.t. Z axis

  • [-col --column_integrate] Column-integrate variable

  • [-zd --zonal_detrend] Subtract zonal mean from variable

  • [-to_dz --dp_to_dz] Convert aerosol opacity op/Pa -> op/m

  • [-to_dp --dz_to_dp] Convert aerosol opacity op/m -> op/Pa

  • [-rm --remove_variable] Remove variable from file

  • [-extract --extract_copy] Copy variable to new file

  • [-edit --edit_variable] Edit variable attributes or scale it

Third-party Requirements:

  • sys

  • argparse

  • os

  • warnings

  • re

  • numpy

  • netCDF4

  • shutil

  • functools

  • traceback

  • matplotlib

  • time

  • io

  • locale

  • amescap

Module Contents

Functions

add_help(var_list)

Create a help string for the add_variable argument.

check_dependencies(f, var, master_list[, add_missing, ...])

Check for variable dependencies in a file, add missing dependencies.

check_variable_exists(var_name, file_vars)

Check if a variable exists in a file.

compute_DP_3D(ps, ak, bk, shape_out)

Calculate the thickness of a layer in pressure units.

compute_DZ_3D(ps, ak, bk, temp, shape_out)

Calculate the thickness of a layer in altitude units.

compute_DZ_full_pstd(pstd, T[, ftype])

Calculate layer thickness.

compute_Ek(ucomp, vcomp)

Calculate wave kinetic energy

compute_Ep(temp)

Calculate wave potential energy.

compute_MF(UVcomp, w)

Calculate zonal or meridional momentum fluxes.

compute_N(theta, zfull)

Calculate the Brunt Vaisala freqency.

compute_Tco2(P_3D)

Calculate the frost point of CO2.

compute_Vg_sed(xTau, nTau, T)

Calculate the sedimentation rate of the dust.

compute_WMFF(MF, rho, lev, interp_type)

Calculate the zonal or meridional wave-mean flow forcing.

compute_dustref_per_pa(dustref, delp)

Computes visible dust opacity per Pascal from dustref and delp.

compute_dustref_per_z(dustref, delz)

Computes visible dust opacity per kilometer from dustref and delz.

compute_mmr(xTau, temp, lev, const, f_type)

Compute the dust or ice mixing ratio.

compute_p_3D(ps, ak, bk, shape_out)

Compute the 3D pressure at layer midpoints.

compute_rho(p_3D, temp)

Compute density.

compute_scorer(N, ucomp, zfull)

Calculate the Scorer wavelength.

compute_theta(p_3D, ps, T, f_type)

Compute the potential temperature.

compute_w(rho, omega)

Compute the vertical wind using the omega equation.

compute_w_net(Vg, wvar)

Computes the net vertical wind.

compute_xzTau(q, temp, lev, const, f_type)

Compute the dust or ice extinction rate.

compute_zfull(ps, ak, bk, T)

Calculate the altitude of the layer midpoints above ground level.

compute_zhalf(ps, ak, bk, T)

Calculate the altitude of the layer interfaces above ground level.

debug_wrapper(func)

A decorator that wraps a function with error handling

ensure_file_closed(filepath[, delay])

Try to ensure a file is not being accessed by the system.

force_close_netcdf_files(file_or_dir[, delay])

Aggressively try to ensure netCDF files are closed on Windows systems.

get_existing_var_name(var_name, file_vars)

Get the actual variable name that exists in the file.

main()

Main function for variable manipulations in NetCDF files.

patched_print_message(self, message[, file])

Patched version of _print_message that handles Unicode encoding errors.

process_add_variables(file_name, add_list, master_list)

Process a list of variables to add.

safe_copy_replace(src_file, dst_file[, max_attempts, ...])

Windows-specific approach to copy file contents and replace destination.

safe_move_file(src_file, dst_file[, max_attempts, delay])

Safely move a file with retries for Windows file locking issues.

safe_print(text)

Print text safely, handling encoding issues on Windows.

safe_remove_file(filepath[, max_attempts, delay])

Safely remove a file with retries for Windows file locking issues

Attributes

C_dst

C_ice

Cp

Kb

M_co2

N

Na

Qext_dst

Qext_ice

R

Rd

Reff_dst

Reff_ice

S0

T0

Tpole

amu

amu_co2

args

cap_str

debug

exit_code

filepath

fill_value

g

mass_co2

master_list

n0

original_print_message

parser

psrf

rgas

rho_air

rho_dst

rho_ice

sigma

add_help(var_list)

Create a help string for the add_variable argument.

Parameters:

var_list (dict) – Dictionary of variables and their attributes

Returns:

Formatted help string

Return type:

str

check_dependencies(f, var, master_list, add_missing=True, dependency_chain=None)

Check for variable dependencies in a file, add missing dependencies.

Parameters:
  • f – NetCDF file object

  • var – Variable to check deps. for

  • master_list – Dict of supported vars and their deps.

  • add_missing – Whether to try adding missing deps. (default: True)

  • dependency_chain – List of vars in the current dep. chain (for detecting cycles)

Returns:

True if all deps. are present or successfully added, False otherwise

Raises:
  • RuntimeError – If the variable is not in the master list

  • Exception – If any other error occurs

check_variable_exists(var_name, file_vars)

Check if a variable exists in a file.

Considers alternative naming conventions.

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

  • file_vars (set) – Set of variable names in the file

Returns:

True if the variable exists, False otherwise

Return type:

bool

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_DP_3D(ps, ak, bk, shape_out)

Calculate the thickness of a layer in pressure units.

Parameters:
  • ps (array [time, lat, lon]) – Surface pressure (Pa)

  • ak (array [phalf]) – Vertical coordinate pressure value (Pa)

  • bk (array [phalf]) – Vertical coordinate sigma value (None)

  • shape_out (float) – Determines how to handle the dimensions of DP_3D. If len(time) = 1 (one timestep), DP_3D is returned as [1, lev, lat, lon] as opposed to [lev, lat, lon]

Returns:

DP Layer thickness in pressure units (Pa)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_DZ_3D(ps, ak, bk, temp, shape_out)

Calculate the thickness of a layer in altitude units.

Parameters:
  • ps (array [time, lat, lon]) – Surface pressure (Pa)

  • ak (array [phalf]) – Vertical coordinate pressure value (Pa)

  • bk (array [phalf]) – Vertical coordinate sigma value (None)

  • shape_out (float) – Determines how to handle the dimensions of DZ_3D. If len(time) = 1 (one timestep), DZ_3D is returned as [1, lev, lat, lon] as opposed to [lev, lat, lon]

Returns:

DZ Layer thickness in altitude units (m)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_DZ_full_pstd(pstd, T, ftype='average')

Calculate layer thickness.

Computes from the midpoint of the standard pressure levels (pstd).

In this context, pfull=pstd with the layer interfaces defined somewhere in between successive layers:

--- Nk --- TOP       ========  phalf
--- Nk-1 ---
                     --------  pfull = pstd    ^
                                               | DZ_full_pstd
                     ========  phalf           |
--- 1 ---            --------  pfull = pstd    v
--- 0 --- SFC        ========  phalf
                      / / / /
Parameters:
  • pstd (array [lev]) – Vertical coordinate (pstd; Pa)

  • T (array [time, lev, lat, lon]) – Temperature (K)

  • f_type – The FV3 file type: diurn, daily, or average

Returns:

DZ_full_pstd, Layer thicknesses (Pa)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

  • RuntimeError – If the layer thickness calculation fails

  • ZeroDivisionError – If the temperature is zero

compute_Ek(ucomp, vcomp)

Calculate wave kinetic energy

Calculation:

Ek = 1/2 (u'**2+v'**2)
Parameters:
  • ucomp (array [time, lev, lat, lon]) – Zonal wind (m/s)

  • vcomp (array [time, lev, lat, lon]) – Meridional wind (m/s)

Returns:

Ek Wave kinetic energy (J/kg)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_Ep(temp)

Calculate wave potential energy.

Calculation:

Ep = 1/2 (g/N)^2 (temp'/temp)^2
Parameters:

temp (array [time, lev, lat, lon]) – Temperature (K)

Returns:

Ep Wave potential energy (J/kg)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_MF(UVcomp, w)

Calculate zonal or meridional momentum fluxes.

Parameters:
  • UVcomp (array) – Zonal or meridional wind (ucomp or vcomp)(m/s)

  • w (array [time, lev, lat, lon]) – Vertical wind (m/s)

Returns:

u'w' or v'w', Zonal/meridional momentum flux (J/kg)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_N(theta, zfull)

Calculate the Brunt Vaisala freqency.

Parameters:
  • theta (array [time, lev, lat, lon]) – Potential temperature (K)

  • zfull (array [time, lev, lat, lon]) – Altitude above ground level at the layer midpoint (m)

Returns:

N, Brunt Vaisala freqency [rad/s]

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_Tco2(P_3D)

Calculate the frost point of CO2.

Adapted from Fannale (1982) - Mars: The regolith-atmosphere cap system and climate change. Icarus.

Parameters:

P_3D – The full 3D pressure array (Pa)

Returns:

CO2 frost point [K]

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_Vg_sed(xTau, nTau, T)

Calculate the sedimentation rate of the dust. [Courtney Batterson, 2023]

Parameters:
  • xTau (array [time, lev, lat, lon]) – Dust or ice MASS mixing ratio (ppm)

  • nTau (array [time, lev, lat, lon]) – Dust or ice NUMBER mixing ratio (None)

  • T (array [time, lev, lat, lon]) – Temperature (K)

Returns:

Vg Dust sedimentation rate (m/s)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

  • RuntimeError – If the sedimentation rate calculation fails

compute_WMFF(MF, rho, lev, interp_type)

Calculate the zonal or meridional wave-mean flow forcing.

Calculation:

ax = -1/rho d(rho u'w')/dz
ay = -1/rho d(rho v'w')/dz

If interp_type == pstd, then:

[du/dz = (du/dp).(dp/dz)] > [du/dz = -rho*g * (du/dp)]

where:

dp/dz = -rho*g
[du/dz = (du/dp).(-rho*g)] > [du/dz = -rho*g * (du/dp)]
Parameters:
  • MF (array [time, lev, lat, lon]) – Zonal/meridional momentum flux (J/kg)

  • rho (array [time, lev, lat, lon]) – Atmospheric density (kg/m^3)

  • lev (array [lev]) – Array for the vertical grid (zagl, zstd, pstd, or pfull)

  • interp_type (str) – The vertical grid type (zagl, zstd, pstd, or pfull)

Returns:

The zonal or meridional wave-mean flow forcing (m/s2)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

  • RuntimeError – If the wave-mean flow forcing calculation fails

  • ZeroDivisionError – If rho is zero

compute_dustref_per_pa(dustref, delp)

Computes visible dust opacity per Pascal from dustref and delp. dustref is visible dust opacity per level (model layer).

opacity per Pa = opacity per layer / layer thickness in Pa:

dustref_per_pa = dustref/delp

[Courtney Batterson, 2025]

Parameters:
  • dustref (array [time, lev, lat, lon]) – Visible dust opacity [op/model layer]

  • delp (array [time, lev, lat, lon]) – Layer thickness [Pa]

Returns:

dustref_per_pa Visible dust opacity [op/Pa]

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_dustref_per_z(dustref, delz)

Computes visible dust opacity per kilometer from dustref and delz. dustref is visible dust opacity per level (model layer).

opacity per km = opacity per layer / layer thickness in m * 1000:

dustref_per_z = dustref/delz*1000

[Courtney Batterson, 2025]

Parameters:
  • dustref (array [time, lev, lat, lon]) – Visible dust opacity [op/model layer]

  • delz (array [time, lev, lat, lon]) – Layer thickness [m]

Returns:

dustref_per_z Visible dust opacity [op/km]

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_mmr(xTau, temp, lev, const, f_type)

Compute the dust or ice mixing ratio.

Adapted from Heavens et al. (2011) observations from MCS (JGR). [Courtney Batterson, 2023]

Parameters:
  • xTau (array [time, lev, lat, lon]) – Dust or ice extinction rate (km-1)

  • temp (array [time, lev, lat, lon]) – Temperature (K)

  • lev (array [lev]) – Vertical coordinate (e.g., pstd) (e.g., Pa)

  • const (array) – Dust or ice constant

  • f_type – The FV3 file type: diurn, daily, or average

Returns:

q, Dust or ice mass mixing ratio (ppm)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

  • RuntimeError – If the mixing ratio calculation fails

compute_p_3D(ps, ak, bk, shape_out)

Compute the 3D pressure at layer midpoints.

Parameters:
  • ps (array [time, lat, lon]) – Surface pressure (Pa)

  • ak (array [phalf]) – Vertical coordinate pressure value (Pa)

  • bk (array [phalf]) – Vertical coordinate sigma value (None)

  • shape_out (float) – Determines how to handle the dimensions of p_3D. If len(time) = 1 (one timestep), p_3D is returned as [1, lev, lat, lon] as opposed to [lev, lat, lon]

Returns:

p_3D The full 3D pressure array (Pa)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

  • RuntimeError – If the pressure calculation fails

compute_rho(p_3D, temp)

Compute density.

Parameters:
  • p_3D (array [time, lev, lat, lon]) – Pressure (Pa)

  • temp (array [time, lev, lat, lon]) – Temperature (K)

Returns:

Density (kg/m^3)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_scorer(N, ucomp, zfull)

Calculate the Scorer wavelength.

Parameters:
  • N (float [time, lev, lat, lon]) – Brunt Vaisala freqency (rad/s)

  • ucomp (array [time, lev, lat, lon]) – Zonal wind (m/s)

  • zfull (array [time, lev, lat, lon]) – Altitude above ground level at the layer midpoint (m)

Returns:

scorer_wl Scorer horizontal wavelength (m)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_theta(p_3D, ps, T, f_type)

Compute the potential temperature.

Parameters:
  • p_3D (array [time, lev, lat, lon]) – The full 3D pressure array (Pa)

  • ps (array [time, lat, lon]) – Surface pressure (Pa)

  • T (array [time, lev, lat, lon]) – Temperature (K)

  • f_type (str) – The FV3 file type: diurn, daily, or average

Returns:

Potential temperature (K)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_w(rho, omega)

Compute the vertical wind using the omega equation.

Under hydrostatic balance, omega is proportional to the vertical wind velocity (w):

omega = dp/dt = (dp/dz)(dz/dt) = (dp/dz) * w

Under hydrostatic equilibrium:

dp/dz = -rho * g

So omega can be calculated as:

omega = -rho * g * w
Parameters:
  • rho (array [time, lev, lat, lon]) – Atmospheric density (kg/m^3)

  • omega (array [time, lev, lat, lon]) – Rate of change in pressure at layer midpoint (Pa/s)

Returns:

vertical wind (m/s)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

  • RuntimeError – If the vertical wind calculation fails

  • ZeroDivisionError – If rho or omega is zero

  • OverflowError – If the calculation results in an overflow

  • Exception – If any other error occurs

compute_w_net(Vg, wvar)

Computes the net vertical wind.

w_net = vertical wind (w) - sedimentation rate (Vg_sed):

w_net = w - Vg_sed

[Courtney Batterson, 2023]

Parameters:
  • Vg (array [time, lev, lat, lon]) – Dust sedimentation rate (m/s)

  • wvar (array [time, lev, lat, lon]) – Vertical wind (m/s)

Returns:

w_net Net vertical wind speed (m/s)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_xzTau(q, temp, lev, const, f_type)

Compute the dust or ice extinction rate.

Adapted from Heavens et al. (2011) observations from MCS (JGR). [Courtney Batterson, 2023]

Parameters:
  • q (array [time, lev, lat, lon]) – Dust or ice mass mixing ratio (ppm)

  • temp (array [time, lev, lat, lon]) – Temperature (K)

  • lev (array [lev]) – Vertical coordinate (e.g., pstd) (e.g., Pa)

  • const (array) – Dust or ice constant

  • f_type – The FV3 file type: diurn, daily, or average

Returns:

xzTau Dust or ice extinction rate (km-1)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

  • RuntimeError – If the extinction rate calculation fails

compute_zfull(ps, ak, bk, T)

Calculate the altitude of the layer midpoints above ground level.

Parameters:
  • ps (array [time, lat, lon]) – Surface pressure (Pa)

  • ak (array [phalf]) – Vertical coordinate pressure value (Pa)

  • bk (array [phalf]) – Vertical coordinate sigma value (None)

  • T (array [time, lev, lat, lon]) – Temperature (K)

Returns:

zfull (m)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

compute_zhalf(ps, ak, bk, T)

Calculate the altitude of the layer interfaces above ground level.

Parameters:
  • ps (array [time, lat, lon]) – Surface pressure (Pa)

  • ak (array [phalf]) – Vertical coordinate pressure value (Pa)

  • bk (array [phalf]) – Vertical coordinate sigma value (None)

  • T (array [time, lev, lat, lon]) – Temperature (K)

Returns:

zhalf (m)

Return type:

array [time, lev, lat, lon]

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

debug_wrapper(func)

A decorator that wraps a function with error handling based on the –debug flag. If the –debug flag is set, it prints the full traceback of any exception that occurs. Otherwise, it prints a simplified error message.

Parameters:

func (function) – The function to wrap.

Returns:

The wrapped function.

Return type:

function

Raises:
  • Exception – If an error occurs during the function call.

  • TypeError – If the function is not callable.

  • ValueError – If the function is not found.

  • NameError – If the function is not defined.

  • AttributeError – If the function does not have the specified attribute.

  • ImportError – If the function cannot be imported.

  • RuntimeError – If the function cannot be run.

  • KeyError – If the function does not have the specified key.

  • IndexError – If the function does not have the specified index.

  • IOError – If the function cannot be opened.

  • OSError – If the function cannot be accessed.

  • EOFError – If the function cannot be read.

  • MemoryError – If the function cannot be allocated.

  • OverflowError – If the function cannot be overflowed.

  • ZeroDivisionError – If the function cannot be divided by zero.

  • StopIteration – If the function cannot be stopped.

  • KeyboardInterrupt – If the function cannot be interrupted.

  • SystemExit – If the function cannot be exited.

  • AssertionError – If the function cannot be asserted.

ensure_file_closed(filepath, delay=0.5)

Try to ensure a file is not being accessed by the system.

This is especially helpful for Windows environments.

Parameters:
  • filepath – Path to the file

  • delay – Delay in seconds to wait for handles to release

Returns:

None

Return type:

None

Raises:
  • FileNotFoundError – If the file does not exist

  • OSError – If the file is locked or cannot be accessed

  • Exception – If any other error occurs

  • TypeError – If the filepath is not a string

  • ValueError – If the filepath is empty

  • RuntimeError – If the file cannot be closed

force_close_netcdf_files(file_or_dir, delay=1.0)

Aggressively try to ensure netCDF files are closed on Windows systems.

Parameters:
  • file_or_dir – Path to the file or directory to process

  • delay – Delay in seconds after forcing closure

Returns:

None

Return type:

None

Raises:
  • FileNotFoundError – If the file or directory does not exist

  • OSError – If the file is locked or cannot be accessed

  • Exception – If any other error occurs

  • TypeError – If the file_or_dir is not a string

  • ValueError – If the file_or_dir is empty

  • RuntimeError – If the file or directory cannot be processed

  • ImportError – If the netCDF4 module is not available

  • AttributeError – If the netCDF4 module does not have the required attributes

  • Exception – If any other error occurs

get_existing_var_name(var_name, file_vars)

Get the actual variable name that exists in the file.

Considers alternative naming conventions.

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

  • file_vars (set) – Set of variable names in the file

Returns:

Actual variable name in the file

Return type:

str

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

main()

Main function for variable manipulations in NetCDF files.

This function performs a sequence of operations on one or more NetCDF files, as specified by command-line arguments. The operations include removing variables, extracting variables, adding variables, vertical differentiation, zonal detrending, opacity conversions, column integration, and editing variable metadata or values.

Workflow:
  • Iterates over all input NetCDF files.

  • For each file, performs the following operations as requested by arguments:

    • Remove specified variables and update the file.

    • Extract specified variables into a new file.

    • Add new variables using provided methods.

    • Compute vertical derivatives of variables with respect to height or pressure.

    • Remove zonal mean (detrend) from specified variables.

    • Convert variables between dp/dz and dz/dp representations.

    • Perform column integration of variables.

    • Edit variable metadata (name, long_name, units) or scale values.

Arguments:
args: Namespace

Parsed command-line arguments specifying which operations to perform and their parameters.

master_list: list

List of available variables and their properties (used for adding variables).

debug: bool

If True, prints detailed error messages and stack traces.

Notes:
  • Handles both Unix and Windows file operations for safe file

replacement. - Uses helper functions for NetCDF file manipulation, variable existence checks, and error handling. - Assumes global constants and utility functions (e.g., Dataset, Ncdf, check_file_tape, etc.) are defined elsewhere. - Uses global variables lev_T and lev_T_out for axis manipulation in vertical operations.

Raises:

Exceptions are caught and logged for each operation; files are cleaned up on error.

patched_print_message(self, message, file=None)

Patched version of _print_message that handles Unicode encoding errors.

Parameters:
  • self – The ArgumentParser instance

  • message – The message to print

  • file (file-like object) – The file to print to (default is sys.stdout)

Returns:

None

Return type:

None

Raises:
  • UnicodeEncodeError – If the message cannot be encoded

  • TypeError – If the message is not a string

  • ValueError – If the message is empty

  • Exception – If any other error occurs

  • RuntimeError – If the message cannot be printed

process_add_variables(file_name, add_list, master_list, debug=False)

Process a list of variables to add.

Dependent variables are added in the correct order. If a variable is already in the file, it is skipped. If a variable cannot be added, an error message is printed.

Parameters:
  • file_name – Input file path

  • add_list – List of variables to add

  • master_list – Dictionary of supported variables and their dependencies

  • debug (bool) – Whether to show debug information

Raises:
  • ValueError – If the input dimensions are not compatible

  • TypeError – If the input types are not compatible

  • Exception – If any other error occurs

  • RuntimeError – If the variable cannot be added

safe_copy_replace(src_file, dst_file, max_attempts=5, delay=1.0)

Windows-specific approach to copy file contents and replace destination.

This avoids move operations which are more likely to fail with locking

Parameters:
  • src_file – Source file path

  • dst_file – Destination file path

  • max_attempts – Maximum number of retry attempts

  • delay – Base delay between attempts (increases with retries)

Returns:

True if successful, False otherwise

Return type:

bool

Raises:
  • FileNotFoundError – If the source file does not exist

  • OSError – If the file is locked or cannot be accessed

  • Exception – If any other error occurs

  • TypeError – If the src_file or dst_file is not a string

  • ValueError – If the src_file or dst_file is empty

  • RuntimeError – If the file cannot be copied or replaced

safe_move_file(src_file, dst_file, max_attempts=5, delay=1)

Safely move a file with retries for Windows file locking issues.

Parameters:
  • src_file – Source file path

  • dst_file – Destination file path

  • max_attempts – Number of attempts to make

  • delay – Delay between attempts in seconds

Returns:

True if successful, False otherwise

Return type:

bool

Raises:
  • FileNotFoundError – If the source file does not exist

  • OSError – If the file is locked or cannot be accessed

  • Exception – If any other error occurs

  • TypeError – If the src_file or dst_file is not a string

  • ValueError – If the src_file or dst_file is empty

  • RuntimeError – If the file cannot be moved

safe_print(text)

Print text safely, handling encoding issues on Windows.

Parameters:

text (str) – Text to print

Returns:

None

Return type:

None

Raises:
  • UnicodeEncodeError – If the text cannot be encoded

  • TypeError – If the text is not a string

  • ValueError – If the text is empty

  • Exception – If any other error occurs

  • RuntimeError – If the text cannot be printed

safe_remove_file(filepath, max_attempts=5, delay=1)

Safely remove a file with retries for Windows file locking issues

Parameters:
  • filepath – Path to the file to remove

  • max_attempts – Number of attempts to make

  • delay – Delay between attempts in seconds

Returns:

True if successful, False otherwise

Return type:

bool

Raises:
  • FileNotFoundError – If the file does not exist

  • OSError – If the file is locked or cannot be accessed

  • Exception – If any other error occurs

  • TypeError – If the filepath is not a string

  • ValueError – If the filepath is empty

  • RuntimeError – If the file cannot be removed

C_dst
C_ice
Cp = 735.0
Kb
M_co2 = 0.044
N = 0.01
Na
Qext_dst = 0.35
Qext_ice = 0.773
R = 8.314
Rd = 192.0
Reff_dst = 1.06
Reff_ice = 1.41
S0 = 222
T0 = 273.15
Tpole = 150.0
amu
amu_co2 = 44.0
args
cap_str = ' (derived w/CAP)'
debug
exit_code
filepath
fill_value = 0.0
g = 3.72
mass_co2
master_list
n0
original_print_message
parser
psrf = 610.0
rgas = 189.0
rho_air
rho_dst = 2500.0
rho_ice = 900
sigma = 0.63676