Giter VIP home page Giter VIP logo

meow's Introduction

meow

Modeling of Eigenmodes and Overlaps in Waveguides

meow

A simple electromagnetic EigenMode Expansion (EME) tool for Python.

Installation

Minimal installation

pip install meow-sim[min]

Full installation

pip install meow-sim[full]

Selecting features

You can select which features to enable during installation as follows:

pip install meow-sim[feature1,feature2,...]

Available features

  • min: minimal installation (equivalent to not specifying any features)
  • vis: explicitly installs matplotlib and trimesh.
  • jax: use JAX in stead of numpy to calculate the S-matrices
  • klu: use klujax to speed up S-matric calculations (implies jax). Note: you need the SuiteSparse headers on your computer for this to work.
  • gds: enable GDS creation with GDSFactory (see GDS Taper example).
  • ipy: install useful jupyter/ipython packages.
  • dev: install dev dependencies
  • full: enable all the above features.

Documentation

Contributors

Credits

  • DALL-E: “a drawing of a kitten with laser eyes walking towards me” (logo)
  • Tidy3D: meow uses the free FDE mode solver from Tidy3D.
  • SAX: meow uses SAX as its circuit simulator when cascading the overlap S-matrices.
  • klujax: Although technically an optional backend for SAX, klujax will significantly speed up the final S-matrix calculation of your structures.
  • EMEPy: an excellent alternative python-based EME solver with optional neural network mode solver.
  • Rigorous and efficient modeling of wavelength scale photonic components: PhD thesis of Peter Bienstman.

meow's People

Contributors

flaport avatar jan-david-fischbach avatar joamatab avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

meow's Issues

Broken visualization functions

When visualizing cells I get the following error:

The number of FixedLocator locations (3), usually from a call to set_ticks, does not match the number of ticklabels (4).

Furthermore we seem to not provide a shading parameter to pcolormesh (almost everywhere). With newer versions of matplotlib it seems to assume flat, which I don't think is what we want. We rather need nearest (e.g. for plotting the eps distribution)

missing module: mapbox_earcut

On Mac OSX M1 processor, I got as far as the visualization step, then received the following error

