Creates an anonymous action client node so a single call to the action
  server can be sent.
  kwargs -- parameters of the action's goal


Adds two vectors
  a -- geometry_msgs Vector3 or Point
  b -- geometry_msgs Vector3 or Point
  returns a Vector3 that represents a + b


Subtracts two vectors
  a -- geometry_msgs Vector3 or Point
  b -- geometry_msgs Vector3 or Point
  returns a Vector3 that represents a - b


Computes the multiplication of the scalar a to the vector b
  a -- float
  b -- geometry_msgs Vector3 or Point
  returns a vector that is the result of ab


Compute the inverse of a quaternion
  a -- geometry_msgs Quaternion
  returns the quaternion inverse of a


Compute the product of two quaternions multiplied together (a * b)
  a -- geometry_msgs Quaternion
  b -- geometry_msgs Quaternion
  returns quaternion product of a and b


Perform a passive rotation of a vector using a quaternion
  q -- geometry_msgs Quaternion -- Should be a unit quaternion
  v -- geometry_msgs Pointer/Vector3
  returns v rotated by q as the same type as v


Computes dot product between vectors/Quaternions a and b (a * b)
  a -- geometry_msgs Vector3, Point, or Quaternions
  b -- geometry_msgs Vector3, Point, or Quaternions
  returns a float that is the result of a * b


Computes the cross product between vectors a and b (a x b)
  a -- geometry_msgs Vector3 or Point
  b -- geometry_msgs Vector3 or Point
  returns a vector that is the result of a x b


Computes the squared norm (or length) of a vector or quaternion
  v -- geometry_msgs Vector3, Point, or Quaternion
  returns the squared norm of v


Computes the norm (or length) of a vector or quaternion
  v -- geometry_msgs Vector3, Point, or Quaternion
  returns the norm of v


Normalizes a vector or quaternion
  v -- geometry_msgs Vector3, Point, or Quaternion
  returns the normalized version of v


Normalization check
  v -- geometry_msgs Vector3 or Point
  returns true if v is normalized


Compute the distance between vectors a and b, same as norm(b - a)
  a -- geometry_msgs Vector3 or Point
  b -- geometry_msgs Vector3 or Point
  returns a float that represents the distance between two vectors


Returns an orthogonal vector to v
  v -- geometry_msgs Vector3 or Point
  returns the orthogonal vector of v


A version of tf.transformation's quaternion_from_euler that returns a
  geometry_msgs Quaternion
  x -- Radian rotation around x (roll)
  y -- Radian rotation around y (pitch)
  z -- Radian rotation around z (yaw)
  returns a geometry_msgs Quaternion


A version of tf.transformation's euler_from_quaternion that accepts a
  geometry_msgs Quaternion
  q -- geometry_msgs Quaternion
  returns a 3-tuple of Euler angles (x, y, z)


Computes a spherical linear interpolation (slerp) between two quaternions.
  This wraps the method quaternion_slerp from tf.transformation so that it
  accepts and returns geometry_msgs types.
  q1 -- geometry_msgs Quaternion -- The value returned when t=0
  q2 -- geometry_msgs Quaternion -- The value returned when t=1
  t  -- Fraction between q1 and q1. 0 <= t <= 1
  returns a geometry_msgs quaternion between q1 and q1 by a fractional amount t


Compute a spherical linear interpolation (slerp) between two vectors.
  a -- geometry_msgs Point/Vector3 -- The value returned when t=0
  b -- geometry_msgs Point/Vector3 -- The value returned when t=1
  t -- Fraction between a and b. 0 <= t <= 1
  returns a geometry_msgs Point/Vector3 between a and b by a fractional amount t


Computes the quaternion rotation between the vectors a and b.
  a -- geometry_msgs Vector3 or Point
  b -- geometry_msgs Vector3 or Point
  returns a quaternion that represents a rotation from a to b


Check if two vectors are nearly the same.
  a -- geometry_msgs Point/Vector3
  b -- geometry_msgs Point/Vector3
  tolerance -- The maximal distance positions can differ by
  returns True if the difference between a and b are below the tolerance


Check if two poses are nearly the same position and orientation.
  pose1 -- geometry_msgs Pose
  pose2 -- geometry_msgs Pose to be checked against pose1
  linear_tolerance  -- The maximal distance positions can differ by
  angular_tolerance -- The maximal spherical distance orientations can differ by
                       (radians)
  returns True if the difference between pose1 and pose2's position and
  orientations are below their respective tolerances. False otherwise.


Publish action feedback during execution of the action. This is not
    required if action has an empty feedback type.
    kwargs -- Keyword arguments that match fields in feedback_type.


Declare action succeeded, and publish its result.
    msg    -- Message that explains why success occurred. It is logged to ROS
              info and passed to action clients.
    kwargs -- Keyword arguments that match fields in result_type. Leave empty
              if result type is empty.


Declare action was preempted, and publish its results.
    msg    -- Message that explains why action was preempted. It is logged to
              ROS info and passed to action clients.
    kwargs -- Keyword arguments that match fields in result_type. Leave empty
              if result type is empty or no results were produced before
              preempt.


Declare action was aborted, and publish its results.
    msg    -- Message that explains why action was aborted. It is logged to
              ROS error and passed to action clients.
    kwargs -- Keyword arguments that match fields in result_type. Leave empty
              if result type is empty or no results were produced before abort.


Return true if the current state of faults and simulation settings permit
    an action to run.


Declare action aborted, but use the language of rejected. Only intended
    for use internally to this class. It always results in an empty result_type
    being used, so there is no need for kwargs.
    NOTE: Since SimpleActionServer is used we cannot actually reject action
      requests, so we use an abort instead.


Calls on MoveIt to plan the next trajectory of the sequence. If no
    trajectory is provided, the plan is constructed from


Internal helper function so position of a coordinate can be set
    independent of other coordinates and orientation.
    coordinate -- either the characters 'x', 'y', or 'z'
    position   -- absolute frame position coordinate will be moved to


Plan for all joints to move to new configuration
    joint_positions -- list of arm joint positions in radians


Plan for all joints to change their positions by a list of translations
    joint_translations -- list of joint displacements in radians


Plan for one or more joints to move to a new position. Any joint not
    listed in kwargs will not change from its most recent position.
    kwargs -- keywords are joint names and their values are the joint's desired
              translation in radians


Plan for one or more joints to change their positions by some translation.
    Any joint not listed in kwargs will not translate from its most recent
    positions.
    kwargs -- keywords are joint names and their values are the joint's desired
              translation in radians


Plan to a named set of joint positions
    target_name -- named set of joint positions


Plan the end-effector to a new pose
    pose -- geometry_msgs Pose end-effector will move to


Plan the end-effector along a linear path from its most recent pose in
    the sequence to a new pose
    pose -- geometry_msgs Pose


Plan the end-effector along a circular path from its most recent pose in
    the sequence to a new pose.
    NOTE: If the most recent pose in the sequence and the intended pose do not
    lie on the same circle centered at center, the path will not be circular,
    but will be curved. It is up to the method caller to provide arguments that
    define a circular path with the most recent pose.
    pose   -- geometry_msgs Pose -- Pose that will be acquired at the end of
              the circular path.
    center -- geometry_msgs Point/Vector3 -- The center of the circle traced out
              by the end-effector.


Plan the end-effector along a linear path form its most recent pose in
    the sequence to a new pose, which will achieve the same orientation it
    started the trajectory with
    translation -- geometry_msgs Point/Vector3


Plan the end-effector into a new position and acquire the same
    orientation in the final pose.
    translation -- geometry_msgs Point/Vector3 representing new position


Plan the end-effector into a new orientation and acquire the same
    position in the final pose.
    orientation -- geometry_msgs Quaternion representing new orientation


Plan the end-effector to move by a Cartesian translation and acquire the
    same orientation in the final pose.
    translation -- geometry_msgs Point/Vector3 representing a change in position


Set absolute x-position independent of other coordinates and orientation
    position -- New x-position


Set absolute y-position independent of other coordinates and orientation
    position -- New y-position


Set absolute z-position independent of other coordinates and orientation
    position -- New z-position


Merge all trajectories in the sequence into a single trajectory. Must be
    called after calling at least one `plan_to_*` method.
    returns a moveit_msgs/RobotTrajectory that is a merge of all contained
    trajectories


Check if shoulder yaw is within allowable
    shou_yaw_position -- shoulder yaw joint position in radians


Compute shoulder yaw angle to trench
    x -- base_link x position
    y -- base_link y position


:type points: sensor_msgs.msg.PointCloud2


Checks if force threshold has been reached
    msg -- Instance of ArmEndEffectorForceTorque.msg.value, a geometry_msgs/Wrench
            datatype with child datatypes Vector3 force and Vector3 torque


Ticks the stop flag when arm should stop due to a fault.


Executes the provided plan and awaits its completions
    plan -- An instance of moveit_msgs.msg.RobotTrajectory that describes the
            arm trajectory to be executed. Can be None, in which case planning
            is assumed to have failed.
    action_feedback_cb -- A function called at 100 Hz during execution of a
                          trajectory. Exists to publish the action's feedback
                          message. Handles no arguments.


Updates the continue arm flag from dynamic reconfigure server.


Execute the provided trajectory asynchronously.
        trajectory -- An instance of moveit_msgs.msg.RobotTrajectory that
                      describes the desired trajectory.


Blocks until the execution of the current trajectory comes to an end
        timeout -- Seconds to wait for results


Returns true if a trajectory is being executed and has not resulted
        in an error code.


Performs a transform on a supported geometry_msgs object. Transform is
    performed in the present; use the transform method for past transforms.
    geometry -- A geometry_msgs object. Supported: Point, Pose, Vector3, Wrench
    target_frame -- ROS identifier string for the frame to be transformed into
    source_frame -- ROS identifier string from the frame being transformed from
    timestamp -- The time of the desired transform. Assigning rospy.Time(0) will
                 request the most recent transform available in the cache. Even
                 older transforms may be requested, but be careful not to
                 request transforms further in the past than the cache saves.
                 Using ropsy.Time.now() will acquire the next (newest)
                 transform. If a rospy.Time.now() or a transform in the future
                 is used, a sufficiently long timeout must be set, or the frame
                 transform will not be found, resulting in an error.
                 default: rospy.Time(0)
    timeout -- The maximum time interval the method will block for while waiting
               for the requested transform to become available. Using
               rospy.Duration(0) will ensure the method returns immediately, and
               should only be used when requesting a timestamp in the past.
               default: rospy.Duration(0)
    returns a geometry_msgs object of the same type as provided, but transformed
    into the target_frame. None if transform call fails


