Skip to content

Commit

Permalink
String representations for Spectrum and SpectrumStream
Browse files Browse the repository at this point in the history
  • Loading branch information
claudiodsf committed Mar 25, 2024
1 parent 2f8df8a commit 8affdbb
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions sourcespec/spectrum.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"""
import copy
import fnmatch
import math
import numpy as np


Expand Down Expand Up @@ -60,6 +61,23 @@ def __deepcopy__(self, memo):
return new_dict


def _n_significant_digits(x):
"""
Helper function to compute the number of significant digits of a number.
- If the number is greater than 1, the number of significant digits is
zero.
- If the number is less than 1, the number of significant digits is
the number of digits after the decimal point.
- If the number is zero, the number of significant digits is zero.
"""
try:
x = math.fabs(x)
except TypeError as e:
raise ValueError('x must be a number') from e
return 0 if x == 0 or x > 1 else -int(math.floor(math.log10(x)))


class Spectrum():
"""
A class to handle amplitude spectra.
Expand Down Expand Up @@ -90,6 +108,33 @@ def __init__(self, obspy_trace=None):
if obspy_trace is not None:
self.from_obspy_trace(obspy_trace)

def __str__(self):
delta = self.stats.delta
ndigits = _n_significant_digits(delta)
delta_str = f'{delta:.{ndigits}f}'
fmin_str = f'{self.freq[0]:.{ndigits}f}' if self.freq.size else '...'
fmax_str = f'{self.freq[-1]:.{ndigits}f}' if self.freq.size else '...'
delta_logspaced = self.stats.delta_logspaced
ndigits = _n_significant_digits(delta_logspaced)
delta_logspaced_str = f'{delta_logspaced:.{ndigits}f}'
fmin_logspaced_str =\
f'{self.freq_logspaced[0]:.{ndigits}f}'\
if self.freq_logspaced.size else '...'
fmax_logspaced_str =\
f'{self.freq_logspaced[-1]:.{ndigits}f}'\
if self.freq_logspaced.size else '...'
return (
f'{self.id} | '
f'{self.stats.npts} samples, {fmin_str}-{fmax_str} Hz | '
f'{delta_str} Hz sample interval | '
f'{self.stats.npts_logspaced} samples logspaced, '
f'{fmin_logspaced_str}-{fmax_logspaced_str} Hz | '
f'{delta_logspaced_str} log10([Hz]) sample interval logspaced '
)

def __repr__(self):
return f'Spectrum {self}'

@property
def id(self):
"""Return the id of the spectrum."""
Expand Down Expand Up @@ -316,6 +361,12 @@ class SpectrumStream(list):
"""
A class to handle a collection of amplitude spectra.
"""
def __str__(self):
return (
f'SpectrumStream with {len(self)} Spectrum objects:\n'
+ '\n'.join(f'{s}' for s in self)
)

def append(self, spectrum):
"""Append a spectrum to the collection."""
if not isinstance(spectrum, Spectrum):
Expand Down

0 comments on commit 8affdbb

Please sign in to comment.