mw.visualize(structs, scale=(1, 1, 0.2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/lukasc/gdsfactory/lib/python3.9/site-packages/meow/visualize.py", line 95, in visualize
    return _visualize_structures(objs, **kwargs)
  File "/Users/lukasc/gdsfactory/lib/python3.9/site-packages/meow/structures.py", line 48, in _visualize_structures
    geometry=[s._trimesh(scale=scale) for s in _sort_structures(structures)]
  File "/Users/lukasc/gdsfactory/lib/python3.9/site-packages/meow/structures.py", line 48, in <listcomp>
    geometry=[s._trimesh(scale=scale) for s in _sort_structures(structures)]
  File "/Users/lukasc/gdsfactory/lib/python3.9/site-packages/meow/structures.py", line 33, in _trimesh
    return self.geometry._trimesh(
  File "/Users/lukasc/gdsfactory/lib/python3.9/site-packages/meow/geometries.py", line 256, in _trimesh
    prism = extrude_polygon(poly, self.h_max - self.h_min)
  File "/Users/lukasc/gdsfactory/lib/python3.9/site-packages/trimesh/creation.py", line 194, in extrude_polygon
    vertices, faces = triangulate_polygon(
  File "/Users/lukasc/gdsfactory/lib/python3.9/site-packages/trimesh/creation.py", line 458, in triangulate_polygon
    faces = _tri_earcut(vertices, rings).reshape(
  File "/Users/lukasc/gdsfactory/lib/python3.9/site-packages/trimesh/exceptions.py", line 48, in failed
    raise exc
  File "/Users/lukasc/gdsfactory/lib/python3.9/site-packages/trimesh/creation.py", line 34, in <module>
    from mapbox_earcut import triangulate_float64 as _tri_earcut
ModuleNotFoundError: No module named 'mapbox_earcut'

easy fix:

pip install mapbox_earcut

perhaps you can add it as a dependancy.

Taper sweep length

How can we sweep the length of a taper?

import gdsfactory as gf
import numpy as np
from gdsfactory.simulation.eme import MEOW

layerstack = gf.tech.get_layer_stack_generic()

filtered_layerstack = gf.tech.LayerStack(
    layers={
        k: layerstack.layers[k]
        for k in (
            "slab90",
            "core",
            "box",
            "clad",
        )
    }
)


lengths = np.array([1, 20, 60, 100])
T = np.zeros_like(lengths, dtype=float)

for length in lengths:
    c = gf.components.taper(width2=10, length=length)
    c.plot()

for i, length in enumerate(lengths):
    c = gf.components.taper(width2=10, length=length)
    eme = MEOW(component=c, layerstack=filtered_layerstack, wavelength=1.55)
    sp = eme.compute_sparameters()
    T[i] = np.abs(sp['o1@0,o2@0'])**2

import matplotlib.pyplot as plt

plt.plot(lengths, T, '.')
plt.title('Fundamental mode transmission')
plt.ylabel('Transmission')
plt.xlabel('taper length (um)')

I would expect a short taper would have more loss

image

Additional features for working with modes

Hey @flaport,
I am a big fan of meow. Besides its EME capabilities, I think it makes quite a lot of sense to use it as an abstraction layer over different FDE algorithms, as switching between "simulation backends" can otherwise necessitate significant code rework (for the structure definition alone). Maybe even interesting for gdsfactory (@joamatab) (We could also build a femwell backend for meow). With that in mind, there is a couple of things I'd like to add:

  • Poynting flux: auxiliary properties to calculate the poynting flux in x,y and z.

$$ \vec{P} = \vec{E} \times \vec{H} $$

An implementation using np.cross is probably most sensible. Addressed in #7.

  • Effective mode area: another auxiliary measure I tend to use relatively frequently. It is not that well defined/ agreed on in literature but I would use the definition as in lumerical's implementation:

$$ A_{eff} = \frac{\left(\int|\vec{E}|^2dA\right)^2}{\int|\vec{E}|^4dA} $$

  • Implementation of the field energies for irregular meshes: At this moment the modal energies are computed by summing over the energy densities, which for equidistant meshes leads to a value proportional to the actual modal energy.:
def electric_energy(mode: Mode) -> float:
    """get the electric energy contained in a `Mode`"""
    return electric_energy_density(mode).sum()

The proportionality constant can be eliminated by normalization, as it is not dependent on the field distribution. This does however not hold for non-equidistant meshes, as finely meshed regions are over-emphasized compared to the more coarsely meshed regions. I would therefore suggest dividing by the mesh step in x and y before summing or even better do a proper integration over the energy densities e.g. using nested np.trapz evaluations.

  • I would love to be able to also easily get the group index. That would however require multiple frequency points to do a finite difference differentiation on the effective index with frequency/wavelength, right?

transition from gdspy to gdstk

now that gdsfactory and tidy3d transitioned to gdstk what do you think of transtioning meow to gdstk?

gdstk is faster to install as we have built wheels for it

taper example results inconsistent

Hello,

I am following your example: https://flaport.github.io/meow/examples/02_taper_length_sweep.html

and obtain strange results that don't make sense:

  1. if I run the two lines in order, 10.0, then 5.0:
S1, _ = find_s_matrix(length=10.0)
S2, _ = find_s_matrix(length=5.0)
print(' - %s' % abs(S1[len(S1)//2][0]))
print(' - %s' % abs(S2[len(S2)//2][0]))

I get:

  • 0.94347876
  • 0.9601483

whereas if I run the two lines in reversed order, 5.0, then 10.0:

S2, _ = find_s_matrix(length=5.0)
S1, _ = find_s_matrix(length=10.0)
print(' - %s' % abs(S1[len(S1)//2][0]))
print(' - %s' % abs(S2[len(S2)//2][0]))

I get:

  • 4.663316e-06
  • 0.9602049
  1. For a taper, I expect that a short taper would have higher loss, whereas a longer one would have lower loss. However, the results are opposite. For a 2 micron taper, the simulation predicts 0.98, but 10 µm predicts 0.94. The example you have also shows numbers where the shorter taper is lower loss. Doesn't make sense.

  2. Performing a sweep of the length can be done by changing the cell_length. But when I change it, the results don't change at all.

def cell_length_sweep(length=10.0, length_sweep = np.linspace(2, 20, 10), cell_length=1.0, wl=1.55, Temp=25.0, num_modes=10):
    '''
    Perform a sweep of the taper length.
    Calculate the modes once, and only change the cell length to stretch the structure.
    '''
    modes = find_modes(
        length=length, cell_length=cell_length, wl=wl, T=Temp, num_modes=num_modes
    )
    lengths, T = [], []
    for length1 in tqdm(length_sweep):
        cell_length1 = length1/length*cell_length
        S, port_map = mw.compute_s_matrix(modes, cell_lengths=[cell_length1 for _ in modes])
        T.append ( abs(S[num_modes][0])**2 )
        lengths.append ( length*cell_length1/cell_length )
        print(' length %s, T %s' % (lengths[-1], T[-1]))
        print(' length %s, T %s' % (length1, T[-1]))

    plt.plot(lengths, 10*np.log10(T), '--pb', label='model', linewidth=1.5)
    SizeFont = 19
    plt.xlabel('Taper length (microns)', fontsize=SizeFont)
    plt.ylabel('Transmission (dB)', fontsize=SizeFont)
    plt.show()

  1. Performing simulations on the same total taper length, but only changing the cell_length (hence number of cells) -- I would expect the loss to be lower for smaller cell sizes. But I get higher loss for more cells. Since this is a convergence test, it isn't conclusive if these numbers are not correct.

thank you
Lukas

meow installation problem

Hello Floris,

I am trying to run meow, and wanted to let you know if the challenges I encountered. See below. Also the "import meow" line takes quite a long time; maybe there are a lot of large dependancies like gdsfactory?

Thank you

On Mac OSX:

lukasc@Lukass-Air klayout_dot_config % pip install meow-sim --upgrade
Requirement already satisfied: meow-sim in /opt/homebrew/lib/python3.10/site-packages (0.11.0)
...

lukasc@Lukass-Air klayout_dot_config % python
Python 3.10.13 (main, Aug 24 2023, 22:43:20) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import meow
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/homebrew/lib/python3.10/site-packages/meow/__init__.py", line 14, in <module>
    from .eme import compute_interface_s_matrices as compute_interface_s_matrices
  File "/opt/homebrew/lib/python3.10/site-packages/meow/eme/__init__.py", line 10, in <module>
    from .sax import compute_s_matrix_sax as compute_s_matrix_sax
  File "/opt/homebrew/lib/python3.10/site-packages/meow/eme/sax.py", line 6, in <module>
    import sax
  File "/opt/homebrew/lib/python3.10/site-packages/sax/__init__.py", line 14, in <module>
    from . import backends as backends
  File "/opt/homebrew/lib/python3.10/site-packages/sax/backends/__init__.py", line 8, in <module>
    from ..netlist import Component
  File "/opt/homebrew/lib/python3.10/site-packages/sax/netlist.py", line 13, in <module>
    import networkx as nx
  File "/opt/homebrew/lib/python3.10/site-packages/networkx/__init__.py", line 100, in <module>
    import networkx.classes.filters
  File "/opt/homebrew/lib/python3.10/site-packages/networkx/classes/__init__.py", line 1, in <module>
    from .graph import Graph
  File "/opt/homebrew/lib/python3.10/site-packages/networkx/classes/graph.py", line 23, in <module>
    from collections import Mapping
ImportError: cannot import name 'Mapping' from 'collections' (/opt/homebrew/Cellar/[email protected]/3.10.13/Frameworks/Python.framework/Versions/3.10/lib/python3.10/collections/__init__.py)
>>> 

upgrading networkx seemed to help:

lukasc@Lukass-Air klayout_dot_config % pip install networkx --upgrade
Requirement already satisfied: networkx in /opt/homebrew/lib/python3.10/site-packages (2.0)
Collecting networkx
  Using cached networkx-3.3-py3-none-any.whl.metadata (5.1 kB)
Using cached networkx-3.3-py3-none-any.whl (1.7 MB)
Installing collected packages: networkx
  Attempting uninstall: networkx
    Found existing installation: networkx 2.0
    Uninstalling networkx-2.0:
      Successfully uninstalled networkx-2.0
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
postman-problems 0.3 requires networkx==2.0, but you have networkx 3.3 which is incompatible.
Successfully installed networkx-3.3

but despite having klujax installed, I get the warning:

lukasc@Lukass-Air klayout_dot_config % pip install klujax
Requirement already satisfied: klujax in /opt/homebrew/lib/python3.10/site-packages (0.2.5)

lukasc@Lukass-Air klayout_dot_config % python                      
Python 3.10.13 (main, Aug 24 2023, 22:43:20) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import meow
/opt/homebrew/lib/python3.10/site-packages/sax/backends/__init__.py:58: UserWarning: klujax not found. Please install klujax for better performance during circuit evaluation!
  warnings.warn(

Then on Python 3.11.1:

lukasc@Lukass-Air GitHub % pip install meow-sim --upgrade
Requirement already satisfied: meow-sim in /Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages (0.11.0)
...

lukasc@Lukass-Air GitHub % python
Python 3.11.1 (main, Apr 14 2024, 12:39:36) [Clang 15.0.0 (clang-1500.0.40.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import meow
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages/meow/__init__.py", line 14, in <module>
    from .eme import compute_interface_s_matrices as compute_interface_s_matrices
  File "/Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages/meow/eme/__init__.py", line 10, in <module>
    from .sax import compute_s_matrix_sax as compute_s_matrix_sax
  File "/Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages/meow/eme/sax.py", line 6, in <module>
    import sax
  File "/Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages/sax/__init__.py", line 14, in <module>
    from . import backends as backends
  File "/Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages/sax/backends/__init__.py", line 8, in <module>
    from ..netlist import Component
  File "/Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages/sax/netlist.py", line 22, in <module>
    from .utils import clean_string, hash_dict
  File "/Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages/sax/utils.py", line 26, in <module>
    import jax.scipy.linalg
  File "/Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages/jax/scipy/linalg.py", line 18, in <module>
    from jax._src.scipy.linalg import (
  File "/Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages/jax/_src/scipy/linalg.py", line 403, in <module>
    @_wraps(scipy.linalg.tril)
            ^^^^^^^^^^^^^^^^^
AttributeError: module 'scipy.linalg' has no attribute 'tril'

then I upgrade scipy:

lukasc@Lukass-Air GitHub % pip install scipy --upgrade
Requirement already satisfied: scipy in /Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages (1.13.0)
Collecting scipy
  Downloading scipy-1.14.0-cp311-cp311-macosx_14_0_arm64.whl.metadata (60 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 60.8/60.8 kB 1.3 MB/s eta 0:00:00
Requirement already satisfied: numpy<2.3,>=1.23.5 in /Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages (from scipy) (1.26.4)
Downloading scipy-1.14.0-cp311-cp311-macosx_14_0_arm64.whl (23.1 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 23.1/23.1 MB 20.1 MB/s eta 0:00:00
Installing collected packages: scipy
  Attempting uninstall: scipy
    Found existing installation: scipy 1.13.0
    Uninstalling scipy-1.13.0:
      Successfully uninstalled scipy-1.13.0
Successfully installed scipy-1.14.0

and get the same error:

  File "/Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages/jax/_src/scipy/linalg.py", line 403, in <module>
    @_wraps(scipy.linalg.tril)
            ^^^^^^^^^^^^^^^^^
AttributeError: module 'scipy.linalg' has no attribute 'tril'
lukasc@Lukass-Air GitHub % pip install jax --upgrade
Requirement already satisfied: jax in /Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages (0.4.23)
Collecting jax
  Using cached jax-0.4.30-py3-none-any.whl.metadata (22 kB)
Collecting jaxlib<=0.4.30,>=0.4.27 (from jax)
  Downloading jaxlib-0.4.30-cp311-cp311-macosx_11_0_arm64.whl.metadata (1.0 kB)
Requirement already satisfied: ml-dtypes>=0.2.0 in /Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages (from jax) (0.4.0)
Requirement already satisfied: numpy>=1.22 in /Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages (from jax) (1.26.4)
Requirement already satisfied: opt-einsum in /Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages (from jax) (3.3.0)
Requirement already satisfied: scipy>=1.9 in /Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages (from jax) (1.14.0)
Using cached jax-0.4.30-py3-none-any.whl (2.0 MB)
Downloading jaxlib-0.4.30-cp311-cp311-macosx_11_0_arm64.whl (66.7 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 66.7/66.7 MB 24.7 MB/s eta 0:00:00
Installing collected packages: jaxlib, jax
  Attempting uninstall: jaxlib
    Found existing installation: jaxlib 0.4.23
    Uninstalling jaxlib-0.4.23:
      Successfully uninstalled jaxlib-0.4.23
  Attempting uninstall: jax
    Found existing installation: jax 0.4.23
    Uninstalling jax-0.4.23:
      Successfully uninstalled jax-0.4.23
Successfully installed jax-0.4.30 jaxlib-0.4.30

and it works:

lukasc@Lukass-Air GitHub % python                   
Python 3.11.1 (main, Apr 14 2024, 12:39:36) [Clang 15.0.0 (clang-1500.0.40.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import meow
/Users/lukasc/.pyenv/versions/3.11.1/lib/python3.11/site-packages/sax/backends/__init__.py:58: UserWarning: klujax not found. Please install klujax for better performance during circuit evaluation!
  warnings.warn(
>>> 

Conclusion: the required dependancies for the meow package should be updated.

thank you
Lukas

documentation suggestions

Hello Floris,

I could not find anywhere in the documentation where to set the wavelength for the simulations. I am guessing it has a default somewhere of 1.55 µm? In the example, I see "wl=1.55".

The example https://flaport.github.io/meow/examples/02_taper_length_sweep.html calls tqdm, which is undefined:
for cs in tqdm(css):

adding
from tqdm import tqdm
helps.

It would be helpful to describe the S-matrix format, e.g., top left quadrant is the back-reflection, top right is the transmission. Use abs(S1[num_modes][0]) to find the transmission amplitude for the fundamental mode.

Support for unequal number of modes in adjacent cross sections

Currently meow fails complaining about the A matrix being non-square here:

T_LR = np.linalg.solve(LHS, RHS)

This can be solved as shown here:
https://github.com/Jan-David-Black/meow/tree/lstsq

which is analogous to the approach by emepy (taking the pseudo-inverse):
https://github.com/BYUCamachoLab/emepy/blob/b22bd7e07a58b50d65be75569e5269640cf3bd4e/emepy/models.py#L575

In my current branch sax however refuses to work with the resulting s-matrices and I dont really know why...
It just spits out an empty dict.

CVCS method

Improve Continuously Varying Cross-sectional Subcell (CVCS) method for tapers

Kernel crashes when using PML

The ipython kernel crashes without an error message when specifying any num_pml unequal to (0,0) and using compute_modes subsequently on an M1 mac.
I suspect there is an incompatibility between the Tidy3D FDE solver and m1 silicon. I have however not yet traced back the origin of the crash.

The issue looks similar to microsoft/vscode-jupyter#9741
However, I do not run out of memory while the kernel crashes.

Self defined material and profile monitor

Mr Laporte,

I am new to this fantastic tool and I am obsessed with it already. Thank you for developing such a rare jewel!

Please forgive me for asking two simple questions (I am new..):

  1. How can one define a non built-in material with a refractive index? What are the relevant classes, variables as well as syntax for this?
  2. In addition to S-matrix, a propagation profile is also desirable for understanding. How can one plot it and again what are the relevant classes, variables as well as syntax for this?

Thanks a lot in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.