Performs a transform on a stamped geometry_msgs object
    stamped_type -- A stamped geometry_msgs object
    target_frame -- ROS identifier string for the frame to be transformed into
    timestamp -- The time of the desired transform. Assigning rospy.Time(0) will
                 request the most recent transform available in the cache. Even
                 older transforms may be requested, but be careful not to
                 request transforms further in the past than the cache saves.
                 Using ropsy.Time.now() will acquire the next (newest)
                 transform. If a rospy.Time.now() or a transform in the future
                 is used, a sufficiently long timeout must be set, or the frame
                 transform will not be found, resulting in an error.
                 default: rospy.Time(0)
    timeout -- The maximum time interval the method will block for while waiting
               for the requested transform to become available. Using
               rospy.Duration(0) will ensure the method returns immediately, and
               should only be used when requesting a timestamp in the past.
               default: rospy.Duration(0)
    returns a stamped object of the same type only transformed into target_frame
    or None if transform call fails


Computes a transform from the source frame to the target frame
    source_frame -- The frame from which the transform is computed
    target_frame -- The frame transformed into
    timestamp -- The time of the desired transform. Assigning rospy.Time(0) will
                 request the most recent transform available in the cache. Even
                 older transforms may be requested, but be careful not to
                 request transforms further in the past than the cache saves.
                 Using ropsy.Time.now() will acquire the next (newest)
                 transform. If a rospy.Time.now() or a transform in the future
                 is used, a sufficiently long timeout must be set, or the frame
                 transform will not be found, resulting in an error.
                 default: rospy.Time(0)
    timeout -- The maximum time interval the method will block for while waiting
               for the requested transform to become available. Using
               rospy.Duration(0) will ensure the method returns immediately, and
               should only be used when requesting a timestamp in the past.
               default: rospy.Duration(0)
    returns a transform or None if lookup_transform call fails


    Convenience method to normalize angles to the range [-pi, pi]
    @param angle: An angle that might need to be normalized
    @returns: the normalized value of the angle


Create a 2D bullseye-style intensity map of haloes produced by the Luneburg lens.

    Default parameters:
    int_map(infile=None,outfile="luneburg_int_map.dat",pixels=500.,frac=0.5,sky_mag=13.,figoutfile="luneburg_int_map.pdf",mag_hist_plot=True,verbose=False)

    This routine uses the output data file from luneburg_lens.py to plot a 2D intensity map with a central region containing a user-supplied fraction of the total output intensity. The image is then normalized such that the central region is set equal to 1, and the remaining output intensity is recorded in concentric rings. The number of rings depends on the 'frac' parameter, as the bin size for the rings is set equal to the radius containing fraction 'frac' of the total output intensity. The final intensity map is plotted in log scale and tick labels are set to show the maximum radius of the pixel map normalized to 1.

    The aim of this routine is to show the strength of haloes produced by the Luneburg lens relative to the user-supplied fraction of the total output intensity. The user-supplied fraction 'frac' should reflect what the user considers to be sufficient lens performance for imaging. The intensity map is plotted in log scale for easy comparison to stellar magnitudes, with a color bar that displays the magnitude of the haloes as magnitude = -2.5*log(intensity). Haloes that have relative magnitudes greater than (i.e. dimmer) the sky brightness background magnitude are washed out, as they will not be detectable over the sky background noise transmitted through the lens.

    Example: The user-supplied fraction is 0.5. The user considers capturing 50% of the total output intensity from the Luneburg lens ray tracing routine to be sufficient lens performance for imaging. The central region of the intensity map will contain 50% of the total output intensity and the image is normalized so that the central region is equal to 1. The remainder of intensity is stored in concentric rings that correspond to lens haloes, each with a width equal to the radius of the central region containing 50% of the output intensity. In log scale, if any of the haloes have a relative magnitude greater than (i.e. dimmer) the sky brightness background magnitude (ring_mag > 'sky_mag') then they are set equal to 'sky_mag' as they will not be visible above the sky background. Haloes that are brighter than the sky background (ring_mag < 'sky_mag') will remain visible and potentially contaiminate the image, depending on their magnitude.

    Returns float values for radius, angle, and intensity contained within central region of intensity map.

    Optionally, this routine can plot a magnitude vs. radius histogram with the mag_hist_plot option. The plot uses the data from the intensity map to show the halo positions and halo strengths relative to the normalized central region containing 'frac' of the total intensity output.

    ==========
    Parameters

    infile: [string] name of the input file for ray position and intensity data (default = None)

    outfile: [string] name of the output file for 2D map Luneburg lens intensity output in ascii format (default = "luneburg_int_map.dat")

    pixels: [float] number of pixels per edge for intensity map of Luneburg lens output (default = 500)

    frac: [float] fraction of total Luneburg lens output intensity to be normalized to one; a lens performance threshold (default = 0.5)

    sky_mag: [float] sky brightness background magnitude (default = 13)

    figoutfile: [string] name of the output figure file (default = "luneburg_int_map.pdf")

    mag_hist_plot: [boolean True/False] option to create a magnitude vs radius histogram plot from the intensity map, output file name is figoutfile"_hist".extension

    verbose: [boolean True/False] option to print out more information to the terminal (default = False)

    ==========
    Usage

    # import the enc_int function
    >> from intensity_map import int_map

    # create intensity map from myfile.dat and plot magnitude vs. radius histogram
    >> int_map(infile="myfile.dat"):

    # create intensity map from myfile.dat and save to myplot.pdf, but no histogram plot
    >> int_map(infile="myfile.dat",figoutfile="myplot.pdf",mag_hist_plot=False):

    # create intensity map from myfile.dat with 1000 pixels
    >> int_map(infile="myfile.dat",pixels=1000):

    # create intensity map from myfile.dat with 1000 pixels, with central region containing 80% of Luneburg lens output intensity
    >> int_map(infile="myfile.dat",pixels=1000,frac=0.8):

    # create intensity map from myfile.dat and call radius, angle, and intensity of central region containing 'frac' of intensity output from function returns
    >> frac_radius, frac_theta, frac_int = int_map(infile="myfile.dat"):

    ==========


Create a stepped Luneburg lens model: a spherical lens of varying index of refraction

    Default parameters:
    stepped_luneburg(outfile="luneburg_output.dat",steps=20.,exp=0.5,nrays=100.,amp_cut=0.01,center=[0.,0.,0.],mode=None,modify=False,plot=True,figoutfile="luneburg_lens_raytrace.pdf",verbose=False,logfile="luneburg_log.dat")

    This routine traces the path of a wavefront of rays through the Luneburg lens using Snell's Law at each lens layer. The radius of the lens surface is normalized to 1. Normalized radii for each lens layer are calculated based on the number of steps provided. The lens index of refraction is calculated as n = (2-r^2)^exp and increases in discrete steps from the lens surface to the lens center with the maximum refractive index at center.

    The mode for the wavefront of rays is initialized such that all incoming rays are parallel (i.e. incoming from infinity) and each ray has an amplitude of 1. Rays enter the lens if they are incident on the top hemisphere. Rays incident on the bottom hemisphere of the lens are discarded. All rays that enter the lens are propagated until the ray exits the lens or falls below a designated amplitude threshold.

    The position, direction, and intensity for rays that exit the bottom hemisphere of the lens are stored and accumulated so that an image can be simulated on the bottom surface of the lens. These ray parameters are written to an output file for later processing.

    A four-panel figure can be created to visualize ray tracing through the Luneburg lens.
      Plot a) shows the lens layers and the position of the incident wavefront in the x-y plane (side view).
      Plot b) shows the lens layers and the position of the incident wavefront in the x-z plane (top view).
      Plot c) shows the lens layers and each ray propagating through each lens layer in the x-y plane (side view). Rays striking the outermost surface of the lens are shown with a large orange dot. Rays striking any lens layer interface are shown with a small red dot. Rays exiting the lens are shown with a yellow dot. Rays marked with a black 'X' have been dropped from the routine due to the amplitude cutoff or due to exiting the top hemisphere of the lens.
      Plot d) shows a 2D projection of the rays exiting the bottom hemisphere of the lens in order to simulate an image produced by the lens. Exiting rays are shown as small blue dots, and an alpha value is applied to each dot that corresponds to intensity (i.e. exiting rays with less intensity are more transparent).
        ***note: if mode='stars' then only the stars in the star pattern are plotted in Plots a), b), c), and an unplotted 'grid' pattern of rays is rotated to the stellar position and used to initialize the wavefront of incoming rays from each star

    Optionally, this routine can calculate the lens layer indices of refraction with a modified refractive index power law equation where n = (2-r^(2*exp)) for performance comparison to the original refractive index power law equation.

    Optionally, this routine can write all terminal output to a log file if verbose = True.

    ==========
    Parameters

    outfile: [string] name of the output file (default = "luneburg_output.dat")

    steps: [float] number of steps/layers for the Luneburg lens model (default = 20)

    exp: [float] power-law exponent for the varying index of refraction of the stepped lens model (default = 0.5)

    nrays: [float] numbers of rays to initialize for the wavefront incident on the Luneburg lens; should be a square number (default = 100.)

    amp_cut: [float] amplitude cutoff value for rays propagating through the lens: rays with amplitude below this value after Snell's law are dropped by the program (default = 0.01, 1% amplitude of ray prior to Snell's law)

    center: [list of floats] x, y, and z coordinates of the lens center (default = [0.,0.,0.])
        *** CAUTION: non-zero centers are not properly implemented yet ***

    mode: [string] initial pattern of the wavefront incident on the upper hemisphere of the Luneburg lens (default = None)
        options are 'stars', 'random', 'grid', or 'line'
        'stars' - star pattern on the sky (default = Orion) that can be manually updated/expanded by the user
        'random' - random distribution of points in the x-z plane within a given radius
        'grid' - uniform grid of points in the x-z plane within a given radius, nrays should be a square number
        'line' - single line of points along the x axis

    modify: [boolean True/False] option to modify power law used to calculate the refractive index: True for modified power law, False for original power law (default = False)
        original: n = (2-r^2)^exp
        modified: n = (2-r^(2*exp))

    plot: [boolean True/False] option to show plot of ray tracing through the lens and save the figure (default = True)
        *note: False recommended if nrays is very large

    figoutfile: [string] name of the output figure file if plot = True (default = "luneburg_raytrace.pdf")

    verbose: [boolean True/False] option to print out more information to the terminal and save to a log file (default = False)

    logfile: [string] name of log file containing terminal output if verbose=True (default="luneburg_log.dat")

    ==========
    Usage

    # import the stepped_luneburg function
    >> from luneburg_lens import stepped_luneburg

    # run a Luneburg model for 'grid' wavefront pattern of incoming rays
    >> stepped_luneburg(mode='grid'):

    # run a Luneburg model for 'grid' wavefront pattern of incoming rays with a non-zero center
    *** CAUTION: non-zero centers are not properly implemented yet ***
    >> stepped_luneburg(mode='grid',center=[0.1,0.1,0.1]):

    # run a Luneburg model for 'grid' wavefront pattern of incoming rays without producing a plot
    >> stepped_luneburg(mode='grid',plot=False):

    # run a Luneburg model for 'line' wavefront pattern of incoming rays for a lens with 40 layers, 1000 rays, and amplitude cutoff at 10% of the ray amplitude prior to Snell's law
    >> stepped_luneburg(mode='line',steps=40.,nrays=1000.,amp_cut=0.1):

    # run a Luneburg model for 'random' wavefront pattern of incoming rays with the modified refractive index power law equation and power law exponent 0.6
    >> stepped_luneburg(mode='random',exp=0.6,modify=True):

    # run a Luneburg model for 'stars' wavefront pattern of incoming rays, save to myfile_out.dat, save figure to myplot.pdf, and save log file mylog.dat
    >> stepped_luneburg(outfile="myfile_out.dat",mode='stars',figoutfile="myplot.pdf",verbose=True,logfile="mylog.dat"):

    ==========


