Skip to content

Commit

Permalink
update formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
hollandjg committed Mar 19, 2024
1 parent affd510 commit 58eaef3
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 46 deletions.
74 changes: 43 additions & 31 deletions src/icesat2waves/local_modules/m_general_ph3.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

_logger = logging.getLogger(__name__)


class Color:
def __init__(self):

Expand Down Expand Up @@ -77,7 +78,6 @@ def __init__(
xsize = x_size if x_size is not None else 8
ysize = y_size if y_size is not None else 5


self.label_letters = iter(f"{i}) " for i in string.ascii_lowercase)

if container:
Expand Down Expand Up @@ -173,7 +173,7 @@ def __init__(self, ax):


class PlotSprecta:
def __init__(self, fs, Xdata, sample_unit="df", data_unit= "X"):
def __init__(self, fs, Xdata, sample_unit="df", data_unit="X"):

self.fs = fs
self.Xdata = Xdata
Expand Down Expand Up @@ -341,8 +341,12 @@ def power(self, anomalie=False):
self.F.ax.set_yscale("log", nonposy="clip")
tt = self.time.astype(DT.datetime)

_logger.debug("Shape of tt: %s, Shape of fs: %s, Shape of dd.T: %s",
tt[:-1].shape, self.fs[:].shape, dd.T.shape)
_logger.debug(
"Shape of tt: %s, Shape of fs: %s, Shape of dd.T: %s",
tt[:-1].shape,
self.fs[:].shape,
dd.T.shape,
)
self.cs = plt.contourf(tt[:-1], self.fs[:], dd.T, self.clevs, cmap=self.cmap)
self.x = np.arange(0, tt[:-1].size)
_logger.debug("clevels: %s", self.clevs)
Expand Down Expand Up @@ -478,14 +482,18 @@ def power_imshow(
fn = self.fs

if isinstance(tt[0], np.datetime64):
_logger.debug('time axis is numpy.datetime64, converted to number for plotting')
_logger.debug(
"time axis is numpy.datetime64, converted to number for plotting"
)
ttt = dates.date2num(tt.astype(DT.datetime))

elif isinstance(tt[0], np.timedelta64):
_logger.debug('time axis is numpy.timedelta64, converted to number for plotting')
_logger.debug(
"time axis is numpy.timedelta64, converted to number for plotting"
)
ttt = tt
else:
_logger.debug('time axis is not converted')
_logger.debug("time axis is not converted")
ttt = tt

MT.stats_format(dd2)
Expand Down Expand Up @@ -623,14 +631,14 @@ def linear_imshow(
fn = self.fs

if isinstance(tt[0], np.datetime64):
_logger.debug('numpy.datetime64')
_logger.debug("numpy.datetime64")
ttt = dates.date2num(tt.astype(DT.datetime))

elif isinstance(tt[0], np.timedelta64):
_logger.debug('numpy.timedelta64')
_logger.debug("numpy.timedelta64")
ttt = tt
else:
_logger.debug('something else')
_logger.debug("something else")
ttt = tt

self.cs = plt.pcolormesh(
Expand Down Expand Up @@ -721,7 +729,6 @@ def linear(self, radial_axis="period", circles=None, ax=None, fontsize=10):
" Polar Spectrum", y=0.95, x=0.5, horizontalalignment="center"
)


# left turned postive
ax.set_theta_direction(-1)
ax.set_theta_zero_location("N")
Expand Down Expand Up @@ -881,7 +888,7 @@ def save_anyfig(fig, name=None, path=None):
extension = ".png"
full_name = (os.path.join(savepath, name)) + extension
fig.savefig(full_name, bbox_inches="tight", format="png", dpi=180)
_logger.debug('save at: %s',full_name)
_logger.debug("save at: %s", full_name)


def read_cdo(file):
Expand Down Expand Up @@ -912,7 +919,7 @@ def cut_nparray(var, low, high, verbose=False):
_logger.debug("out of lower limit!")
if high > var[-1]:
if verbose:
_logger.debug('out of upper limit!')
_logger.debug("out of upper limit!")
_logger.debug("high: %s, last var: %s", high, var[-1])
return (var >= low) & (var <= high)

Expand Down Expand Up @@ -965,8 +972,7 @@ def boxmean(data, lon, lat, xlim, ylim):
case (2, 1):
datan = data[:, :, xbool][:, ybool, :]
case _:
_logger.debug('arrays do not have the same shape')

_logger.debug("arrays do not have the same shape")

_logger.debug("new shape %s", datan.shape)

Expand Down Expand Up @@ -1265,7 +1271,7 @@ def __init__(self, span, dt=None, unit="h"):
for s in self.span:
assert type(s) is int, "span is not an integrer!"

self.length = self.span[1] -self.span[0]
self.length = self.span[1] - self.span[0]
self.loop_iter = np.arange(0, self.length, 1)
self.index_iter = np.arange(self.span[0], self.span[1], 1)
if dt:
Expand Down Expand Up @@ -1326,8 +1332,8 @@ def corse_iter(self, dt, unit=None):
.astype("float")
)
span_new = np.array(self.span) * dt_format / dt
_logger.debug('old span= %s',self.span)
_logger.debug('new span= %s',span_new )
_logger.debug("old span= %s", self.span)
_logger.debug("new span= %s", span_new)

for s in span_new:
span.append(int(np.floor(s)))
Expand Down Expand Up @@ -1379,22 +1385,22 @@ def compose_ts(self, ts, name, time=None):

for i in iindex:
if i + span[0] < 0:
_logger.debug('i: %s span: %s %s', i, span[0], span[1])
_logger.debug('left postion: %s', i+span[0])
_logger.debug("i: %s span: %s %s", i, span[0], span[1])
_logger.debug("left postion: %s", i + span[0])
raise ValueError("composite span exceeds ts limits")

return -1
elif i + span[1] > ts.size:
return -1
_logger.debug('i: %s span: %s %s', i, span[0], span[1])
_logger.debug('right postion: %s',i+span[1])
_logger.debug("i: %s span: %s %s", i, span[0], span[1])
_logger.debug("right postion: %s", i + span[1])
raise ValueError("composite span exceeds ts limits")
return -1

_logger.debug('comp %s', comp.shape)
_logger.debug('ts %s', ts[i + span[0]:i + span[1]].shape)
_logger.debug('i: %s span: %s %s', i, span[0], span[1])
comp = np.vstack((comp, ts[i + span[0]:i + span[1]]))
_logger.debug("comp %s", comp.shape)
_logger.debug("ts %s", ts[i + span[0] : i + span[1]].shape)
_logger.debug("i: %s span: %s %s", i, span[0], span[1])
comp = np.vstack((comp, ts[i + span[0] : i + span[1]]))

comp = np.delete(comp, 0, 0)
comp1 = CompositeData(comp, self.weigthing)
Expand All @@ -1415,7 +1421,9 @@ def compose_2d(self, field, name, time=None):
span = self.iter_operate.span

if span != [0, 0]:
_logger.debug("span range: %s, field shape: %s", -span[0]+span[1],field.shape[1])
_logger.debug(
"span range: %s, field shape: %s", -span[0] + span[1], field.shape[1]
)
comp = np.empty((-span[0] + span[1], field.shape[1])) * np.NaN
self.length = -span[0] + span[1]
for i in iindex:
Expand All @@ -1437,7 +1445,7 @@ def compose_2d(self, field, name, time=None):
comp1 = CompositeData(comp, self.weigthing)
self.comp[name] = comp1
else:
_logger.debug('no span defined')
_logger.debug("no span defined")
comp = field[iindex, :]

comp1 = CompositeData(comp, self.weigthing)
Expand Down Expand Up @@ -1525,12 +1533,14 @@ def gen_log_space(limit, n):

def linefit2Points(time_lin, f, data, f1, f2, f_delta=None, plot=False):
if isinstance(time_lin[0], np.datetime64):
_logger.debug('type is numpy.datetime64, shape %s', time_lin.shape)
_logger.debug("type is numpy.datetime64, shape %s", time_lin.shape)
time_lin = time_lin.astype("m8[s]").astype(int)

if f.shape[0] != data.shape[0]:
_logger.error("ERROR: shapes are not correct")
_logger.error("f: %s; time_lin: %s; data: %s", f.shape, time_lin.shape, data.shape)
_logger.error(
"f: %s; time_lin: %s; data: %s", f.shape, time_lin.shape, data.shape
)
return

# find neerest discrete frequency
Expand Down Expand Up @@ -1615,7 +1625,9 @@ def find_max_along_line(
f_start = np.unravel_index(np.abs(a).argmin(), np.transpose(a.shape))[0]

if mode == "free_limits" or mode == "lower_limit":
_logger.debug("line_right[-1]: %s, time_lin[-1]: %s", line_right[-1], time_lin[-1])
_logger.debug(
"line_right[-1]: %s, time_lin[-1]: %s", line_right[-1], time_lin[-1]
)
if line_right[-1] > time_lin[-1]:
_logger.debug(" right line > time window")
a = line_right - time_lin[-1]
Expand Down
39 changes: 24 additions & 15 deletions src/icesat2waves/local_modules/m_tools_ph3.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@


def dt_form_timestamp(timestamp, unit="h"):
return (timestamp[1]-timestamp[0]).astype(f"m8[{unit}]")
return (timestamp[1] - timestamp[0]).astype(f"m8[{unit}]")


def tick_formatter(a, interval=2, rounder=2, expt_flag=True, shift=0):

fact = 10**(int(np.log10(a.max())) - 1)
fact = 10 ** (int(np.log10(a.max())) - 1)
b = np.round(a / fact, rounder + 1) * fact
ticklabels = [" "] * len(b)

Expand Down Expand Up @@ -107,9 +107,9 @@ def fake_2d_data(verbose=True, timeaxis=False):
z3 = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-((YY - mu) ** 2) / (2 * sigma**2))
z3 = z3 / z3.max()
if verbose:
_logger.debug("x %s" , x.shape)
_logger.debug("y %s" , y.shape)
_logger.debug("z %s" , z3.shape)
_logger.debug("x %s", x.shape)
_logger.debug("y %s", y.shape)
_logger.debug("z %s", z3.shape)

plt.contourf(x, y, z2 / 2 + z3 / 2)
plt.colorbar()
Expand All @@ -129,6 +129,7 @@ def pickle_save(name, path, data, verbose=True):
if verbose:
_logger.debug("save at: %s", full_name)


def pickle_load(name, path, verbose=True):
full_name = os.path.join(path, name + ".npy")

Expand Down Expand Up @@ -191,7 +192,7 @@ def h5_load(name, path, verbose=False):

def h5_load_v2(name, path, verbose=False):

with h5py.File(path + name + '.h5','r') as h5f:
with h5py.File(path + name + ".h5", "r") as h5f:
if verbose:
_logger.debug("%s h5f keys: %s", name, h5f.keys())

Expand Down Expand Up @@ -240,13 +241,15 @@ def save_pandas_table(table_dict, ID, save_path):
def write_log(hist, string, verbose=False, short=True, date=True):

_now = datetime.datetime.now()
_short = "%Y%m%d"
_short = "%Y%m%d"
_long = "%Y-%m-%d %H:%M"
now = _now.strftime(_short) if short else _now.strftime(_long)
message = f"\n{now} {string}" if date else f"\n {string}"

if verbose in [True, 'all']:
_logger.debug("hist message: %s", hist + message if verbose == 'all' else message)
if verbose in [True, "all"]:
_logger.debug(
"hist message: %s", hist + message if verbose == "all" else message
)

return hist + message

Expand All @@ -264,8 +267,10 @@ def write_variables_log(hist, var_list, locals, verbose=False, date=False):

message = f"\n{now} {stringg}" if date else f"\n{' '.ljust(5)} {stringg}"

if verbose in [True, 'all']:
_logger.debug("write_variables_log: %s", hist + message if verbose == 'all' else message)
if verbose in [True, "all"]:
_logger.debug(
"write_variables_log: %s", hist + message if verbose == "all" else message
)


def save_log_txt(name, path, hist, verbose=False):
Expand All @@ -275,7 +280,7 @@ def save_log_txt(name, path, hist, verbose=False):
with open(full_name, "w") as ifile:
ifile.write(str(hist))
if verbose:
_logger.debug("saved at: %s",full_name)
_logger.debug("saved at: %s", full_name)


def load_log_txt(hist_file, path):
Expand Down Expand Up @@ -319,11 +324,10 @@ def stats(a):
np.sum(np.isnan(a)),
np.nanmax(a),
np.nanmin(a),
np.nanmean(a)
np.nanmean(a),
)



def stats_format(a, name=None):
_logger.debug(
"Name: %s\n"
Expand All @@ -332,5 +336,10 @@ def stats_format(a, name=None):
" max: %s\n"
" min: %s\n"
" mean: %s",
name, a.shape, np.sum(np.isnan(a)), np.nanmax(a), np.nanmin(a), np.nanmean(a)
name,
a.shape,
np.sum(np.isnan(a)),
np.nanmax(a),
np.nanmin(a),
np.nanmean(a),
)

0 comments on commit 58eaef3

Please sign in to comment.