Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make most modules lazy load #1065

Draft
wants to merge 39 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
17529da
Merge remote-tracking branch 'upstream/master'
jhillairet Apr 23, 2024
b00e5ea
Make most modules lazy load
cafeclimber May 6, 2024
1186d2f
Fix some issues caught by ruff
cafeclimber May 6, 2024
4097df9
Change all occurences of npy to np
cafeclimber May 2, 2024
f4a130c
run permissions
FranzForstmayr May 6, 2024
eb712bc
run permissions
FranzForstmayr May 6, 2024
d7c1770
run permissions
FranzForstmayr May 6, 2024
8cb6eab
run permissions
FranzForstmayr May 6, 2024
02f29ff
run permissions
FranzForstmayr May 6, 2024
136c734
Use ruff directly
FranzForstmayr May 6, 2024
4d87ebe
Run tox as recommended from gitlab
FranzForstmayr May 6, 2024
7b0be56
Install tox
FranzForstmayr May 6, 2024
c2a4f14
remove skip env
FranzForstmayr May 6, 2024
4466b19
Show test results in PR
FranzForstmayr May 6, 2024
758a594
Do not continue on errors!
FranzForstmayr May 6, 2024
793ff69
pytest display
FranzForstmayr May 6, 2024
8f1226e
Linter fixes
FranzForstmayr May 6, 2024
d051384
Testing
FranzForstmayr May 6, 2024
6b25537
Testing
FranzForstmayr May 6, 2024
c79eff4
Testing
FranzForstmayr May 6, 2024
5652863
Tox testing
FranzForstmayr May 7, 2024
ad397e8
Test allclose instead of equality
FranzForstmayr May 7, 2024
d41484d
More numeric issues
FranzForstmayr May 7, 2024
9d75584
Merge master and fix lingering npy usage
cafeclimber May 7, 2024
d425bb3
Make most modules lazy load
cafeclimber May 6, 2024
b41aa42
Fix some issues caught by ruff
cafeclimber May 6, 2024
0f102fe
Merge branch 'master' of https://github.com/scikit-rf/scikit-rf into …
cafeclimber May 7, 2024
52f3418
Fix linting issues
cafeclimber May 7, 2024
24839ec
Trying to fix mpl import issue
cafeclimber May 7, 2024
0a74337
Fix minimal dependency issue
cafeclimber May 7, 2024
f8c2a15
Function level import mpl
cafeclimber May 22, 2024
35d806c
Merge branch 'master' into lazy_loading
cafeclimber May 23, 2024
11b3323
Fix linter issues
cafeclimber May 23, 2024
13f6838
Merge remote-tracking branch 'upstream/master'
jhillairet Jun 22, 2024
6eaf03e
Merge branch 'master' into lazy_loading
jhillairet Jul 10, 2024
67f1342
Merge remote-tracking branch 'upstream/master'
jhillairet Jul 10, 2024
70d60ed
Merge branch 'master' into lazy_loading
jhillairet Jul 10, 2024
71406c4
fix Circuit plot_graph and stylely
jhillairet Jul 10, 2024
aa5dbe6
fix signature
jhillairet Jul 10, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions skrf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
"""

__version__ = '1.1.0'
## Import all module names for coherent reference of name-space
#import io

## Import all module names for coherent reference of name-space
# import io

from . import (
calibration,
Expand Down Expand Up @@ -56,9 +56,11 @@
except Exception:
pass


def __getattr__(name: str):
return getattr(instances._instances, name)


## built-in imports
from copy import deepcopy as copy

Expand Down Expand Up @@ -89,14 +91,15 @@ def setup_pylab() -> bool:


def setup_plotting():
plotting_environment = os.environ.get('SKRF_PLOT_ENV', "pylab").lower()
plotting_environment = os.environ.get("SKRF_PLOT_ENV", "pylab").lower()

if plotting_environment == "pylab":
setup_pylab()
elif plotting_environment == "pylab-skrf-style":
if setup_pylab():
stylely()
# elif some different plotting environment
# set that up
# set that up


plotting_available = setup_plotting()
17 changes: 14 additions & 3 deletions skrf/calibration/calibration.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,15 @@
convert_pnacoefs_2_skrf

"""
from __future__ import annotations