Generates indices of refraction for each shell radius based on Luneburg solutions with largest radius normalized to r=1

    ==========
    Parameters

    r_sph: [float or array of floats] radius (radii) of lens layer(s)

    n_pow: [float] power-law exponent

    eq: [boolean True/False] True for modified power law, False for original power law
        original: n = (2-r^2)^exp
        modified: n = (2-r^(2*exp))

    ==========


Rotates points about two axes in two steps. It intakes a list of arrays for point positions (vec_list) with each array consisting of [x,y,z] values. Also intakes a list of two angles. It rotates the points in the x-y plane about the z axis for the first angle, then rotates the points again in the x-z plane about the y axis for the second angle.

    ==========
    Parameters

    vec_list: [list of array of floats] direction vector(s) to be rotated

    ang1_list: [list of array of floats] angle(s) for rotation in x-y plane

    ang2_list: [list of array of floats] angle(s) for rotation in x-z plane

    ==========


Creates the points for the constellation Orion. Starting at some input distance y from the origin, RA and DEC are used to rotate the points into the correct position. Returns a list of arrays with each array containing [x,y,z] coordinates for one star in the constellation

    ==========
    Parameters

    y_offset: [float] offset distance along y-axis, stellar position is initialized at [0.,y,0.]

    ==========


rand_grid distributes random points of total number n within a circle of radius r and returns the points as a list individual arrays [x,y,z]

    ==========
    Parameters

    r: [float] radius of lens surface

    n: [float] number of points to act as initial ray positions for wavefront of rays

    y_offset: [float] offset distance along y-axis, ray position is initialized at [0.,y,0.]

    ==========


uniform_grid creates a uniform grid of points and returns the points as a list individual arrays [x,y,z]

    ==========
    Parameters

    n: [float] number of points to act as initial ray positions for wavefront of rays

    y_offset: [float] offset distance along y-axis, ray position is initialized at [0.,y,0.]

    ==========


Calculate the cumulative enclosed intensity as a function of angle away from the Luneburg lens focal point.

    Default parameters:
    enc_int(infile=None,outfile="luneburg_enc_int.dat",frac=0.5, mode=None, star_num=None,plot=True,figoutfile="luneburg_enc_int.pdf"):

    This routine uses the output data file from luneburg_lens.py to calculate the enclosed intensity of rays exiting the bottom hemisphere of the lens as a function of the angle away from the expected wavefront focal point. The data is saved to an output file that records the angle away from the focal point, the total enclosed intensity at each angle, and the normalized enclosed intensity at each angle. The data can also be plotted with normalized cumulative intensity as a function of log of the angle from the focal point.

    Returns three arrays for theta, enclosed intensity, and normalized enclosed intensity

    ==========
    Parameters

    infile: [string] name of the input file for ray position and intensity data (default = None)

    outfile: [string] name of the output file for angle and enclosed intensity data (default = "luneburg_enc_int.dat")

    frac: [float] fraction of total enclosed intensity to mark for plotting; measure of lens performance (default = 0.5)

    mode: [string] initial pattern of the wavefront incident on the upper hemisphere of the Luneburg lens (default = None)
        options are 'stars', 'random', 'grid', or 'line'
        'stars' - star pattern on the sky (default = Orion) that can be manually updated/expanded by the user
        'random' - random distribution of points in the x-z plane within a given radius
        'grid' - uniform grid of points in the x-z plane within a given radius, nrays should be a square number
        'line' - single line of points along the x axis
            *note: if mode='stars' and star_num = ##: intensity output from the entire star pattern is read in from infile, so other stars in pattern will contaminate enclosed intensity function for star ## in star pattern

    star_num: [int] integer corresponding to the desired star from a user-provided star pattern; only required if mode='stars' (default = None)

    plot: [boolean True/False] option to show plot of normalized enclosed intensity as a function of log(angle) and save the figure (default = True)

    figoutfile: [string] name of the output figure file if plot = True (default = "luneburg_enc_int.pdf")

    ==========
    Usage

    # import the enc_int function
    >> from enclosed_intensity import enc_int

    # calculate enclosed intensity from myfile.dat for 'grid' pattern, plot results
    >> enc_int(infile="myfile.dat",mode='grid'):

    # calculate enclosed intensity from myfile.dat for a specific star from the user-provided 'stars' pattern
    >> enc_int(infile="myfile.dat",mode='stars',star_num=2):

    # calculate enclosed intensity from myfile.dat for a 'line' pattern, write output to myfile_out.dat, and plot results to myplot.pdf
    >> enc_int(infile="myfile.dat",outfile="myfile_out.dat",mode='line',figoutfile='myplot.pdf'):

    # calculate enclosed intensity from myfile.dat for a 'grid' pattern with a high fraction of total intensity marked for plotting
    >> enc_int(infile="myfile.dat",mode='grid',frac=0.9):

    # calculate enclosed intensity and call theta, enclosed intensity, and normalized enclosed intensity from function return
    >> theta, enclosed_int, enclosed_int_norm = enc_int(infile="myfile.dat",mode='grid'):

    ==========


Normalizes a given vector and returns the normalized vector.

    ==========
    Parameters

    v: [array of floats] vector to be normalized

    ==========


Uses a point in 3D space, direction vector, sphere center, and sphere radius to determine if the ray vector will intersect with the sphere. Returns minimum value t for the vector-sphere intersection, indicating that the vector hits the sphere closest to the initial point p0. If the ray vector does not intersect with a sphere then value of t = -1 is returned.

    ==========
    Parameters

    p0: [array of floats] initial point in 3D space [x,y,z]

    d0: [array of floats] initial direction vector in 3D space [x,y,z]

    c0: [array of floats] center of sphere in 3D space [x,y,z]

    r: [float] radius of sphere for determining vector-sphere intersection

    ==========


Uses the normal vector, light ray direction vector, and two indices of refraction from either side of a given sphere radius to calculate the direction and amplitude of a reflected and refracted ray. Returns the direction vectors of the reflected and refracted rays, and the amplitude of the reflected ray.

    CAUTION: When dot product of direction vector and normal vector goes negative, routine fails and calculates a negative cth1 which produces false values for reflection coefficient

    ==========
    Parameters

    nn: [array of floats] direction vector for the normal plane [x,y,z]

    nl: [array of floats] direction vector for the light ray [x,y,z]

    n1: [float] index of refraction on incoming ray side of interface

    n2: [float] index of refraction on refracted ray side of interface

    ==========


Uses a point in 3D space, direction vector, and value generated by sphere_hit() to draw a line from the initial point to a point of intersection with a sphere and returns the point of intersection with a sphere.

    ==========
    Parameters

    p: [array of floats] initial point in 3D space at [x,y,z] for line plotting

    d: [array of floats] direction vector [x,y,z] for line plotting

    t: [float] value to test for the vector-sphere intersection between point p and the nearest sphere, as calculated by sphere_hit()

    plotray: [boolean True/False] option to plot the ray; taken from stepped_luneburg(plot=True/False) parameter

    ==========


Draws sphere with given center and radius.

    ==========
    Parameters

    c: [array of floats] center of sphere at [x,y,z]

    r: [float] radius of sphere to be drawn

    zord: [int] zorder parameter for pl.plot(), adjust plotting order of figure

    ==========


Marks points for a 2D projection from polar to cartesian of sphere with given center and radius.

    ==========
    Parameters

    c: [array of floats] center of sphere at [x,y,z]

    r: [float] radius of sphere to be drawn in 2D projection

    zord: [int] zorder parameter for pl.plot(), adjust plotting order of figure

    ==========


        This function will replace the keywords in the given
        keyword.in-file.


        This function will replace the keywords in the given
        cice-keyword.in-file.


        Create a deep copy of the Config object.

        Returns
        -------
        Config
            A deep copy of the current Config instance.


        Create a deep copy of the dataset.

        Returns
        -------
        BiaPyDataset
            A deep copy of the current instance.


        Return a deep copy of the DatasetFile object.

        Returns
        -------
        DatasetFile
            Deep-copied instance of the object.


        Create a deep copy of the DataSample.

        Returns
        -------
        DataSample
            A new deep-copied instance of the current object.


        Create a deep copy of the PatchCoords object.

        Returns
        -------
        PatchCoords
            A new PatchCoords object with the same coordinate values.


        Return a deep copy of the Normalization object.

        Returns:
            Normalization: Deep copy of the object.


Returns a randomly generated dataset of `nbinaries` solar-type binaries.

    These can be used to fit an observed radial velocity distribution or to generate random radial velocity datasets for Monte Carlo simulations.

    These are defined by:
    - The log-normal period distribution from Raghavan et al. (2010, ApJS, 190, 1)
    - The slightly sloped mass ratio distribution between 0.1 and 1 from Reggiani & Meyer (2013, A&A, 553, 124).
    - A flat eccentricity distribution with a maximum eccentricity as observed in Raghavan et al. (2010) and characterized by Parker et al. (...)

    Arguments:
    - `nbinaries`: number of orbital parameters to draw.


