Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
19 changes: 10 additions & 9 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@
# with open('tests/requirements.txt') as f:
# required += f.read().splitlines()

setup(name='Tidy3D',
version='0.1.1',
description='Front end for Tidy3D.',
author='Flexcompute inc.',
author_email='tyler@flexcompute.com',
url='flexcompute.com',
# install_requires=required,
packages=['tidy3d'],
)
setup(
name="Tidy3D",
version="0.1.1",
description="Front end for Tidy3D.",
author="Flexcompute inc.",
author_email="tyler@flexcompute.com",
url="flexcompute.com",
# install_requires=required,
packages=["tidy3d"],
)
6 changes: 3 additions & 3 deletions tests/test_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def test_webapi_6_load():
"""load the results into sim_data"""
task_id = _get_gloabl_task_id()
sim_data = web.load(task_id, simulation=sim_original, path=PATH_SIM_DATA)
first_monitor_name = list(sim_original.monitors.keys())[0]
first_monitor_name = sim_original.monitors[0].name
_ = sim_data[first_monitor_name]


Expand Down Expand Up @@ -131,7 +131,7 @@ def test_job_6_load():
"""load the results into sim_data"""
job = _get_gloabl_job()
sim_data = job.load(path=PATH_SIM_DATA)
first_monitor_name = list(sim_original.monitors.keys())[0]
first_monitor_name = sim_original.monitors[0].name
_ = sim_data[first_monitor_name]


Expand Down Expand Up @@ -202,7 +202,7 @@ def test_batch_6_load():
"""load the results into sim_data"""
batch = _get_gloabl_batch()
sim_data_dict = batch.load(path_dir=PATH_DIR_SIM_DATA)
first_monitor_name = list(sim_original.monitors.keys())[0]
first_monitor_name = sim_original.monitors[0].name
for _, sim_data in sim_data_dict.items():
_ = sim_data[first_monitor_name]

Expand Down
3 changes: 1 addition & 2 deletions tidy3d/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
""" Tidy3d package imports"""
__version__ = "0.0.0"

from rich import pretty, traceback
from concurrent.futures import ProcessPoolExecutor

# import component as `from tidy3d import Simulation` or `td.Simulation`
from rich import pretty, traceback

# pml
from .components import PML, StablePML, Absorber
Expand Down
23 changes: 20 additions & 3 deletions tidy3d/components/grid.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Defines the FDTD grid."""
import numpy as np
from typing import List
from typing import Tuple

import numpy as np # pylint:disable=unused-import

from .base import Tidy3dBaseModel
from .types import Array, Axis
Expand Down Expand Up @@ -159,7 +160,23 @@ def sizes(self) -> Coords:
return Coords(**{key: np.diff(val) for key, val in self.boundaries.dict().items()})

@property
def num_cells(self) -> List[int]:
def num_cells(self) -> Tuple[int, int, int]:
"""Return sizes of the cells in the :class:`Grid`.

Returns
-------
tuple[int, int, int]
Number of cells in the grid in the x, y, z direction.

Example
-------
>>> x = np.linspace(-1, 1, 10)
>>> y = np.linspace(-1, 1, 11)
>>> z = np.linspace(-1, 1, 12)
>>> coords = Coords(x=x, y=y, z=z)
>>> grid = Grid(boundaries=coords)
>>> Nx, Ny, Nz = grid.num_cells
"""
return [coords1d.size - 1 for coords1d in self.boundaries.dict().values()]

@property
Expand Down
2 changes: 1 addition & 1 deletion tidy3d/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def set_logging_file(fname: str, filemode="w", level=DEFAULT_LEVEL.lower()):

Example
-------
>>> set_logging_file('tidy3d_log.log)
>>> set_logging_file('tidy3d_log.log')
>>> log.warning('this warning will appear in the tidy3d_log.log')
"""

Expand Down
25 changes: 13 additions & 12 deletions tidy3d/web/httputils.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
""" handles communication with server """
import os
# import os
from typing import Dict
from enum import Enum

import requests

from .auth import get_credentials
from .config import DEFAULT_CONFIG as Config
from ..log import WebError


class ResponseCodes(Enum):
"""HTTP response codes to handle individually"""
"""HTTP response codes to handle individually."""

UNAUTHORIZED = 401
OK = 200


def handle_response(func):
"""hndles return values of http requests based on status"""
"""Handles return values of http requests based on status."""

def wrapper(*args, **kwargs):
"""new function to replace func with"""
"""New function to replace func with."""

# call originl request
resp = func(*args, **kwargs)

# while its unauthorized
# while it's unauthorized
while resp.status_code == ResponseCodes.UNAUTHORIZED.value:

# ask for credentials and call the http request again
Expand All @@ -43,15 +44,15 @@ def wrapper(*args, **kwargs):

# if that doesnt work, raise
except Exception as e:
print(f"Could not decode response json: {resp.text})")
raise e
raise WebError(f"Could not decode response json: {resp.text})") from e

return wrapper


def get_query_url(method: str) -> str:
"""construct query url from method name"""
return os.path.join(Config.web_api_endpoint, method)
return f"{Config.web_api_endpoint}/{method}"
# return os.path.join(Config.web_api_endpoint, method)


def get_headers() -> Dict[str, str]:
Expand All @@ -67,31 +68,31 @@ def get_headers() -> Dict[str, str]:

@handle_response
def post(method, data=None):
"""uploads the file"""
"""Uploads the file."""
query_url = get_query_url(method)
headers = get_headers()
return requests.post(query_url, headers=headers, json=data)


@handle_response
def put(method, data):
"""runs the file"""
"""Runs the file."""
query_url = get_query_url(method)
headers = get_headers()
return requests.put(query_url, headers=headers, json=data)


@handle_response
def get(method):
"""downloads the file"""
"""Downloads the file."""
query_url = get_query_url(method)
headers = get_headers()
return requests.get(query_url, headers=headers)


@handle_response
def delete(method):
"""deletes the file"""
"""Deletes the file."""
query_url = get_query_url(method)
headers = get_headers()
return requests.delete(query_url, headers=headers)
18 changes: 9 additions & 9 deletions tidy3d/web/webapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def get_info(task_id: TaskId) -> TaskInfo:
:class:`TaskInfo`
Object containing information about status, size, credits of task.
"""
method = os.path.join("fdtd/task", task_id)
method = f"fdtd/task/{task_id}"
info_dict = http.get(method)
if info_dict is None:
raise WebError(f"task {task_id} not found, unable to load info.")
Expand All @@ -120,7 +120,7 @@ def start(task_id: TaskId) -> None:
"""
task = get_info(task_id)
folder_name = task.folderId
method = os.path.join("fdtd/model", folder_name, "task", task_id)
method = f"fdtd/model/{folder_name}/task/{task_id}"
task.status = "queued"
http.put(method, data=task.dict())

Expand All @@ -142,7 +142,7 @@ def get_run_info(task_id: TaskId):
"""

client, bucket, user_id = get_s3_user()
key = os.path.join("users", user_id, task_id, "output", "solver_progress.csv")
key = f"users/{user_id}/{task_id}/output/solver_progress.csv"
progress = client.get_object(Bucket=bucket, Key=key)["Body"]
progress_string = progress.read().split(b"\n")
perc_done, field_decay = progress_string[-2].split(b",")
Expand Down Expand Up @@ -283,7 +283,7 @@ def load(
task_id: TaskId,
simulation: Simulation,
path: str = "simulation_data.hdf5",
replace_existing : bool = True,
replace_existing: bool = True,
) -> SimulationData:
"""Download and Load simultion results into :class:`.SimulationData` object.

Expand Down Expand Up @@ -324,7 +324,7 @@ def delete(task_id: TaskId) -> TaskInfo:
Object containing information about status, size, credits of task.
"""

method = os.path.join("fdtd", "task", str(task_id))
method = f"fdtd/task/{str(task_id)}"
return http.delete(method)


Expand Down Expand Up @@ -353,7 +353,7 @@ def _upload_task( # pylint:disable=too-many-locals
"workerGroup": worker_group,
}

method = os.path.join("fdtd/model", folder_name, "task")
method = f"fdtd/model/{folder_name}/task"

log.debug("Creating task.")
try:
Expand All @@ -368,7 +368,7 @@ def _upload_task( # pylint:disable=too-many-locals

client, bucket, user_id = get_s3_user()

key = os.path.join("users", user_id, task_id, "simulation.json")
key = f"users/{user_id}/{task_id}/simulation.json"

# size_bytes = len(json_string.encode('utf-8'))
# TODO: add progressbar, with put_object, no callback, so no real need.
Expand Down Expand Up @@ -403,9 +403,9 @@ def _download_file(task_id: TaskId, fname: str, path: str) -> None:
client, bucket, user_id = get_s3_user()

if fname in ("monitor_data.hdf5", "tidy3d.log"):
key = os.path.join("users", user_id, task_id, "output", fname)
key = f"users/{user_id}/{task_id}/output/{fname}"
else:
key = os.path.join("users", user_id, task_id, fname)
key = f"users/{user_id}/{task_id}/{fname}"

head_object = client.head_object(Bucket=bucket, Key=key)
size_bytes = head_object["ContentLength"]
Expand Down