pyfemtet 0.8.3__py3-none-any.whl → 0.8.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of pyfemtet might be problematic. Click here for more details.

pyfemtet/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.8.3"
1
+ __version__ = "0.8.5"
pyfemtet/opt/_femopt.py CHANGED
@@ -31,7 +31,6 @@ from pyfemtet.opt._femopt_core import (
31
31
  from pyfemtet._message import Msg, encoding
32
32
  from pyfemtet.opt.optimizer.parameter import Parameter, Expression
33
33
  from pyfemtet._warning import experimental_feature
34
- from pyfemtet._imports import *
35
34
 
36
35
  from dask import config as cfg
37
36
  cfg.set({'distributed.scheduler.worker-ttl': None})
@@ -368,7 +367,7 @@ class FEMOpt:
368
367
  # 引数の処理
369
368
  if fun is None:
370
369
  from pyfemtet.opt.interface import SurrogateModelInterfaceBase
371
- if not isinstance_wrapper(self.fem, SurrogateModelInterfaceBase):
370
+ if not isinstance(self.fem, SurrogateModelInterfaceBase):
372
371
  raise ValueError('`fun` argument is not specified.')
373
372
  if args is None:
374
373
  args = tuple()
@@ -404,7 +403,7 @@ class FEMOpt:
404
403
 
405
404
  if names is not None:
406
405
  if isinstance(names, str):
407
- names = [f'name_{i}' for i in range(n_return)]
406
+ names = [f'{names}_{i}' for i in range(n_return)]
408
407
  else:
409
408
  # names = names
410
409
  pass
@@ -511,13 +510,13 @@ class FEMOpt:
511
510
  name = candidate
512
511
  if using_fem is None:
513
512
  # 自動推定機能は Femtet 特有の処理とする
514
- if isinstance_wrapper(self.fem, FemtetInterface):
513
+ if isinstance(self.fem, FemtetInterface):
515
514
  using_fem = _is_access_femtet(fun)
516
515
  else:
517
516
  using_fem = False
518
517
 
519
518
  # strict constraint の場合、solve 前に評価したいので Gogh へのアクセスを禁ずる
520
- if strict and isinstance_wrapper(self.fem, FemtetInterface):
519
+ if strict and isinstance(self.fem, FemtetInterface):
521
520
  if _is_access_gogh(fun):
522
521
  message = Msg.ERR_CONTAIN_GOGH_ACCESS_IN_STRICT_CONSTRAINT
523
522
  raise Exception(message)
@@ -681,7 +680,7 @@ class FEMOpt:
681
680
 
682
681
  # Femtet 特有の処理
683
682
  metadata = None
684
- if isinstance_wrapper(self.fem, FemtetInterface):
683
+ if isinstance(self.fem, FemtetInterface):
685
684
 
686
685
  # 結果 csv に記載する femprj に関する情報の作成
687
686
  metadata = json.dumps(
@@ -36,7 +36,6 @@ else:
36
36
  # pyfemtet relative
37
37
  from pyfemtet.opt.interface import FEMInterface, FemtetInterface
38
38
  from pyfemtet._message import encoding, Msg
39
- from pyfemtet._imports import *
40
39
 
41
40
  # logger
42
41
  from pyfemtet.logger import get_module_logger
@@ -324,7 +323,7 @@ class Function:
324
323
 
325
324
  args = self.args
326
325
  # Femtet 特有の処理
327
- if isinstance_wrapper(fem, FemtetInterface):
326
+ if isinstance(fem, FemtetInterface):
328
327
  args = (fem.Femtet, *args)
329
328
  return float(self.fun(*args, **self.kwargs))
330
329
 
@@ -59,32 +59,39 @@ def _get_obj_from_csv(csv_path, encoding=ENCODING):
59
59
  reader = csv.reader(f, delimiter=",")
60
60
  meta = reader.__next__()
61
61
  obj_indices = np.where(np.array(meta) == "obj")[0]
62
- out = df.iloc[:, obj_indices]
62
+ out: pd.DataFrame = df.iloc[:, obj_indices]
63
+ out = out.dropna(axis=0)
63
64
  return out, columns
64
65
 
65
66
 
66
- def is_equal_result(ref_path, dif_path, log_path):
67
+ def is_equal_result(ref_path, dif_path, log_path=None, threashold=0.05):
67
68
  """Check the equality of two result csv files."""
68
69
  ref_df, ref_columns = _get_obj_from_csv(ref_path)
69
70
  dif_df, dif_columns = _get_obj_from_csv(dif_path)
70
71
 
71
- with open(log_path, "a", newline="\n", encoding=ENCODING) as f:
72
- f.write("\n\n===== 結果の分析 =====\n\n")
73
- f.write(f" \tref\tdif\n")
74
- f.write(f"---------------------\n")
75
- f.write(f"len(col)\t{len(ref_columns)}\t{len(dif_columns)}\n")
76
- f.write(f"len(df) \t{len(ref_df)}\t{len(dif_df)}\n")
77
- try:
78
- difference = (
72
+ if log_path is not None:
73
+ with open(log_path, "a", newline="\n", encoding=ENCODING) as f:
74
+ f.write("\n\n===== 結果の分析 =====\n\n")
75
+ f.write(f" \tref\tdif\n")
76
+ f.write(f"---------------------\n")
77
+ f.write(f"len(col)\t{len(ref_columns)}\t{len(dif_columns)}\n")
78
+ f.write(f"len(df) \t{len(ref_df)}\t{len(dif_df)}\n")
79
+ try:
80
+ difference = (
81
+ np.abs(ref_df.values - dif_df.values) / np.abs(dif_df.values)
82
+ ).mean()
83
+ f.write(f"diff \t{int(difference*100)}%\n")
84
+ except Exception:
85
+ f.write(f"diff \tcannot calc\n")
86
+
87
+ else:
88
+ difference = (
79
89
  np.abs(ref_df.values - dif_df.values) / np.abs(dif_df.values)
80
- ).mean()
81
- f.write(f"diff \t{int(difference*100)}%\n")
82
- except Exception:
83
- f.write(f"diff \tcannot calc\n")
90
+ ).mean()
84
91
 
85
92
  assert len(ref_columns) == len(dif_columns), "結果 csv の column 数が異なります。"
86
93
  assert len(ref_df) == len(dif_df), "結果 csv の row 数が異なります。"
87
- assert difference <= 0.05, "前回の結果との平均差異が 5% を超えています。"
94
+ assert difference <= threashold*100, f"前回の結果との平均差異が {int(difference)}% で {int(threashold*100)}% を超えています。"
88
95
 
89
96
 
90
97
  def _get_simplified_df_values(csv_path, exclude_columns=None):
@@ -1,30 +1,37 @@
1
+ import platform
1
2
  from typing import TYPE_CHECKING
2
- from pyfemtet._imports import _LazyImport, _lazy_class_factory
3
3
 
4
4
  from pyfemtet.opt.interface._base import FEMInterface
5
5
  from pyfemtet.opt.interface._base import NoFEM
6
6
 
7
- if TYPE_CHECKING:
7
+ if (platform.system() == 'Windows') or TYPE_CHECKING:
8
8
  from pyfemtet.opt.interface._femtet import FemtetInterface
9
9
  from pyfemtet.opt.interface._femtet_with_sldworks import FemtetWithSolidworksInterface
10
10
  from pyfemtet.opt.interface._femtet_with_nx import FemtetWithNXInterface
11
- from pyfemtet.opt.interface._surrogate import PoFBoTorchInterface
12
11
  from pyfemtet.opt.interface._excel_interface import ExcelInterface
13
12
 
14
13
  else:
15
- FemtetInterface = _lazy_class_factory(_LazyImport('pyfemtet.opt.interface._femtet'), 'FemtetInterface')
16
- FemtetWithSolidworksInterface = _lazy_class_factory(_LazyImport('pyfemtet.opt.interface._femtet_with_sldworks'), 'FemtetWithSolidworksInterface')
17
- FemtetWithNXInterface = _lazy_class_factory(_LazyImport('pyfemtet.opt.interface._femtet_with_nx'), 'FemtetWithNXInterface')
18
- PoFBoTorchInterface = _lazy_class_factory(_LazyImport('pyfemtet.opt.interface._surrogate'), 'PoFBoTorchInterface')
19
- ExcelInterface = _lazy_class_factory(_LazyImport('pyfemtet.opt.interface._excel_interface'), 'ExcelInterface')
14
+ class NotAvailableForWindows:
15
+ def __init__(self, *args, **kwargs):
16
+ raise NotImplementedError
20
17
 
21
18
 
19
+ FemtetInterface = type('FemtetInterface', (NotAvailableForWindows,), {})
20
+ FemtetWithSolidworksInterface = type('FemtetWithSolidworksInterface', (FemtetInterface,), {})
21
+ FemtetWithNXInterface = type('FemtetWithNXInterface', (FemtetInterface,), {})
22
+ ExcelInterface = type('FemtetInterface', (NotAvailableForWindows,), {})
22
23
 
23
- __all__ = [
24
+ from pyfemtet.opt.interface._surrogate._base import SurrogateModelInterfaceBase
25
+ from pyfemtet.opt.interface._surrogate._singletaskgp import PoFBoTorchInterface
26
+
27
+
28
+ __all__ =[
24
29
  'FEMInterface',
25
30
  'NoFEM',
26
31
  'FemtetInterface',
27
- 'FemtetWithNXInterface',
28
32
  'FemtetWithSolidworksInterface',
33
+ 'FemtetWithNXInterface',
34
+ 'ExcelInterface',
35
+ 'SurrogateModelInterfaceBase',
29
36
  'PoFBoTorchInterface',
30
37
  ]
@@ -17,6 +17,7 @@ class SurrogateModelInterfaceBase(FEMInterface, ABC):
17
17
  self,
18
18
  history_path: str = None,
19
19
  history: History = None,
20
+ override_objective: bool = True,
20
21
  ):
21
22
 
22
23
  self.history: History
@@ -25,6 +26,7 @@ class SurrogateModelInterfaceBase(FEMInterface, ABC):
25
26
  self.obj: dict[str, float] = dict()
26
27
  self.df_prm: pd.DataFrame
27
28
  self.df_obj: pd.DataFrame
29
+ self.override_objective: bool = override_objective
28
30
 
29
31
  # history_path が与えられた場合、history をコンストラクトする
30
32
  if history_path is not None:
@@ -57,27 +59,25 @@ class SurrogateModelInterfaceBase(FEMInterface, ABC):
57
59
  FEMInterface.__init__(
58
60
  self,
59
61
  history=history, # コンストラクト済み history を渡せば並列計算時も何もしなくてよい
62
+ override_objective=self.override_objective
60
63
  )
61
64
 
62
65
  def filter_feasible(self, x: np.ndarray, y: np.ndarray, return_feasibility=False):
63
66
  feasible_idx = np.where(~np.isnan(y.sum(axis=1)))
64
67
  if return_feasibility:
65
68
  # calculated or not
66
- y = np.zeros_like(y)
67
- y[feasible_idx] = 1.
68
- # satisfy weak feasibility or not
69
- infeasible_idx = np.where(~self.history.get_df()['feasible'].values)
70
- y[infeasible_idx] = .0
71
- return x, y.reshape((-1, 1))
69
+ feas = np.zeros((len(y), 1), dtype=float)
70
+ feas[feasible_idx] = 1.
71
+ return x, feas
72
72
  else:
73
73
  return x[feasible_idx], y[feasible_idx]
74
74
 
75
75
  def _setup_after_parallel(self, *args, **kwargs):
76
-
77
- opt: AbstractOptimizer = kwargs['opt']
78
- obj: Objective
79
- for obj_name, obj in opt.objectives.items():
80
- obj.fun = lambda: self.obj[obj_name]
76
+ if self.override_objective:
77
+ opt: AbstractOptimizer = kwargs['opt']
78
+ obj: Objective
79
+ for obj_name, obj in opt.objectives.items():
80
+ obj.fun = lambda obj_name_=obj_name: self.obj[obj_name_]
81
81
 
82
82
  def update_parameter(self, parameters: pd.DataFrame, with_warning=False) -> Optional[List[str]]:
83
83
  for i, row in parameters.iterrows():
@@ -27,8 +27,8 @@ class PoFBoTorchInterface(SurrogateModelInterfaceBase):
27
27
  def train_f(self):
28
28
  # df そのまま用いて training する
29
29
  x, y = self.filter_feasible(self.df_prm.values, self.df_obj.values, return_feasibility=True)
30
- if y.min() == 1:
31
- self.model_f.predict = lambda *args, **kwargs: (1., 0.001)
30
+ if y.min() == 1: # feasible values only
31
+ self.model_f.predict = lambda *args, **kwargs: (1., 0.001) # mean, std
32
32
  self.model_f.fit(x, y)
33
33
 
34
34
  def _setup_after_parallel(self, *args, **kwargs):
@@ -64,7 +64,8 @@ class PoFBoTorchInterface(SurrogateModelInterfaceBase):
64
64
  raise SolveError(Msg.INFO_POF_IS_LESS_THAN_THRESHOLD)
65
65
 
66
66
  # 実際の計算(mean は history.obj_names 順)
67
- mean, _ = self.model.predict(np.array([x]))
67
+ _mean, _std = self.model.predict(np.array([x]))
68
+ mean = _mean[0]
68
69
 
69
70
  # 目的関数の更新
70
71
  self.obj = {obj_name: value for obj_name, value in zip(self.history.obj_names, mean)}
@@ -85,6 +85,8 @@ class SingleTaskGPModel(PredictionModelBase):
85
85
  fit_gpytorch_mll(mll)
86
86
 
87
87
  def predict(self, x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
88
+ assert len(x.shape) >= 2
89
+
88
90
  X = tensor(x)
89
91
 
90
92
  post = self.gp.posterior(X)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: pyfemtet
3
- Version: 0.8.3
3
+ Version: 0.8.5
4
4
  Summary: Design parameter optimization using Femtet.
5
5
  License: BSD-3-Clause
6
6
  Author: kazuma.naito
@@ -1,8 +1,7 @@
1
- pyfemtet/__init__.py,sha256=uU_hzq15Wx5XpYHPCxZI1TgnfSGCFymQwugCWVkFva0,21
1
+ pyfemtet/__init__.py,sha256=ryTvYnQfAb0LetADNMrzLGomNovaozHgioSBOHXn2ms,21
2
2
  pyfemtet/_femtet_config_util/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
3
  pyfemtet/_femtet_config_util/autosave.py,sha256=dNirA9XGuFehas8_Jkj2BW9GOzMbPyhnt1WHcH_ObSU,2070
4
4
  pyfemtet/_femtet_config_util/exit.py,sha256=0BWID-tjOkmZwmgPFkcJMkWW39voccz5ARIBWvZbHaw,1877
5
- pyfemtet/_imports.py,sha256=sO_YNotNCG6IeoA0ge34YnH7q6q_qx2VFDKei3ZfvSk,3268
6
5
  pyfemtet/_message/1. make_pot.bat,sha256=wrTA0YaL7nUfNB0cS8zljOmwq2qgyG6RMwHQbrwjvY4,476
7
6
  pyfemtet/_message/2. make_mo.bat,sha256=6shJ3Yn4BXjDc0hhv_kiGUtVTq4oSRz8-iS4vW29rNE,155
8
7
  pyfemtet/_message/__init__.py,sha256=gE1-XX_PzHj9BbhqPaK5VcIHuv6_Tec5qlPMC3IRiBg,100
@@ -25,12 +24,12 @@ pyfemtet/dispatch_extensions/_impl.py,sha256=yH_yeAnQ-Xi9GfjX-FQt9u3yHnrLYIteRb6
25
24
  pyfemtet/logger/__init__.py,sha256=UOJ9n_U2xwdTrp0Xgg-N6geySxNzKqTBQlXsaH0kW_w,420
26
25
  pyfemtet/logger/_impl.py,sha256=rsAd0HpmveOaLS39ucp3U2OcDhQMWjC5fnVGhbJtWVw,6375
27
26
  pyfemtet/opt/__init__.py,sha256=wRR8LbEhb5I6MUgmnCgjB6-tqHlOVxDIo7yPkq0QbBs,758
28
- pyfemtet/opt/_femopt.py,sha256=0HOKlHDkqNimf10v2oUGEHfgVEM4-4RuyLOUHkJi3ec,39281
29
- pyfemtet/opt/_femopt_core.py,sha256=wd4KijbJuSSuH2n3FY6eAmK_oOJC1R7VzWYKDoJD2KM,38123
27
+ pyfemtet/opt/_femopt.py,sha256=O6Fpaaz2x42iaHI60uMXBFJNWrCGgWYnQsGbnQALzPM,39220
28
+ pyfemtet/opt/_femopt_core.py,sha256=mA2wQ5h_mmbTQ9ilhDHLUyN-jsWFDpJE2r5guUWlS10,38083
30
29
  pyfemtet/opt/_test_utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
31
30
  pyfemtet/opt/_test_utils/control_femtet.py,sha256=8oAl9y5V2n8Nnsgx_ebcZVzwFt1eI3swkdiKg6pg3-M,1085
32
31
  pyfemtet/opt/_test_utils/hyper_sphere.py,sha256=nQhw8EIY0DwvcTqrbKhkxiITLZifr4-nG77E-_6ggmA,700
33
- pyfemtet/opt/_test_utils/record_history.py,sha256=JCNJLZMCNTpJ6VT7iwEt2DIbwmsuQmgC0ClQSfcatj4,3915
32
+ pyfemtet/opt/_test_utils/record_history.py,sha256=mACxWglF7GvLwhvKUC0IhUFHFRrhs2UfTyJqy7vhpbE,4244
34
33
  pyfemtet/opt/advanced_samples/excel_ui/(ref) original_project.femprj,sha256=5OqZfynTpVCrgEIOBOMYuDGaMvepi5lojVNFr1jAsEI,157489
35
34
  pyfemtet/opt/advanced_samples/excel_ui/femtet-macro.xlsm,sha256=ckF0SQ0f3IWSW6QoH1IPJdwUUlR7O_AiGC5fi8SI3jA,133137
36
35
  pyfemtet/opt/advanced_samples/excel_ui/pyfemtet-core.py,sha256=aF2TWXdbt7dnkeBqqVO6GvIExozjFp0mxx3BX8rpYNc,9879
@@ -40,7 +39,7 @@ pyfemtet/opt/advanced_samples/surrogate_model/gal_ex13_create_training_data_jp.p
40
39
  pyfemtet/opt/advanced_samples/surrogate_model/gal_ex13_optimize_with_surrogate.py,sha256=s0b31wuN3iXjb78dt0ro0ZjxHa8uLIH94jRfEuj1EVY,3090
41
40
  pyfemtet/opt/advanced_samples/surrogate_model/gal_ex13_optimize_with_surrogate_jp.py,sha256=OAOpHKyMMo1StSqNMqx4saYDn4hiGOKDypyK6uhTILQ,3215
42
41
  pyfemtet/opt/advanced_samples/surrogate_model/gal_ex13_parametric.femprj,sha256=iIHH1X-wWBqEYj4cFJXco73LCJXSrYBsSKOD0HxYu60,87599
43
- pyfemtet/opt/interface/__init__.py,sha256=POOSj5AN42h7jm8ULjiKDAqPO_l0NY1FpBBUBRVGH-g,1382
42
+ pyfemtet/opt/interface/__init__.py,sha256=na6-elI9-karOqoSxT9LfLQpjBPm1lrUWjow0NYYRP4,1349
44
43
  pyfemtet/opt/interface/_base.py,sha256=y0uQ5jdsWbgt5odyqPin7NXcK_IbUwPDcrrkV_JhpRw,2722
45
44
  pyfemtet/opt/interface/_excel_interface.py,sha256=s103vePTPXXYiPwGdAEUFgtpvGXtu1nSljDtP4HsmcY,40355
46
45
  pyfemtet/opt/interface/_femtet.py,sha256=teALmp66aJ_rrmtEOjCGDG1jGLTZr2AmvMFmuuXRQkw,34634
@@ -50,9 +49,9 @@ pyfemtet/opt/interface/_femtet_with_nx/_interface.py,sha256=LkaODUSpBLq05uz5Jf-J
50
49
  pyfemtet/opt/interface/_femtet_with_nx/update_model.py,sha256=P7VH0i_o-X9OUe6AGaLF1fACPeHNrMjcrOBCA3MMrI4,3092
51
50
  pyfemtet/opt/interface/_femtet_with_sldworks.py,sha256=rjEgebuP1w1eAFVWw4eRJUq3lsyBcmXlkMjZKIpD0kw,11019
52
51
  pyfemtet/opt/interface/_surrogate/__init__.py,sha256=2UT5NuBylyWQJNjg1zsBRCV-MzNCUswTUt6ZuSrYFUM,120
53
- pyfemtet/opt/interface/_surrogate/_base.py,sha256=-k02jRywxaSKMDzGitPE_qBj5nUxC7OL6guF4y6F1Zw,2923
52
+ pyfemtet/opt/interface/_surrogate/_base.py,sha256=bQMoztVq1b-3BW5Z1V-dSROplMHutrblDI289j0cC-E,3001
54
53
  pyfemtet/opt/interface/_surrogate/_chaospy.py,sha256=gL72bCgs1AY_EZdJtcifSC-apwsZzp4zsWYxcpVKvtw,1969
55
- pyfemtet/opt/interface/_surrogate/_singletaskgp.py,sha256=YBRm-8MRwK26qg6T5LKaAhwPfF3jLcKQV-fycP6dnlA,2406
54
+ pyfemtet/opt/interface/_surrogate/_singletaskgp.py,sha256=ojZHsxGxSc8ZJqJQ_uMHvpK98TPUsHzXP0q4tmM0YPQ,2471
56
55
  pyfemtet/opt/optimizer/__init__.py,sha256=Ia6viowECkG0IFXtFef0tJ4jDKsoDzJLqMJ9xLFH2LQ,543
57
56
  pyfemtet/opt/optimizer/_base.py,sha256=j8aQc3fGehZTJT9ETf9cr3VWYs2FYk1F8fO3f7QyKAU,13099
58
57
  pyfemtet/opt/optimizer/_optuna/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -65,7 +64,7 @@ pyfemtet/opt/optimizer/_scipy_scalar.py,sha256=rGvrLjrgfYzxK9GA0-r2Hhoaqt6A0TQsT
65
64
  pyfemtet/opt/optimizer/parameter.py,sha256=YLE9lmYRaZA8isnTPJnbYXpUn6zsJFW4xg03QaSWey8,3950
66
65
  pyfemtet/opt/prediction/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
67
66
  pyfemtet/opt/prediction/_base.py,sha256=dEyEur3IntNokYK8NhPndHb2pWY_A4C1SjEejOTCUGw,2048
68
- pyfemtet/opt/prediction/single_task_gp.py,sha256=6NMSjTtzXJWaW7NEqfqOjz_37mbHpXh9Oo5_KjivRU0,3922
67
+ pyfemtet/opt/prediction/single_task_gp.py,sha256=lhJMrkh3-TPpSpPM2OYmsiZW6TVzxd0XAG2E9VAdFng,3956
69
68
  pyfemtet/opt/samples/femprj_sample/ParametricIF.femprj,sha256=9BtDHmc3cdom0Zq33DTdZ0mDAsIUY6i8SRkkg-n7GO0,442090
70
69
  pyfemtet/opt/samples/femprj_sample/ParametricIF.py,sha256=oXzchBZEbH69xacDht5HDnbZzKwapXsn6bp9qihY17Y,707
71
70
  pyfemtet/opt/samples/femprj_sample/ParametricIF_test_result.reccsv,sha256=TiOAqEDMub6SCGYClBv1JvQxphDOY3iIdr_pMmGgJ9M,2859
@@ -138,8 +137,8 @@ pyfemtet/opt/visualization/result_viewer/.gitignore,sha256=ryvb4aqbbsHireHWlPQfx
138
137
  pyfemtet/opt/visualization/result_viewer/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
139
138
  pyfemtet/opt/visualization/result_viewer/application.py,sha256=WcHBx_J5eNLKSaprpk9BGifwhO04oN8FiNGYTWorrXA,1691
140
139
  pyfemtet/opt/visualization/result_viewer/pages.py,sha256=zcsRmVpVK7xbmOpnKkSypNPsRyHcV3ingfNmuqln6nw,32171
141
- pyfemtet-0.8.3.dist-info/LICENSE,sha256=sVQBhyoglGJUu65-BP3iR6ujORI6YgEU2Qm-V4fGlOA,1485
142
- pyfemtet-0.8.3.dist-info/METADATA,sha256=oVuFWAGVv9bS8O05OqEDoUg0QhNvf9ebmTYWB4ZA8qg,3509
143
- pyfemtet-0.8.3.dist-info/WHEEL,sha256=IYZQI976HJqqOpQU6PHkJ8fb3tMNBFjg-Cn-pwAbaFM,88
144
- pyfemtet-0.8.3.dist-info/entry_points.txt,sha256=ZfYqRaoiPtuWqFi2_msccyrVF0LurMn-IHlYamAegZo,104
145
- pyfemtet-0.8.3.dist-info/RECORD,,
140
+ pyfemtet-0.8.5.dist-info/LICENSE,sha256=sVQBhyoglGJUu65-BP3iR6ujORI6YgEU2Qm-V4fGlOA,1485
141
+ pyfemtet-0.8.5.dist-info/METADATA,sha256=NGd9CK6oM_7IsLx92fBkvQ34tuaWL7RZp8N4WEHvrv8,3509
142
+ pyfemtet-0.8.5.dist-info/WHEEL,sha256=IYZQI976HJqqOpQU6PHkJ8fb3tMNBFjg-Cn-pwAbaFM,88
143
+ pyfemtet-0.8.5.dist-info/entry_points.txt,sha256=ZfYqRaoiPtuWqFi2_msccyrVF0LurMn-IHlYamAegZo,104
144
+ pyfemtet-0.8.5.dist-info/RECORD,,
pyfemtet/_imports.py DELETED
@@ -1,108 +0,0 @@
1
- import types
2
- import importlib
3
- from typing import TYPE_CHECKING, Any
4
- from abc import ABCMeta
5
-
6
-
7
- __all__ = [
8
- 'isinstance_wrapper',
9
- '_LazyImport',
10
- '_lazy_class_factory',
11
- ]
12
-
13
-
14
- class _MetaClass(ABCMeta):
15
- __original_cls__: type
16
-
17
- def __repr__(self):
18
- if hasattr(self, '__original_cls__'):
19
- return f'<LazyClass of {self.__original_cls__()}>'
20
- else:
21
- return f'<LazyClass of <unloaded class>>'
22
-
23
-
24
- def _lazy_class_factory(module, cls_name):
25
- class LazyClass(object, metaclass=_MetaClass):
26
- # 継承を正しくコピーできていないので
27
- # issubclass を使う際は注意
28
- def __new__(cls, *args, **kwargs):
29
- OriginalClass = cls.__original_cls__()
30
- self = OriginalClass(*args, **kwargs)
31
- return self
32
-
33
- @staticmethod
34
- def __original_cls__():
35
- return getattr(module, cls_name)
36
-
37
- return LazyClass
38
-
39
-
40
- class _LazyImport(types.ModuleType):
41
- """Module wrapper for lazy import.
42
-
43
- Note:
44
- This module is totally derived from `optuna._imports._LazyImport`.
45
- The following author has the copyright of this code.
46
-
47
- *******************************************
48
- Copyright (c) 2018 Preferred Networks, Inc.
49
- *******************************************
50
-
51
- This class wraps the specified modules and lazily imports them only when accessed.
52
- Otherwise, `import optuna` is slowed down by importing all submodules and
53
- dependencies even if not required.
54
- Within this project's usage, importlib override this module's attribute on the first
55
- access and the imported submodule is directly accessed from the second access.
56
-
57
- Args:
58
- name: Name of module to apply lazy import.
59
- """
60
-
61
- def __init__(self, name: str) -> None:
62
- super().__init__(name)
63
- self._name = name
64
-
65
- def _load(self) -> types.ModuleType:
66
- module = importlib.import_module(self._name)
67
- self.__dict__.update(module.__dict__)
68
- return module
69
-
70
- def __getattr__(self, item: str) -> Any:
71
- return getattr(self._load(), item)
72
-
73
-
74
- def isinstance_wrapper(obj: object, cls: type) -> bool:
75
- if isinstance(cls, _MetaClass):
76
- try:
77
- cls_ = cls.__original_cls__()
78
- except ModuleNotFoundError:
79
- return False
80
- return isinstance(obj, cls_)
81
- else:
82
- return isinstance(obj, cls)
83
-
84
-
85
- if __name__ == '__main__':
86
- if TYPE_CHECKING:
87
- # for type check only
88
- import numpy
89
- NDArray = numpy.ndarray
90
- import no_module
91
- else:
92
- # runtime
93
- numpy = _LazyImport('numpy')
94
- NDArray = _lazy_class_factory(numpy, 'ndarray')
95
- NDArray2 = _lazy_class_factory(numpy, 'ndarray')
96
- no_module = _LazyImport('no_module')
97
- NoClass = _lazy_class_factory(no_module, 'NoClass')
98
-
99
- print('numpy is loaded:', numpy.__doc__ is not None)
100
- a = NDArray(shape=[1])
101
- print('numpy is loaded:', numpy.__doc__ is not None)
102
-
103
- print(f"{isinstance(None, NoClass)=}")
104
- print(f"{isinstance_wrapper(None, NoClass)=}")
105
- print(f"{isinstance(a, NDArray)=}")
106
- print(f"{isinstance_wrapper(a, NDArray)=}")
107
- print(f"{isinstance_wrapper(a, NoClass)=}")
108
- print(f"{isinstance_wrapper(a, NDArray2)=}")