Returns a randomly generated dataset of `nbinaries` OB spectroscopic binaries.

    These can be used to fit an observed radial velocity distribution or to generate random radial velocity datasets for Monte Carlo simulations.

    The `source` parameter is used to select a reference setting the orbital parameter distribution. It should be one of:
    - 'Kiminki12': The binary properties found for 114 B3-O5 stars in Cyg OB2 (Kimkinki & Kobulnicky, 2012, ApJ, 751, 4)
    - 'Sana12': The binary properties found for the O-type star population of six nearby Galactic open clusters (Sana et al., 2012, Science, 337, 444).
    - 'Sana13': The binary properties found for 360 O-type stars in 30 Doradus as part of the Tarantula survey (Sana et al, 2013, A&A, 550, 107).

    The maximum period in these distribution can be overwritten by setting `pmax`.
    In all cases a flat eccentricity distribution is used.

    Arguments:
    - `source`: A reference setting the orbital parameter distribution (one from ['Kiminki12', 'Sana12', 'Sana13'], see above)
    - `pmax`: maximum period to include in the distribution (default set by `source`)
    - `nbinaries`: number of orbital parameters to draw.


Draw a new period distribution in unit of years.

        Either provide an array (with the same length as the number of binaries) or choose from:
        For solar-type stars:
          - 'Raghavan10': The log-normal distribution from Raghavan et al. (2010, ApJS, 190, 1).
          - 'DM91': The log-normal distribution from Duquennoy & Mayor (1991, A&A, 248, 485).
        For OB stars:
          - 'Kiminki12': The log-powerlaw distribution from Kiminki & Kobulnicky (2012, ApJ, 751, 4).
          - 'Sana12': The log-powerlaw distribution from Sana et al. (2012, Science, 337, 444).
          - 'Sana13': The log-powerlaw distribution from Sana et al. (2013, A&A, 550, 107).

        For the log-normal distributions `pmax` can be set (in years) to override the default maximum period.

        If the eccentricity distribution depends on the period, the eccentricity might have to be redrawn afterwards.

        Arguments:
        - `period`: New period distribution (array or name of new distribution).
        - `pmax`: Maximum period in years of log-powerlaw distribution (ignored for log-normal distributions).


Draw a new mass ratio distribution.

        The mass ratio is the ratio of the mass of the secondary star to the primary star, where the observed star is defined as the primary and its companion as the secondary.

        Either provide an array (with the same length as the number of binaries) or choose from:
        - 'flat': Flat distribution between 0 and 1.
        - 'Reggiani13': Powerlaw distribution between 0.1 and 1 from Reggiani & Meyer (2013, A&A, 553, 124).
        - 'Kiminki12': Powerlaw distribution from Kiminki & Kobulnicky (2012, ApJ, 751, 4).
        - 'Sana12': Powerlaw distribution between 0.1 and 1 from Sana et al. (2012, Science, 337, 444).
        - 'Sana13': Powerlaw distribution from Sana et al. (2013, A&A, 550, 107).

        Arguments:
        - `mass_ratio`: New mass ratio distribution (array or name of distribution).
        - `qmin`: Overrides the default minimum mass ratio from the adopted distribution.
        - `qmax`: Overrides the default maximum mass ratio from the adopted distribution.


Draw a new eccentricity distribution.

        Either provide an array (with the same length as the number of binaries) or choose from:
        - 'flat': Flat distribution between `emin` and `emax`.
        - 'thermal`: f(e) ~ e^2 between `emin` and `emax`.

        If `emax` is set to 'tidal' it will depend on the period of the binary to mimic tidal circulirization through:
        emax = max(emin, 0.5 * (0.95 + tanh(0.6 * log_10(period in days) - 1.7)))
        If this setting is chosen the eccentricities will have to be redrawn if the periods are redrawn.

        Arguments:
        - `eccentricity`: New eccentricity distribution (array or name of distriution).
        - `emin`: Minimum eccentricity (default: 0.)
        - `emax`: Maximum eccentricity (default: set by tidal circularization)


Returns the semi-major axis of the binaries in AU.

        Arguments:
        - `mass`: primary mass in solar masses.


Returns the radial velocities and proper motions in km/s.

        Returns an (N, 2) array with the radial velocities and the proper motions due to the binary orbital motions of the N binaries.

        Arguments:
        - `mass`: primary mass of the star in solar masses.
        - `time`:


Returns a callable Basefitter which computes the log-likelihood to reproduce the observed single-epoch radial velocity distribution.

        Uses the current settings of the binary properties to calculate the distribution of radial velocity offsets due to binary orbital motions.

        Arguments:
        - `velocity`: 1D array-like giving velocities in km/s.
        - `sigvel`: 1D array-like (or single number) giving measurement uncertainties in km/s.
        - `mass`: 1D array-like (or single number) giving best estimate for mass of the observed stars in solar masses.
        - `log_minv`: 10_log of the lowest velocity bin in km/s (should be significantly smaller than the velocity dispersion).
        - `log_maxv`: 10_log maximum of the largest velocity bin (default: logarithm of maximum velocity)
        - `log_stepv`: step size in 10_log(velocity) space.


Returns a callable Basefitter which computes the log-likelihood to reproduce the observed multi-epoch radial velocity distribution.

        Uses the current settings of the binary properties to calculate the distribution of radial velocity offsets due to binary orbital motions.

        Arguments:
        - `velocity`: list-like with for every star an array-like containing the observed radial velocities in km/s.
        - `sigvel`: list-like with for every star an array-like containing the measurement uncertainties in km/s.
        - `mass`: 1D array-like (or single number) giving best estimate for mass of the observed stars in solar masses.
        - `dates`: list-like with for every star an array-like containing the date of observations in years.
        - `pfalse`: probability of false detection (i.e. detecting a single star as a binary). Lowering this will decrease the number of detected binaries.
        - `log_minv`: 10_log of the lowest velocity bin in km/s (should be significantly smaller than the velocity dispersion).
        - `log_maxv`: 10_log maximum of the largest velocity bin.
        - `log_stepv`: step size in 10_log(velocity) space.


Creates a fake single-epoch radial velocity data for Monte Carlo simulations.

        Note that multiple calls will use the same binary properties. Redraw the binary properties to get a new set.

        Arguments:
        - `nvel`: number of velocities to draw.
        - `vdisp`: velocity dispersion of the cluster in km/s.
        - `fbin`: binary fraction among observed stars.
        - `sigvel`: array-like of size `nvel` or single number; measurement uncertainty in km/s (undistinguishable from velocity dispersion for single epoch case).
        - `mass`: array-like of size `nvel` or single number; mass of observed stars in solar masses.
        - `dates`: iterable with relative dates of observations in years. Creates a one-dimensional single-epoch dataset if the iterable has a length of one.
        - `vmean`: mean velocity in km/s.


Computes array with the individual log-likelihoods for observing the (average) radial velocity of the observed (seemingly single) stars.

        Call the object for the total log-likelihood (which includes a contribution from RV-variables).

        Arguments:
        - `vmean`: mean velocity of the cluster in km/s.
        - `vdisp`: velocity dispersion of the cluster in km/s.
        - `fbin`: binary fraction of the stars in the cluster.


Calculates the log-likelihood of the RV-variables actually being detected and the seemingly single stars not.

        Computes the binomial probability using the individual detection probability of every star

        Arguments:
        - `fbin`: binary fraction of the stars in the cluster.


Replace certain Unicode characters with named HTML entities.

        This differs from data.encode(encoding, 'xmlcharrefreplace')
        in that the goal is to make the result more readable (to those
        with ASCII displays) rather than to recover from
        errors. There's absolutely nothing wrong with a UTF-8 string
        containg a LATIN SMALL LETTER E WITH ACUTE, but replacing that
        character with "é" will make it more readable to some
        people.


Force an attribute value into a string representation.

        A multi-valued attribute will be converted into a
        space-separated stirng.


Renders the contents of this tag as a bytestring.


performs an md5 sum one chunk at a time to avoid memory issues with large files.


    Returns a matplotlib figure containing the plotted confusion matrix.
    Args:
        cm (array, shape = [n, n]): a confusion matrix of integer classes
        class_names: list with classes for confusion matrix
    Return: confusion matrix figure.


Precursor of gen_random_tiles, where a json file is accepted.


    Function to generate all combinations of available augmentations
    without generating an exact duplicate. The need for this was to
    be able to add more specific data points to a set from a single


Drop multiple bands to existing rasterio object


Change pixel label values based on expression.


    Clip extremity of pixels in the array to given range.
    Args:
        array (np.ndarray): numpy array with image
        xmin (int): minimum value allowed
        xmax (max): maximum value allowed
    Returns:
        np.array mean, np.array std


Crop ROI, from outside to inside based on pixel address.


    Normalize image within parameter, simple scaling of values.
    Args:
        image (np.ndarray): array to normalize
        normalize (float): float value to normalize with
    Returns:
        normalized np.ndarray


    Rescale image [0, 1] per-image or per-channel.
    Args:
        image (np.ndarray): array to rescale
        rescale_type (str): rescaling strategy
    Returns:
        rescaled np.ndarray


    Read dataset CSV from disk and load for preprocessing.
    Args:
        filename (str): string dataset csv.
    Returns:
        pandas dataframe


    Read list of CSV from disk and load for preprocessing.
    Args:
        filename_regex (str): string dataset csv.
    Returns:
        dict of pandas dataframes


    Standardize image within parameter, simple scaling of values.
    Loca, Global, and Mixed options.


    Help function to normalise the features by the mean and
    standard deviation


    Help function to normalise the features by the
    99th percentile


    TODO: FIX STABILITY
    Standardize image within parameter, simple scaling of values.
    Loca, Global, and Mixed options.


Fetch tensorflow dataset.


Initialize TensorFlow dataloader.