from typing import TYPE_CHECKING, TypeVar

if TYPE_CHECKING:
try:
from matplotlib.pyplot import Axes
except ImportError:
Axes = TypeVar("Axes")

import json
import warnings
Expand All @@ -99,7 +108,6 @@
import numpy as np
from numpy import angle, einsum, exp, imag, invert, linalg, ones, poly1d, real, sqrt, zeros
from numpy.linalg import det
from scipy.optimize import least_squares

from .. import __version__ as skrf__version__
from .. import util
Expand All @@ -119,6 +127,7 @@
zipfile,
)
from ..networkSet import NetworkSet
from ..plotting import axes_kwarg

ComplexArray = np.typing.NDArray[complex]

Expand Down Expand Up @@ -975,8 +984,8 @@ def write(self, file=None, *args, **kwargs):

write(file,self, *args, **kwargs)

@util.axes_kwarg
def plot_calibration_errors(self, *args, ax: util.Axes = None, **kwargs):
@axes_kwarg
def plot_calibration_errors(self, *args, ax: Axes = None, **kwargs):
"""
Plot biased, unbiased and total error in dB scaled.

Expand Down Expand Up @@ -4361,6 +4370,8 @@ def __init__(self, measured, ideals, switch_terms=None, isolation=None,
**kwargs)

def run(self):
from scipy.optimize import least_squares

mList = [k for k in self.measured_unterminated]
lm = mList[0]
r1m = mList[1]
Expand Down
17 changes: 15 additions & 2 deletions skrf/calibration/deembedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,9 @@ class :class:`Deembedding`.
import numpy as np
from numpy import angle, concatenate, conj, exp, flip, real, zeros
from numpy.fft import fft, fftshift, ifftshift, irfft
from scipy.interpolate import interp1d

from ..frequency import Frequency
from ..network import Network, concat_ports, overlap_multi, subnetwork
from ..util import subplots


class Deembedding(ABC):
Expand Down Expand Up @@ -1102,6 +1100,8 @@ def dc_interp(self, s, f):
enforces symmetric upon the first 10 points and interpolates the DC
point.
"""
from scipy.interpolate import interp1d

sp = s[0:9]
fp = f[0:9]

Expand Down Expand Up @@ -1159,6 +1159,8 @@ def DC(self, s, f):


def split2xthru(self, s2xthru):
from scipy.interpolate import interp1d

f = s2xthru.frequency.f
s = s2xthru.s

Expand Down Expand Up @@ -1222,6 +1224,9 @@ def split2xthru(self, s2xthru):
z11x = z11[x]

if self.verbose:
from ..plotting import plt
subplots = plt.subplots

fig, (ax1, ax2) = subplots(2,1)
fig.suptitle('Midpoint length and impedance determination')
ax1.plot(t21, label = 't21')
Expand Down Expand Up @@ -1835,6 +1840,8 @@ def dc_interp(self, s, f):
enforces symmetric upon the first 10 points and interpolates the DC
point.
"""
from scipy.interpolate import interp1d

sp = s[0:9]
fp = f[0:9]

Expand Down Expand Up @@ -2104,6 +2111,9 @@ def makeErrorBox_v7(self, s_dut, s2x, gamma, z0, pullback):
s11dut = s_dut.s[:, 0, 0]
s22dut = s_dut.s[:, 1, 1]
if self.verbose:
from ..plotting import plt
subplots = plt.subplots

if i == 0:
fig, axs = subplots(2, 2)
axs[0, 0].plot(z1, color = 'k')
Expand Down Expand Up @@ -2150,6 +2160,9 @@ def makeErrorBox_v8(self, s_dut, s2x, gamma, z0, pullback):
s_dut = sTL1.inv ** s_dut
s11dut = s_dut.s[:, 0, 0]
if self.verbose:
from ..plotting import plt
subplots = plt.subplots

if i == 0:
fig, axs = subplots(1, 2)
axs[0].plot(z1, color = 'k')
Expand Down
7 changes: 4 additions & 3 deletions skrf/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,7 @@
import numpy as np

from .constants import INF, S_DEF_DEFAULT, NumberLike
from .media import media
from .network import Network, connect, innerconnect, s2s
from .util import subplots

if TYPE_CHECKING:
from .frequency import Frequency
Expand Down Expand Up @@ -332,7 +330,8 @@ def Port(cls, frequency: Frequency, name: str, z0: float = 50) -> Network:

In [18]: port1 = rf.Circuit.Port(freq, name='Port1')
"""
_media = media.DefinedGammaZ0(frequency, z0=z0)
from .media import DefinedGammaZ0
_media = DefinedGammaZ0(frequency, z0=z0)
port = _media.match(name=name)
port._ext_attrs['_is_circuit_port'] = True
return port
Expand Down Expand Up @@ -1365,6 +1364,8 @@ def plot_graph(self, **kwargs):
'label_shift_y': 0

