# Path: gprMax/exceptions.py
# class CmdInputError(ValueError):
#     """Handles errors in user specified commands. Subclasses the ValueError class."""
# 
#     def __init__(self, message, *args):
# 
#         self.message = message
#         super(CmdInputError, self).__init__(message, *args)
#         print(Fore.RED)
# 
# Path: gprMax/receivers.py
# class Rx(object):
#     """Receiver output points."""
# 
#     allowableoutputs = ['Ex', 'Ey', 'Ez', 'Hx', 'Hy', 'Hz', 'Ix', 'Iy', 'Iz']
#     gpu_allowableoutputs = allowableoutputs[:-3]
#     defaultoutputs = allowableoutputs[:-3]
# 
#     def __init__(self):
# 
#         self.ID = None
#         self.outputs = OrderedDict()
#         self.xcoord = None
#         self.ycoord = None
#         self.zcoord = None
#         self.xcoordorigin = None
#         self.ycoordorigin = None
#         self.zcoordorigin = None
# 
# Path: gprMax/utilities.py
# def fft_power(waveform, dt):
#     """Calculate a FFT of the given waveform of amplitude values;
#         converted to decibels and shifted so that maximum power is 0dB
# 
#     Args:
#         waveform (ndarray): time domain waveform
#         dt (float): time step
# 
#     Returns:
#         freqs (ndarray): frequency bins
#         power (ndarray): power
#     """
# 
#     # Calculate magnitude of frequency spectra of waveform (ignore warning from taking a log of any zero values)
#     with np.errstate(divide='ignore'):
#         power = 10 * np.log10(np.abs(np.fft.fft(waveform))**2)
# 
#     # Replace any NaNs or Infs from zero division
#     power[np.invert(np.isfinite(power))] = 0
# 
#     # Frequency bins
#     freqs = np.fft.fftfreq(power.size, d=dt)
# 
#     # Shift powers so that frequency with maximum power is at zero decibels
#     power -= np.amax(power)
# 
#     return freqs, power


import argparse
import os
import sys
import h5py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from gprMax.exceptions import CmdInputError
from gprMax.receivers import Rx
from gprMax.utilities import fft_power
                # ax.set_ylim([-15, 20])
                ax.grid(which='both', axis='both', linestyle='-.')

                if 'H' in output:
                    plt.setp(line, color='g')
                    plt.setp(ax, ylabel=outputtext + ', field strength [A/m]')
                elif 'I' in output:
                    plt.setp(line, color='b')
                    plt.setp(ax, ylabel=outputtext + ', current [A]')

        # If multiple outputs required, create all nine subplots and populate only the specified ones
        else:
            fig, ax = plt.subplots(subplot_kw=dict(xlabel='Time [s]'), num='rx' + str(rx), figsize=(20, 10), facecolor='w', edgecolor='w')
            if len(outputs) == 9:
                gs = gridspec.GridSpec(3, 3, hspace=0.3, wspace=0.3)
            else:
                gs = gridspec.GridSpec(3, 2, hspace=0.3, wspace=0.3)

            for output in outputs:
                # Check for polarity of output and if requested output is in file
                if output[-1] == 'm':
                    polarity = -1
                    outputtext = '-' + output[0:-1]
                    output = output[0:-1]
                else:
                    polarity = 1
                    outputtext = output

                # Check if requested output is in file
                if output not in availableoutputs:

# Path: gprMax/exceptions.py
# class CmdInputError(ValueError):
#     """Handles errors in user specified commands. Subclasses the ValueError class."""
# 
#     def __init__(self, message, *args):
# 
#         self.message = message
#         super(CmdInputError, self).__init__(message, *args)
#         print(Fore.RED)
# 
# Path: gprMax/receivers.py
# class Rx(object):
#     """Receiver output points."""
# 
#     allowableoutputs = ['Ex', 'Ey', 'Ez', 'Hx', 'Hy', 'Hz', 'Ix', 'Iy', 'Iz']
#     gpu_allowableoutputs = allowableoutputs[:-3]
#     defaultoutputs = allowableoutputs[:-3]
# 
#     def __init__(self):
# 
#         self.ID = None
#         self.outputs = OrderedDict()
#         self.xcoord = None
#         self.ycoord = None
#         self.zcoord = None
#         self.xcoordorigin = None
#         self.ycoordorigin = None
#         self.zcoordorigin = None
# 
# Path: gprMax/utilities.py
# def fft_power(waveform, dt):
#     """Calculate a FFT of the given waveform of amplitude values;
#         converted to decibels and shifted so that maximum power is 0dB
# 
#     Args:
#         waveform (ndarray): time domain waveform
#         dt (float): time step
# 
#     Returns:
#         freqs (ndarray): frequency bins
#         power (ndarray): power
#     """
# 
#     # Calculate magnitude of frequency spectra of waveform (ignore warning from taking a log of any zero values)
#     with np.errstate(divide='ignore'):
#         power = 10 * np.log10(np.abs(np.fft.fft(waveform))**2)
# 
#     # Replace any NaNs or Infs from zero division
#     power[np.invert(np.isfinite(power))] = 0
# 
#     # Frequency bins
#     freqs = np.fft.fftfreq(power.size, d=dt)
# 
#     # Shift powers so that frequency with maximum power is at zero decibels
#     power -= np.amax(power)
# 
#     return freqs, power


# Path: tools/plot_Ascan.py
import argparse
import os
import sys
import h5py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from gprMax.exceptions import CmdInputError
from gprMax.receivers import Rx
from gprMax.utilities import fft_power

                # ax.set_ylim([-15, 20])
                ax.grid(which='both', axis='both', linestyle='-.')

                if 'H' in output:
                    plt.setp(line, color='g')
                    plt.setp(ax, ylabel=outputtext + ', field strength [A/m]')
                elif 'I' in output:
                    plt.setp(line, color='b')
                    plt.setp(ax, ylabel=outputtext + ', current [A]')

        # If multiple outputs required, create all nine subplots and populate only the specified ones
        else:
            fig, ax = plt.subplots(subplot_kw=dict(xlabel='Time [s]'), num='rx' + str(rx), figsize=(20, 10), facecolor='w', edgecolor='w')
            if len(outputs) == 9:
                gs = gridspec.GridSpec(3, 3, hspace=0.3, wspace=0.3)
            else:
                gs = gridspec.GridSpec(3, 2, hspace=0.3, wspace=0.3)

            for output in outputs:
                # Check for polarity of output and if requested output is in file
                if output[-1] == 'm':
                    polarity = -1
                    outputtext = '-' + output[0:-1]
                    output = output[0:-1]
                else:
                    polarity = 1
                    outputtext = output

                # Check if requested output is in file
                if output not in availableoutputs:

                    raise CmdInputError('Output(s) requested to plot: {}, but available output(s) for receiver {} in the file: {}'.format(', '.join(outputs), rx, ', '.join(availableoutputs)))