Load data on training loop.


    Get list indices for band locations.
    Args:
        bands (list): list of bands in the original raster
        requested_bands (list): list of requested bands for indices
    Returns:
        List of band locations in the order received.


    Burn Area Index (BAI), BAI := 1/((0.1 -RED)^2 + (0.06 - NIR)^2)
    Args:
        raster (list): xarray or numpy array object in the form (c, h, w)
    Returns:
        new xarray.DataArray band with index calculated


    Chlorophyll Index - Green (CIg), CIRE := (NIR / Green) - 1
    Args:
        raster (list): xarray or numpy array object in the form (c, h, w)
    Returns:
        new xarray.DataArray band with index calculated


    Chlorophyll Index - Red-Edge (CIre), CIRE := (NIR / RedEdge) - 1
    Args:
        raster (list): xarray or numpy array object in the form (c, h, w)
    Returns:
        new xarray.DataArray band with index calculated


    Clay Minerals (CM), CM := SWIR1 / SWIR2
    Args:
        raster (list): xarray or numpy array object in the form (c, h, w)
    Returns:
        new xarray.DataArray band with index calculated


    Cloud detection index (CS1), CS1 := (3. * NIR1) / (Blue + Green + Red)
    Args:
        raster (list): xarray or numpy array object in the form (c, h, w)
    Returns:
        new xarray.DataArray band with index calculated


    Cloud detection index (CS2), CS2 := (Blue + Green + Red + NIR1) / 4.
    Args:
        raster (list): xarray or numpy array object in the form (c, h, w)
    Returns:
        new xarray.DataArray band with index calculated


    Enhanced Vegetation Index (EVI)
    EVI := 2.5 [(NIR1 - RE) / (NIR + 6 * RED - 7.5 * BLUE + 1) ]
    Args:
        raster (list): xarray or numpy array object in the form (c, h, w)
    Returns:
        new xarray.DataArray band with index calculated


    Forest Discrimination Index (FDI), type int16
    Args:
        raster (list): xarray or numpy array object in the form (c, h, w)
    Returns:
        new xarray.DataArray band with index calculated


    Norm. Difference Red Edge (NDRE), NDRE := (NIR - RedEdge) / (NIR + RedEdge)
    Args:
        raster (list): xarray or numpy array object in the form (c, h, w)
    Returns:
        new xarray.DataArray band with index calculated


    Get index function from the indices registry.
    Args:
        index_key (str): index key to mine callable index function
    Returns:
        index callable function


    Add indices to a given xarray (appended as bands).
    Args:
        xraster (xarray.DataArray): index key to mine callable index function
        input_bands (list): input bands given by the original raster
        output_bands (list): output bands including new indices (order matters)
        factor (float): factor used for toa imagery calculations
    Returns:
        xarray DataArray with updated bands list and indices


    Dice Crossentropy loss function.
    Args:
        y_true (np.array): array value with truth logits
        y_pred (np.array): array value with prediction logits
    Returns:
       tf.tensor for loss value


Wraps loss function. Crops the labels to match the logits size.


    Function to calculate the Tversky loss for imbalanced data
    :param prediction: the logits
    :param ground_truth: the segmentation ground_truth
    :param alpha: weight of false positives
    :param beta: weight of false negatives
    :param weight_map:
    :return: the loss


    Find the array module to use, for example **numpy** or **cupy**.

    :param xp: The array module to use, for example, 'numpy'
               (normal CPU-based module) or 'cupy' (GPU-based module).
               If not given, will try to read
               from the ARRAY_MODULE environment variable. If not given and
               ARRAY_MODULE is not set,
               will use numpy. If 'cupy' is requested, will
               try to 'import cupy'. If that import fails, will
               revert to numpy.
    :type xp: optional, string or Python module
    :rtype: Python module

    >>> from pysnptools.util import array_module
    >>> xp = array_module() # will look at environment variable
    >>> print(xp.zeros((3)))
    [0. 0. 0.]
    >>> xp = array_module('cupy') # will try to import 'cupy'
    >>> print(xp.zeros((3)))
    [0. 0. 0.]

    # License: Apache 2.0
    # Carl Kadie
    # https://fastlmm.github.io/


    Seeds starting randomization from libraries.
    Args:
        seed (int): integer to seed libraries with.
    Returns:
        None.


Center crop numpy array

    :param image: image to be center cropped
    :type image: np.array
    :param dim: dimensions (width, height) to be cropped
    :type dim: tuple
    :return: center cropped image
    :rtype: np.array


    Load model from filename, take the latest model if not given.
    Args:
        model_filename (str): string with model filename.
        model_dir (str): string with model directory.
        custom_objects (dict): dictionary with callable custom objects
        model_extension (str): string with model extension
    Returns:
        Callable


    Filter GDF by list of values.
    Args:
        gdf (gpd.GeoDataFrame): geodataframe to modify
        gdf_key (str): column key to perform operations on
        isin_list (list): list of features to filter on
        reset_index (bool): reset geodataframe index
    Returns:
        gpd.GeoDataFrame


    Extract window from raster or from numpy array.
    Args:
        image_dataset (gdal.Dataset): gdal dataset to extract window
        pixel_x (int): integer for pixel position on x
        pixel_y (int): integer for pixel position on y
        pixel_width (int): integer for pixel width
        pixel_height (int): integer for pixel height
    Returns:
        np.ndarray


    Define center pixels and call window extraction.
    Args:
        image_dataset (gdal.Dataset): gdal dataset to extract window
        pixel_x (int): integer for pixel position on x
        pixel_y (int): integer for pixel position on y
        pixel_width (int): integer for pixel width
        pixel_height (int): integer for pixel height
    Returns:
        np.ndarray


    Convert geographical coordinates to array pixel location.
    Args:
        coords (list): coordinate from the rater location, [x, y]
        transform (list): transform list from gdal transform
    Returns:
        (x coordinate, y coordinate)


    Extract and save tile from pandas dataframe metadata.
    Args:
        gpd_iter (gpd.GeoDataframe): row from geodataframe
    Returns:
        None (saves np.array to disk)


UNet network using dropout features.


UNet network using batch normalization features.


    TF implementation of DeepLabV3+ model.
    Currently only implements with Xception backbone.


 Method to declare the UNet model.
    Args:
        input_shape: tuple(int, int, int, int)
            Shape of the input in the format (batch, height, width, channels).
        input_label_channel_count: int
            index count of label channels, used for calculating the
            number of channels in model output.
        layer_count: (int, optional)
            Count of kernels in first layer. Number of kernels in other
            layers grows with a fixed factor.
        regularizers: keras.regularizers
            regularizers to use in each layer.
        weight_file: str
            path to the weight file.
        summary: bool
            Whether to print the model summary


Read configuration filename and initiate objects


Set logger configuration.


Preprocess subprocess for parallelization.


Perform general preprocessing.


    Residual convolutional layer.
    Two variants....
    Either put activation function before the addition with shortcut
    or after the addition (which would be as proposed in the original resNet).

    1. conv - BN - Activation - conv - BN - Activation
                                          - shortcut  - BN - shortcut+BN

    2. conv - BN - Activation - conv - BN
       - shortcut  - BN - shortcut+BN - Activation

    Check fig 4 in https://arxiv.org/ftp/arxiv/papers/1802/1802.06955.pdf


    resize the down layer feature map into the same dimension
    as the up layer feature map using 1x1 conv
    :return: the gating feature map with the same dimension
    of the up layer feature map


Residual UNet, with attention


    Load a stored keras model and return its weights.

    Input
    ----------
        The file path of the stored keras model.

    Output
    ----------
        Weights of the model.


    Converting RGB images to numpy arrays.

    Input
    ----------
        filenames: an iterable of the path of image files
        size: the output size (height == width) of image.
              Processed through PIL.Image.NEAREST
        channel: number of image channels, e.g. channel=3 for RGB.

    Output
    ----------
        An array with shape = (filenum, size, size, channel)


    Generating random shuffled indices.

    Input
    ----------
        L: an int that defines the largest index

    Output
    ----------
        a numpy array of shuffled indices with shape = (L,)


    freeze a keras model
    Input
    ----------
        model: a keras model
        freeze_batch_norm: False for not freezing batch notmalization layers


    Stacked Swin Transformers that share the same token size.

    Alternated Window-MSA and Swin-MSA will be configured
    if `shift_window=True`, Window-MSA only otherwise.
    *Dropout is turned off.


    The base of Swin-UNET.

    The general structure:

    1. Input image --> a sequence of patches --> tokenize these patches
    2. Downsampling: swin-transformer --> patch merging (pooling)
    3. Upsampling: concatenate --> swin-transfprmer --> \
        patch expanding (unpooling)
    4. Model head


Check whether an object is an instance of a base type.
    Parameters
    ----------
    obj : object
        The object to be validated.
    name : str
        The name of `obj` in the calling function.
    base : type or tuple of type
        The base type that `obj` should be an instance of.
    func: callable, optional
        A function to be applied to `obj` if it is of type `base`. If None, no
        function will be applied and `obj` will be returned as-is.
    allow_none : bool, optional
        Indicates whether the value None should be allowed to pass through.
    default : object, optional
        The default value to return if `obj` is None and `allow_none` is True.
        If `default` is not None, it must be of type `base`, and it will have
        `func` applied to it if `func` is not None.
    error_message : str or None, optional
        Custom error message to display if the type is incorrect.
    Returns
    -------
    base type or None
        The validated object.
    Raises
    ------
    TypeError
        If `obj` is not an instance of `base`.
    Examples
    --------
    >>> check_type(1, int)
    1
    >>> check_type(1, (int, str))
    1
    >>> check_type(1, str)
    Traceback (most recent call last):
    ...
    TypeError: Invalid type. Expected: str. Actual: int.
    >>> check_type(1, (str, bool))
    Traceback (most recent call last):
    ...
    TypeError: Invalid type. Expected: (str, bool). Actual: int.
    >>> print(check_type(None, str, allow_none=True))
    None
    >>> check_type(1, str, name='num')
    Traceback (most recent call last):
    ...
    TypeError: Invalid type for parameter 'num'. Expected: str. Actual: int.
    >>> check_type(1, int, func=str)
    '1'
    >>> check_type(1, int, func='not callable')
    Traceback (most recent call last):
    ...
    ValueError: Parameter 'func' must be callable or None.
    >>> check_type(2.0, str, error_message='Not a string!')
    Traceback (most recent call last):
    ...
    TypeError: Not a string!
    >>> check_type(None, int, allow_none=True, default=0)
    0


Validate boolean function arguments.
    Parameters
    ----------
    obj : object
        The object to be validated.
    name : str, optional
        The name of `obj` in the calling function.
    allow_none : bool, optional
        Indicates whether the value None should be allowed.
    default : object, optional
        The default value to return if `obj` is None and `allow_none` is True.
    Returns
    -------
    bool or None
        The validated bool.
    Raises
    ------
    TypeError
        If `obj` is not an instance of bool.
    Examples
    --------
    >>> check_bool(True)
    True
    >>> check_bool(1.0)
    Traceback (most recent call last):
    ...
    TypeError: Invalid type. Expected: bool. Actual: float.
    >>> a = (1 < 2)
    >>> check_bool(a, name='a')
    True
    >>> b = 'not a bool'
    >>> check_bool(b, name='b')
    Traceback (most recent call last):
    ...
    TypeError: Invalid type for parameter 'b'. Expected: bool. Actual: str.


Helper function for check_float and check_int.