"""
import matplotlib.pyplot as plt
subplots = plt.subplots

nx = self._get_nx()
G = self.G
Expand Down
9 changes: 8 additions & 1 deletion skrf/frequency.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
from typing import TypeVar
Axes = TypeVar("Axes")

import re
import warnings
from numbers import Number
Expand All @@ -51,7 +57,8 @@
)

from .constants import FREQ_UNITS, ZERO, NumberLike
from .util import Axes, axes_kwarg, find_nearest_index, slice_domain
from .plotting import axes_kwarg
from .util import find_nearest_index, slice_domain


class InvalidFrequencyWarning(UserWarning):
Expand Down
2 changes: 1 addition & 1 deletion skrf/instances.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@

from .constants import mil
from .frequency import Frequency
from .media import Freespace, RectangularWaveguide
from .media import DefinedGammaZ0, Freespace, RectangularWaveguide # noqa : F401


class StaticInstances:
Expand Down
2 changes: 0 additions & 2 deletions skrf/io/csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@
from ..frequency import Frequency
from ..network import Network

# delayed imports
# from pandas import Series, Index, DataFrame

def read_pna_csv(filename, *args, **kwargs):
r"""
Expand Down
25 changes: 15 additions & 10 deletions skrf/io/general.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@
from typing import Any

import numpy as np
from pandas import DataFrame, ExcelWriter, Series