Validate integer function arguments.
    Parameters
    ----------
    obj : object
        The object to be validated.
    name : str, optional
        The name of `obj` in the calling function.
    positive : bool, optional
        Whether `obj` must be a positive integer (1 or greater).
    minimum : int, optional
        The minimum value that `obj` can take (inclusive).
    maximum : int, optional
        The maximum value that `obj` can take (inclusive).
    allow_none : bool, optional
        Indicates whether the value None should be allowed.
    default : object, optional
        The default value to return if `obj` is None and `allow_none` is True.
    Returns
    -------
    int or None
        The validated integer.
    Raises
    ------
    TypeError
        If `obj` is not an integer.
    ValueError
        If any of the optional positivity or minimum and maximum value
        constraints are violated.
    Examples
    --------
    >>> check_int(0)
    0
    >>> check_int(1, positive=True)
    1
    >>> check_int(1.0)
    Traceback (most recent call last):
    ...
    TypeError: Invalid type. Expected: Integral. Actual: float.
    >>> check_int(-1, positive=True)
    Traceback (most recent call last):
    ...
    ValueError: Parameter must be positive.
    >>> check_int(1, name='a', minimum=10)
    Traceback (most recent call last):
    ...
    ValueError: Parameter 'a' must be at least 10.


Validate float function arguments.
    Parameters
    ----------
    obj : object
        The object to be validated.
    name : str, optional
        The name of `obj` in the calling function.
    positive : bool, optional
        Whether `obj` must be a positive float.
    minimum : float, optional
        The minimum value that `obj` can take (inclusive).
    maximum : float, optional
        The maximum value that `obj` can take (inclusive).
    allow_none : bool, optional
        Indicates whether the value None should be allowed.
    default : object, optional
        The default value to return if `obj` is None and `allow_none` is True.
    Returns
    -------
    float or None
        The validated float.
    Raises
    ------
    TypeError
        If `obj` is not a float.
    ValueError
        If any of the optional positivity or minimum and maximum value
        constraints are violated.
    Examples
    --------
    >>> check_float(0)
    0.0
    >>> check_float(1.0, positive=True)
    1.0
    >>> check_float(1.0 + 1.0j)
    Traceback (most recent call last):
    ...
    TypeError: Invalid type. Expected: Real. Actual: complex.
    >>> check_float(-1, positive=True)
    Traceback (most recent call last):
    ...
    ValueError: Parameter must be positive.
    >>> check_float(1.2, name='a', minimum=10)
    Traceback (most recent call last):
    ...
    ValueError: Parameter 'a' must be at least 10.0.


Compute the per-example focal loss.
        This method simply calls :meth:`~focal_loss.binary_focal_loss` with the
        appropriate arguments.
        Parameters
        ----------
        y_true : tensor-like
            Binary (0 or 1) class labels.
        y_pred : tensor-like
            Either probabilities for the positive class or logits for the
            positive class, depending on the `from_logits` attribute.
            The shapes of `y_true` and `y_pred` should be broadcastable.
        Returns
        -------
        :class:`tf.Tensor`
            The per-example focal loss. Reduction to a scalar is handled by
            this layer's :meth:`~focal_loss.BinaryFocalLoss.__call__` method.


Pre-process a binary label tensor, maybe applying smoothing.
    Parameters
    ----------
    labels : tensor-like
        Tensor of 0's and 1's.
    label_smoothing : float or None
        Float in [0, 1]. When 0, no smoothing occurs. When positive, the binary
        ground truth labels `y_true` are squeezed toward 0.5, with larger
        values of `label_smoothing` leading to label values closer to 0.5.
    dtype : tf.dtypes.DType
        Desired type of the elements of `labels`.
    Returns
    -------
    tf.Tensor
        The processed labels.


Compute focal loss from logits using a numerically stable formula.
    Parameters
    ----------
    labels : tensor-like
        Tensor of 0's and 1's: binary class labels.
    logits : tf.Tensor
        Logits for the positive class.
    gamma : float
        Focusing parameter.
    pos_weight : float or None
        If not None, losses for the positive class will be scaled by this
        weight.
    label_smoothing : float or None
        Float in [0, 1]. When 0, no smoothing occurs. When positive, the binary
        ground truth labels `y_true` are squeezed toward 0.5, with larger
        values of `label_smoothing` leading to label values closer to 0.5.
    Returns
    -------
    tf.Tensor
        The loss for each example.


Compute focal loss from probabilities.
    Parameters
    ----------
    labels : tensor-like
        Tensor of 0's and 1's: binary class labels.
    p : tf.Tensor
        Estimated probabilities for the positive class.
    gamma : float
        Focusing parameter.
    pos_weight : float or None
        If not None, losses for the positive class will be scaled by this
        weight.
    label_smoothing : float or None
        Float in [0, 1]. When 0, no smoothing occurs. When positive, the binary
        ground truth labels `y_true` are squeezed toward 0.5, with larger
        values of `label_smoothing` leading to label values closer to 0.5.
    Returns
    -------
    tf.Tensor
        The loss for each example.


Compute the per-example focal loss.
        This method simply calls
        :meth:`~focal_loss.sparse_categorical_focal_loss` with the appropriate
        arguments.
        Parameters
        ----------
        y_true : tensor-like, shape (N,)
            Integer class labels.
        y_pred : tensor-like, shape (N, K)
            Either probabilities or logits, depending on the `from_logits`
            parameter.
        Returns
        -------
        :class:`tf.Tensor`
            The per-example focal loss. Reduction to a scalar is handled by
            this layer's
            :meth:`~focal_loss.SparseCateogiricalFocalLoss.__call__` method.


Sliding window using tiler.


        Apply a function on each tile. Progress by batching the tiles.
        :param function: The function to apply on each batchs of tile.
        :type function: callable.
        :param progress_bar: choose if a progress_bar should be used.
        :type progress_bar: `bool`. Optional, default value is `False`.
        :param batch_size: Number of batchs to pass inside the function.
        :type batch_size: `int`. Optional, default value is `1`.
        :return: A subclass of `np.ndarray`, with shape of length
        either `4` or `5`.
        :rtype: `MightyMosaic`.


    Create a instance of `MightyMosaic` from a `np.ndarray`
    :param array: The array on which to apply the tiling.
    :type array: `np.ndarray`, it's shape should be of length
    either `2` or `3`.
    :param tile_shape: Number of pixels on each axis of the tile.
    :type tile_shape: `list` or `tuple`, should be of length `2`.
    :param overlap_factor: Overlapping of neighbor tiles. If iterable,
    the overlap can be different on the two axis.
    :type overlap_factor: `int`, `list` or `tuple`. If iterable,
    should be of length 2.
    :param fill_mode: Points outside the boundaries of the input are
    filled according to the given mode:
                        `constant`: kkkkkkkk|abcd|kkkkkkkk (cval=k)
                        `nearest`: aaaaaaaa|abcd|dddddddd
                        `reflect`: abcddcba|abcd|dcbaabcd
    :type fill_mode: `str`, one of `constant`, `nearest` or `reflect`.
    :param cval: Value used for points outside the boundaries when
    fill_mode = `constant`.
    :type cval: `int`. Optional.
    :return: A subclass of `np.ndarray`, with shape of length either
    `4` or `5`.
    :rtype: `MightyMosaic`


    Fill an array on the given indexes with respect to the `fill_mode`.
    :param array: Array to fill.
    :type array: `np.ndarray`.
    :param fill_mode: Points outside the boundaries of the input are
    filled according to the given mode:
                        `constant`: kkkkkkkk|abcd|kkkkkkkk (cval=k)
                        `nearest`: aaaaaaaa|abcd|dddddddd
                        `reflect`: abcddcba|abcd|dcbaabcd
    :type fill_mode: `str`, one of `constant`, `nearest` or
    `reflect`. Optional.
    :param cval: Value used for points outside the boundaries
    when fill_mode = `constant`.
    :type cval: `int`. Optional.
    :param i_begin: Index, on the first axis, of the real begin
    of the array. Index below are filled.
    :type i_begin: `int`. Optional, default value is `0`.
    :param i_end: Index, on the first axis, of the real end of
    the array. Index above are filled.
    :type i_end: `int`. Optional, default value is `-1`.
    :param j_begin: Index, on the second axis, of the real begin
    of the array. Index below are filled.
    :type j_begin: `int`. Optional, default value is `0`.
    :param j_end: Index, on the second axis, of the real end of
    the array. Index above are filled.
    :type j_end: `int`. Optional, default value is `-1`.
    :return:


The query status as a 2-element tuple e.g. ('OK', 'Everythings fine')


        A list of columns in the table.
        Must contain only `~pyvo.io.vosi.vodataservice.TableParam` objects.

        A description of a table column.


        Generate power-law Dl template
        Input: alpha in Cl


        Read FG template (in Dl, muK^2)
        WARNING: need to check file before reading...


Return spectra model for each cross-spectra


lbin = [(lmin,lmax)] for each 15 cross-spectra


    Given a grid of likelihood values, convert them to cumulative
    standard deviation.  This is useful for drawing contours from a
    grid of likelihoods.


Extract the contours for the 2d plots


        Average spectra with defined bins
        can be weighted by `l(l+1)/2pi`.
        Return Cb


Average covariance with defined bins


        Return the (lmin,lmax) for each cross-spectra for each mode (TT, EE, TE, ET)
        array(nmode,nxspec)


        Read xspectra from Xpol [Dl in K^2]
        Output: Dl (TT,EE,TE,ET) in muK^2


        Read xspectra inverse covmatrix from Xpol [Dl in K^-4]
        Output: invkll [Dl in muK^-4]


        Compute covariance matrix size given activated mode
        Return: number of multipole


        Cut spectra given Multipole Ranges and flatten
        Return: list


Average cross-spectra per cross-frequency


        Reduction matrix

        each column is equal to 1 in the 15 elements corresponding to a cross-power spectrum
        measurement in that multipole and zero elsewhere


        Compute likelihood from model out of Boltzmann code
        Units: Dl in muK^2

        Parameters
        ----------
        pars: dict
              parameter values
        dl: array or arr2d
              CMB power spectrum (Dl in muK^2)

        Returns
        -------
        lnL: float
            Log likelihood for the given parameters -2ln(L)


Generate a simple background image.


Generate x, y, and flux lists for stars.


Generate stars image to add to background.


Generate a full image of stars with noise.


Gen frames with {'v', 'u'} dict


Generate translated positions.


Convert a string to a header key following FITS standard.

    Parameters
    ----------
    string : str
        String to convert to header key.


Add a `unit` property to a class.


Generated a mask `~numpy.ndarray` from a given set of flags.

    Given an array or 2D image containing the flag values for each pixel or
    element, this function will generate a mask where all the pixels or
    elements that match any of the given flags will be masked.

    The comparison is performed using bitwise operations and the flags
    must be `IntFlag` instances and its values must be powers of 2.

    Parameters
    ----------
    values: `~numpy.ndarray`
        Array continaing the values to be evaluated.
    flags_to_mask : list of `Flag` or `Flag`
        List of flags to be masked.
    allowed_flags_class : `Flag` or `None`
        If not `None`, only flags from this class will be allowed. If `None`,
        any flag will be allowed.

    Returns
    -------
    mask : `~numpy.ndarray`
        Boolean mask with the same shape as `values` where all the pixels or
        elements that match any of the given flags will be masked.


Append the log record to the list.


Add a ListHandler and a log_list to a Logger.

    Parameters
    ----------
    logger : `logging.Logger`
        `Logger` instance where handler will be added.
    log_list : list or None, optional
        List to store log records.
    full_record : bool, optional
        Store full log records instead of just the message.

    Returns
    -------
        `ListHandler` created during the process.


Resolve the log level of a string.


Raise assertion error if a is not True.


Raise assertion error if condition is not False.


Check if two objects are equal. Arrays supported.


Check if two objects are almost equal. Arrays supported.


Raise assertion error if values are equal.


Raise assertion error if `a is b`.


Raise assertion error if `a is not b`.


Raise assertion error if `a is not None`.


Raise assertion error if `a is None`.


Raise assertion error if `a not in b`.


Raise assertion error if `a in b`.


Raise assertion error if not `isinstance(a, b)`.


Raise assertion error if `isinstance(a, b)`.


Raise assertion error if a is not greater then b.


Raise assertion error if a is not greater or equal then b.


Raise assertion error if a is not less b.


Raise assertion error if a is not less or equal then b.


Raise assertion error if path a do not exists.


Raise assertion error if path a do exists.


    Fix the byte<->string problem in python 3.

    This method converts anything is passed to it into a string. If it is
    `bytes` also handle the decoding.

    Parameters
    ----------
    string: `str` or `bytes`
        String to be checked or converted.
    encode: string (optional)
        Python compatible `bytes` like encoding.
        Default: 'utf-8'

    Returns
    -------
    string: `str`
        The Python 3 string.


Check if a value passed is a scalar number.

    Parameters
    ----------
    value: any
        Value to be checked.

    Returns
    -------
    bool:
        `True` if the value is a scalar number (not string, list or array) and
        `False` otherwise.


Get the length of iterable only values.


Scan and replace {key} values in a dict by dict['key'] value.

    Notes
    -----
    All the replacement is did inplace. Nothing is returned.

    Parameters
    ----------
    dictionary: dict_like
        Dictionary to replace the keys.
    key: string or None, optional
        The key to be replaced.


Read stream buffers.


Run async task and avoid problems with Jupyter.


Run a command in command line with logging.

    Parameters
    ----------
    args: list of strings or string
        Full command, with arguments, to be executed.
    stdout: list (optional)
        List to store the stdout of the command. If None, a new list will be
        created.
    stderr: list (optional)
        List to store the stderr of the command. If None, a new list will be
        created.
    stdout_loglevel: string (optional)
        Log level to print the stdout lines. Default is 'DEBUG'.
    stderr_loglevel: string (optional)
        Log level to print the stderr lines. Default is 'ERROR'.
    logger: `~logging.Logger` (optional)
        Custom logger to print the outputs.
    **kwargs: dict (optional)
        Additional arguments to be passed to `~asyncio.create_subprocess_shell`

    Returns
    -------
        `~subprocess.CompletedProcess` results of the execution.


List all fist files in a directory, if compressed or not.

    Parameters
    ----------
    location : str
        Main directory to look for the files. Files will be listed recursively.
    fits_extensions : str or list, optional
        FITS file name extension to be used. Default is None, wich means
        that the default extensions will be used, like '.fits' and '.fit'.
    glob_include : str, optional
        Glob pattern to include files. Default is None.
    glob_exclude : str, optional
        Glob pattern to exclude files. Default is None.

    Returns
    -------
    list
        List of files found.


Read the database and generate the summary if needed.


Create a new FitsFileGroup with only filtered files.

        Parameters
        ----------
        keywords : dict
            Dictionary with the keywords to be used to filter the files.
            The keys are the column names and the values are the values
            to be used to filter the files.

        Returns
        -------
        FitsFileGroup
            A new FitsFileGroup with only the files that match the
            keywords.


Create FitsFileGroups grouped by keywords.

        Parameters
        ----------
        keywords : list
            List of column names to be used to group the files.

        Yields
        ------
        FitsFileGroup
            A new FitsFileGroup with only the files that match the
            keywords.


Update the database with the current files.


Return the values of a keyword in the summary.

        Parameters
        ----------
        keyword : str
            Name of the keyword to be used to filter the files.
        unique : bool, optional
            If unique, only unique values returned.

        Returns
        -------
        list
            List of values for the keyword.


Add a new column to the summary.

        Parameters
        ----------
        name : str
            Name of the column.
        values : list, optional
            List of values for the column. If None, the column is
            initialized with null values.


Add a new file to the group.

        Parameters
        ----------
        file : str
            File name with absolute path or relative to the filegroup
            location.


Remove a file from the group.

        Parameters
        ----------
        file : str or int
            If string, the file name with absolute path or relative to the
            filegroup location. If int, the index of the file.


Get the full path of a file in the group.

        Parameters
        ----------
        file : str or int
            If string, the file name. If int, the index of the file.

        Returns
        -------
        path : str
            Full path of the file.


Get the relative path of a file.

        Parameters
        ----------
        file : str
            Full path of the file.

        Returns
        -------
        path : str
            Relative path of the file.


Iterate over files.


Create a mask of the sigma clipped pixels.

    This function will not change the array, instead, just output a
    mask for the masked elements.

    Parameters
    ----------
    data: array_like
        Data to be clipped. Can have any dimensionality.
    threshold: int, float or tuple (optional)
        Threshold of sigma clipping. If a number is provided, it is applied
        for both low and high values. If a number is provided, it is
        interpreted as (sigma_low, sigma_high) values.
        Default: 3
    cen_func: callable or {'mean', 'median'} (optional)
        Function to compute the center value used for sigma clipping.
        Default: 'median'
    dev_func: callable or {'std', 'mad_std'} (optional)
        Function to compute the base deviation value used for sigma clipping.
        Default: 'mad_std'
    axis: int
        The axis to perform the clipping and masking.

    Returns
    -------
    mask: `~numpy.ndarray`
        Array with the same shape of `data` containing the mask for elements.


Create a mask of pixels clipped between min_clip and max_clip vals.

    Parameters
    ----------
    data: array_like
        Data array to be cliped.
    min_clip: `float`
        Minimum value accepted in the array. Values lower then this will be
        masked. `None` will disable minimum clip.
        Default: `None`
    max_clip: `float`
        Maximum value accepted in the array. Values greater then this will be
        masked. `None` will disable maximum clip.
        Default: `None`

    Returns
    -------
    mask: `~numpy.ndarray`
        Array with the same shape of `data` containing the mask for elements.


Yield slices for a given shape and number of chunks.


Clear buffer and images.


Read images to FrameData and enable memmap.


Check the consistency between loaded images.


Split the data in chuncks according to the method.


Process the combine and compute the uncertainty.


Perform the image combining.

        Parameters
        ----------
        image_list: `list` or `tuple`
            List containing the images to be combined. The values in the list
            must be all of the same type and `~astropop.framedata.FrameData`
            supported.
        method: {'mean', 'median', 'sum'}
            Combining method.
        **kwargs:
            sum_normalize: bool (optional)
                If True, the imaged will be multiplied, pixel by pixel, by the
                number of images divided by the number of non-masked pixels.
                This will avoid discrepancies by different numbers of masked
                pixels across the image. If False, the raw sum of images will
                be returned.
                Default: True

        Returns
        -------
        combined: `~astropop.framedata.FrameData`
          The combined image.

        Notes
        -----
        - For now, it don't consider WCS, so it perform plain between the
          images, whitout registering.
        - Clipping parameters are set using class functions.
        - If the images exceed the maximum memory allowed, they are splited
          to perform the median and mean combine.
        - Masked elements are skiped. Result pixels will be masked if all the
          source pixels combined in it are also masked.


Combine a list of images or frames in a single one.

    Parameters
    ----------
    frames: list
        List of the frames to be combined. Can be a list of `FrameData`,
        a list of file names, a list of `~astropy.fits.ImageHDU` or
        a list of `~numpy.ndarray`. All members must have the same dimensions.
        For `FrameData`, all units must be the compatible.
    method: {'sum', 'median', 'mean'}
        Combining method. Each one has a proper math and a proper error
        computation.
    memory_limit: int (optional)
        The maximum memory limit (in bytes) to be used in the combining.
        If the data exceeds the maximum memory limit, it will be slipted in
        chunks for the rejection and combining processes.
    **kwargs:
        sigma_clip: float or tuple (optional)
            Threshold of sigma clipping rejection. If `None`, it disables the
            sigma clipping. If a number is provided, it is applied for both low
            and high values. If a tuple is provided, it is interpreted as
            (sigma_low, sigma_high) values.
            Default: `None`
        sigma_cen_func: callable or {'median', 'mean'} (optional)
            Function to compute the central value of sigma clipping rejection.
            If a name is provided, it must follow the convention in Notes.
            If a callable is provided, it will be applied directly on the data
            and must accept 'axis' argument.
            Default: 'median'
        sigma_dev_func: callable or {'std', 'mad_std'} (optional)
            Function to compute the std deviation of sigma clipping rejection.
            If a name is provided, it must follow the convention in Notes.
            If a callable is provided, it will be applied directly on the data
            and must accept 'axis' argument.
            Default: 'std'
        minmax_clip: tuple (optional)
            Minimum and maximum limits for minmax clipping. The values are
            interpreted as (min, max) limits. All values lower then the minimum
            limit and greater then the maximum limit will be masked. If `None`,
            the minmax clipping will be disabled.
            Default: `None`
        merge_header: {'first', 'selected_keys', 'no_merge'} (optional)
            Strategy to merge the headers of the images. If 'first', the first
            image header will be used. If 'selected_keys', the headers will be
            merged using the keys provided in the `header_merge_keys`.
            If 'no_merge', the headers will not be merged.
            Default: 'no_merge'
        header_merge_keys: list (optional)
            List of the keywords to be used to merge the headers.
            Defaut: `None`

    Returns
    -------
    result: `FrameData`
        A `FrameData` containing the combined image and its uncertainty.

    Notes
    -----
    - It is not recomended using clipping with 'sum' method, since it will
      change the number of elements to be summed in each column.
    - To disable a low or high clipping, use tuple with None. For example,
      using `sigma_clip=(None, 2)`, the lower clipping will be disabled.
    - The center function names are:
      - 'median': `~numpy.nanmedian`
      - 'mean': `~numpy.nanmean`
    - The standard deviation funcion names are:
      - 'std': `~numpy.nanstd`
      - 'mad_std': `~astropy.stats.funcs.mad_std`


Check the algorithms and get the register.


Check if the list if it is compatible with the register.


Get the slices of the clip.