from ..frequency import Frequency
from ..network import Network
Expand Down Expand Up @@ -668,6 +667,8 @@ def network_2_spreadsheet(ntwk: Network, file_name: str = None,
--------
networkset_2_spreadsheet : writes a spreadsheet for many networks
"""
import pandas as pd

file_extns = {'csv':'csv','excel':'xls','html':'html'}

form = form.lower()
Expand All @@ -691,23 +692,23 @@ def network_2_spreadsheet(ntwk: Network, file_name: str = None,
if form =='db':
for m,n in ntwk.port_tuples:
d[f'S{ntwk._fmt_trace_name(m,n)} Log Mag(dB)'] = \
Series(ntwk.s_db[:,m,n], index = index)
pd.Series(ntwk.s_db[:,m,n], index = index)
d[f'S{ntwk._fmt_trace_name(m,n)} Phase(deg)'] = \
Series(ntwk.s_deg[:,m,n], index = index)
pd.Series(ntwk.s_deg[:,m,n], index = index)
elif form =='ma':
for m,n in ntwk.port_tuples:
d[f'S{ntwk._fmt_trace_name(m,n)} Mag(lin)'] = \
Series(ntwk.s_mag[:,m,n], index = index)
pd.Series(ntwk.s_mag[:,m,n], index = index)
d[f'S{ntwk._fmt_trace_name(m,n)} Phase(deg)'] = \
Series(ntwk.s_deg[:,m,n], index = index)
pd.Series(ntwk.s_deg[:,m,n], index = index)
elif form =='ri':
for m,n in ntwk.port_tuples:
d[f'S{ntwk._fmt_trace_name(m,n)} Real'] = \
Series(ntwk.s_re[:,m,n], index = index)
pd.Series(ntwk.s_re[:,m,n], index = index)
d[f'S{ntwk._fmt_trace_name(m,n)} Imag'] = \
Series(ntwk.s_im[:,m,n], index = index)
pd.Series(ntwk.s_im[:,m,n], index = index)

df = DataFrame(d)
df = pd.DataFrame(d)
df.__getattribute__(f'to_{file_type}')(file_name,
index_label=f'Freq({ntwk.frequency.unit})', **kwargs)

Expand Down Expand Up @@ -735,6 +736,8 @@ def network_2_dataframe(ntwk: Network, attrs: list[str] =None,
-------
df : pandas DataFrame Object
"""
import pandas as pd

if attrs is None:
attrs = ["s_db"]
if ports is None:
Expand All @@ -748,7 +751,7 @@ def network_2_dataframe(ntwk: Network, attrs: list[str] =None,
attr_array = getattr(ntwk, attr)
for m, n in ports:
d[f'{attr} {m+1}{port_sep}{n+1}'] = attr_array[:, m, n]
return DataFrame(d, index=ntwk.frequency.f)
return pd.DataFrame(d, index=ntwk.frequency.f)

def networkset_2_spreadsheet(ntwkset: NetworkSet, file_name: str = None, file_type: str = 'excel',
*args, **kwargs):
Expand Down Expand Up @@ -789,6 +792,8 @@ def networkset_2_spreadsheet(ntwkset: NetworkSet, file_name: str = None, file_ty
--------
networkset_2_spreadsheet : writes a spreadsheet for many networks
"""
import pandas as pd

if ntwkset.name is None and file_name is None:
raise(ValueError('Either ntwkset must have name or give a file_name'))
if file_name is None:
Expand All @@ -798,7 +803,7 @@ def networkset_2_spreadsheet(ntwkset: NetworkSet, file_name: str = None, file_ty
# add file extension if missing
if not file_name.endswith('.xlsx'):
file_name += '.xlsx'
with ExcelWriter(file_name) as writer:
with pd.ExcelWriter(file_name) as writer:
[network_2_spreadsheet(k, writer, sheet_name=k.name, **kwargs) for k in ntwkset]
else:
[network_2_spreadsheet(k,*args, **kwargs) for k in ntwkset]
Expand Down
8 changes: 7 additions & 1 deletion skrf/io/touchstone.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@
"""
from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
from ..media import DefinedGammaZ0

import os
import re
import typing
Expand All @@ -37,7 +42,6 @@
import numpy as np

from ..constants import FREQ_UNITS, S_DEF_HFSS_DEFAULT
from ..media import DefinedGammaZ0
from ..network import Network
from ..util import get_fid

Expand Down Expand Up @@ -811,6 +815,8 @@ def hfss_touchstone_2_media(filename: str) -> list[DefinedGammaZ0]:
--------
hfss_touchstone_2_gamma_z0 : returns gamma, and z0
"""
from ..media import DefinedGammaZ0

ntwk = Network(filename)

freq = ntwk.frequency
Expand Down
3 changes: 1 addition & 2 deletions skrf/mathFunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@

import numpy as np
from numpy import imag, pi, real, unwrap
from scipy import signal

from .constants import ALMOST_ZERO, EIG_COND, EIG_MIN, INF, LOG_OF_NEG, NumberLike

Expand Down Expand Up @@ -917,7 +916,7 @@ def psd2TimeDomain(f: np.ndarray, y: np.ndarray, windowType: str = 'hamming'):
If spectrum is not baseband then, `timeSignal` is modulated by `exp(t*2*pi*f[0])`.
So keep in mind units. Also, due to this, `f` must be increasing left to right.
"""

from scipy import signal

# apply window function
# make sure windowType exists in scipy.signal
Expand Down
4 changes: 3 additions & 1 deletion skrf/media/circularWaveguide.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import numpy as np
from numpy import sqrt, where
from scipy.constants import epsilon_0, mu_0, pi
from scipy.special import jn_zeros, jnp_zeros

from ..constants import NumberLike
from ..data import materials
Expand Down Expand Up @@ -162,6 +161,7 @@ def from_z0(cls, frequency: Frequency, z0: NumberLike,
passed to :class:`~skrf.media.media.Media`'s constructor
(:func:`~skrf.media.media.Media.__init__`
"""
from scipy.special import jnp_zeros

mu = mu_0*mu_r
ep = epsilon_0*ep_r
Expand Down Expand Up @@ -236,6 +236,8 @@ def kc(self) -> NumberLike:
kc : number
cut-off wavenumber
"""
from scipy.special import jn_zeros, jnp_zeros

if self.mode_type =="te":
u = jnp_zeros(self.m, self.n)[-1]
elif self.mode_type =="tm":
Expand Down
Loading