Apply the transform to an image.


Compute the transform to register image2 to image1.

        Parameters
        ----------
        image1 : 2d `~numpy.ndarray`
            Reference image for registration.
        image2 : 2d `~numpy.ndarray`
            Moving image for registration.
        mask1, mask2 : 2d `~numpy.ndarray` (optional)
            Masks for images 1 and 2.
            Default: `None`

        Returns
        -------
        tfrom : `~skimage.transform.AffineTransform`
            Transform computed to project image2 in image2.


Align and transform an image2 to match image1.

        Parameters
        ----------
        image1 : 2d `~numpy.ndarray`
            Reference image for registration.
        image2 : 2d `~numpy.ndarray`
            Moving image for registration.
        mask1, mask2 : 2d `~numpy.ndarray` (optional)
            Masks for images 1 and 2.
            Default: `None`
        cval : float or {'median', 'mean'} (optional)
            Fill value for transformed pixels from outside the image. If
            'median' or 'mean', these statistics will be computed as cval.
            Default: 'median'

        Returns
        -------
        reg_image : `~numpy.ndarray`
            Registered image according the transform computed by the class.
        mask : `~numpy.ndarray`
            Mask for the registered image.
        tfrom : `~skimage.transform.AffineTransform`
            Transform computed to project image2 in image2.


Align and transform a frame2 to match frame1.

        Parameters
        ----------
        frame1 : `~astropop.framedata.FrameData`
            Reference image for registration.
        image2 : `~astropop.framedata.FrameData`
            Moving image for registration.
        cval : `float` or {'median', 'mean'} (optional)
            Fill value for transformed pixels from outside the image. If
            'median' or 'mean', these statistics will be computed as cval.
            Default: 'median'
        inplace : `bool` (optional)
            Perform the operation in original frame2 instance. The original
            data will be changed.

        Returns
        -------
        reg_frame : `~astropop.framedata.FrameData`
            Registered frame.


Compute the shift between a list of frames.

    Parameters
    ----------
    frame_list : list
        A list containing `~astropop.framedata.FrameData` images to be
        registered. All images must have the same shape.
    algorithm : {'cross-correlation', 'asterism-matching'} (optional)
        The algorithm to compute the `~skimage.transform.AffineTransform`
        between the images.
        'cross-correlation' will compute the transform
        using `~skimage.transform.phase_cross_correlation` method.
        'asterism-matching' will use `~astroalign` to match asterisms of 3
        detected stars in the field and compute the transform.
        Default: 'cross-correlation'
    ref_image : int (optional)
        Reference image index to compute the registration.
        Default: 0
    skip_failure : bool (optional)
        If True, the images that fail to register will be skipped and their
        shifts will be set to nan.
        Default: False
    **kwargs :
        keyword arguments to be passed to `CrossCorrelationRegister` or
        `AsterismRegister` during instance creation. See the parameters in
        each class documentation.


Perform registration in a framedata list.

    Parameters
    ----------
    frame_list : list
        A list containing `~astropop.framedata.FrameData` images to be
        registered. All images must have the same shape.
    algorith : {'cross-correlation', 'asterism-matching'} (optional)
        The algorithm to compute the `~skimage.transform.AffineTransform`
        between the images.
        'cross-correlation' will compute the transform
        using `~skimage.transform.phase_cross_correlation` method.
        'asterism-matching' will use `~astroalign` to match asterisms of 3
        detected stars in the field and compute the transform.
        Default: 'cross-correlation'
    ref_image : int (optional)
        Reference image index to compute the registration.
        Default: 0
    clip_output : bool (optional)
        If True, the output images will be clipped to a only-valid pixels
        frame.
    cval : float or {'median', 'mean'} (optional)
        Fill value for the empty pixels in the transformed image. If 'mean' or
        'median', the correspondent values will be computed from the image.
        Default: 'median'
    skip_failure: bool (optional)
        If True, the images that fail to register will be skipped. Their data
        will be fill with the cval and all pixels mask will be set to
        True. If False, the error will be raised.
        Default: False
    inplace : bool (optional)
        Perform the operation inplace, modifying the original FrameData
        container. If `False`, a new container will be created.
        Default: `False`
    **kwargs :
        keyword arguments to be passed to `CrossCorrelationRegister` or
        `AsterismRegister` during instance creation. See the parameters in
        each class documentation.


Check if the data is QFloat or FrameData. Else, convert it.


Perform the math operation itself using QFloats.


Perform arithmetic operations using `~astropop.framedata.FrameData`.

    Notes
    -----
    * Keeps the header of the first image.

    * If ``operand1`` is not a `~astropop.framedata.FrameData` instance,
      inplies in ``inplace=False``, and a new `~astropop.framedata.FrameData`
      instance will be created.

    * Supported operations:
        - ``+`` : add. Example: 1+1=2
        - ``-`` : subtract. Example: 2-1=1
        - ``*`` : scalar product. Example: 2*3=6
        - ``/`` : true division. Example: 3/2=1.5
        - ``**`` : power. Example: 3**2=9
        - ``%`` : modulus. Example: 7%2=1
        - ``//`` : floor division. Example: 7//2=3

    Parameters
    ----------
    operand1, operand2: `~astropop.framedata.FrameData` compatible
        Values to perform the operation. `~astropop.math.physical.QFloat`
        `~astropy.units.Quantity`, numerical values and
        `~astropy.nddata.CCDData` are also suported.
    operation: {``+``, ``-``, ``*``, ``/``, ``**``, ``%``, ``//``}
        Math operation.
    inplace: bool, optional
        If True, the operations will be performed inplace in the operand 1.
    merge_flags: {'or', 'and', 'no_merge'}, optional
        How to join the masks of the operands. If ``'or'``, the resulting mask
        will be the union of the masks of the operands. If ``'and'``, the
        resulting mask will be the intersection of the masks of the operands.
        If ``'no_merge'``, the resulting mask will be only zeroes.
    merge_headers: {'no_merge', 'first', 'only_equal', 'selected_keys'}
        How to merge the headers of the operands. If ``'no_merge'``, the
        resulting header will be ``None``. If ``'first'``, the resulting
        header will be the header of the first operand. If ``'only_equal'``,
        the resulting header will be the header of the first operand, but only
        the keys that are equal in both operands. If ``'selected_keys'``, the
        resulting header will be the header of the first operand, but only the
        keys in ``selected_keys``.
    **kwargs:
        Additional arguments:
            selected_keys: list, optional
                List of keys to be merged in the header. Only used if
                ``merge_headers='selected_keys'``.

    Returns
    -------
    `~astropop.framedata.FrameData`:
        new `FrameData` instance if not ``inplace``, else the ``operand1``
        `~astropop.framedata.FrameData` instance.


    Remove cosmic rays with LAcosmic. From astroscrappy package.

    Notes
    -----
    * Detailed information about the Laplacian Cosmic Ray Identification method
      can be found on Dokkum,P.G. (2001) - PASP 113, 1420 (2001)
      https://arxiv.org/pdf/astro-ph/0108003.pdf.

    * If `frame` is not a `~astropop.framedata.FrameData` instance,
      inplies in `inplace=False`, and a new `~astropop.framedata.FrameData`
      instance will be created.

    Parameters
    ----------
    frame: `~astropop.framedata.FrameData` compatible
        2D image to clean with LACosmic.
    inplace: bool, optional
        If True, the operations will be performed inplace in the `frame`.
    logger: `~logging.Logger`
        Python logger to log the actions.

    Returns
    -------
    `~astropop.framedata.FrameData`
        New cosmic-rays corrected `FrameData` instance if not `inplace`,
        else the `image` `~astropop.framedata.FrameData` instance.


    Process the gain correction of an image.

    Notes
    -----
    * The gain is implemented as a multiplier of the original image.

    * If ``image`` is not a `~astropop.framedata.FrameData` instance,
      inplies in ``inplace=False``, and a new `~astropop.framedata.FrameData`
      instance will be created.

    Parameters
    ----------
    image : `~astropop.framedata.FrameData` compatible
        Values to perform the operation. `~astropy.units.Quantity`, numerical
        values and `~astropy.nddata.CCDData` are also suported.
    gain : float, `~astropy.units.Quantity` or `~astropop.math.QFloat`
        Gain to be applied on the image numerical values.
    inplace : bool, optional
        If True, the operations will be performed inplace in the `image`.

    Returns
    -------
    `~astropop.framedata.FrameData`:
        New gain corrected `FrameData` instance if not ``inplace``, else the
        ``image`` `~astropop.framedata.FrameData` instance.


    Subtract a master_bias frame from a FrameData.

    Notes
    -----
    * This function will just subtract a master bias image from the original
      image. The master bias calculation, by handling several bias images,
      must be done previously.

    * If ``image`` is not a `~astropop.framedata.FrameData` instance,
      inplies in ``inplace=False``, and a new `~astropop.framedata.FrameData`
      instance will be created.

    Parameters
    ----------
    image: `~astropop.framedata.FrameData` compatible
        Image to perform the bias correction. `~astropy.units.Quantity`,
        numerical values and `~astropy.nddata.CCDData` are also suported.
    master_bias: `~astropop.framedata.FrameData` compatible
        Master bias image to be subtracted from the ``image``.
    inplace: bool, optional
        If True, the operations will be performed inplace in the ``image``.

    Returns
    -------
    `~astropop.framedata.FrameData`:
        New bias corrrected `FrameData` instance if ``inplace``, else the
        ``image`` `~astropop.framedata.FrameData` instance.


    Subtract master_dark frame from a FrameData.

    Notes
    -----
    * This function will just subtract a master dark frame from the original
      image. The master dark calculation, by handling several dark images,
      must be done previously.

    * Different exposure times among dark image and `FrameData` are handled by
      a multiplying the Master dark image by ``image_exposure/dark_exposure``

    * If ``image`` is not a `~astropop.framedata.FrameData` instance,
      inplies in ``inplace=False``, and a new `~astropop.framedata.FrameData`
      instance will be created.

    Parameters
    ----------
    image : `~astropop.framedata.FrameData` compatible
        Image to perform the dark correction. `~astropy.units.Quantity`,
        numerical values and `~astropy.nddata.CCDData` are also suported.
    master_dark : `~astropop.framedata.FrameData` compatible
        Master dark image to be subtracted from the ``image``.
    dark_exposure : float
        Exposure time of the Master dark.
    image_exposure : float
        Exposure time of the `image`.
    inplace : bool, optional
        If True, the operations will be performed inplace in the `image`.

    Returns
    -------
    `~astropop.framedata.FrameData`:
        New dark corrrected `FrameData` instance if ``inplace``, else the
        ``image`` `~astropop.framedata.FrameData` instance.