corset.solver

Contents

corset.solver#

Mode matching solver and related data structures.

The main entry point is the function mode_match(), it will setup the ModeMatchingProblem. The problem defined with the help of ShiftingRange, Aperture, and Passage instances. The constructed ModeMatchingProblem yields ModeMatchingCandidate instances that are then optimized to produce ModeMatchingSolution instances. Each step containing a reference to the data structure it is based on. The actual constrained optimization is carried out using scipy.optimize.minimize() using the SLSQP method. All solutions will then be collected in a SolutionList for convenient analysis and filtering.

class corset.solver.Aperture(position, radius, power=0.8646647167633873) None#

Aperture constraint for a mode matching problem.

Parameters:
classmethod load_yaml(filename) Self#

Load an object from a YAML file.

If this is called from a subclass the loaded object type must match that subclass.

Parameters:

filename (str | Path) – Path to the YAML file.

Return type:

Self

Returns:

The loaded object.

Raises:
  • ValueError – If the YAML file does not contain a ‘data’ field.

  • TypeError – If the loaded object type does not match the class used to call this method.

save_yaml(filename) None#

Save the object to a YAML file.

Parameters:
  • filename (str | Path) – Path to the YAML file.

  • self (Any)

Return type:

None

position: float#

Axial position of the aperture

power: float = 0.8646647167633873#

Minimum fraction of power that must pass through the aperture. If set to \(1 - e^{-2} \approx 0.865\), the beam’s \(1/e\) amplitude radius at the aperture is constrained to be smaller than the aperture radius.

radius: float#

Aperture radius

property radius_constraints: list[tuple[float, float]]#

A list containing this aperture as a normalized \(1/e\) beam radius constraint tuple (position, radius). This is a tuple of a tuple to provide a uniform interface with Passage which is a tuple of two tuple.

class corset.solver.Focus(position) None#

Focus constraint for a mode matching problem. Constrains the beam to have a focus of any ways at a specified position.

Note

Unlike the other constraints, this is an equality constraint. This means it “costs” an additional degree of freedom for it to be satisfied while maintaining perfect mode matching.

Parameters:

position (float)

classmethod load_yaml(filename) Self#

Load an object from a YAML file.

If this is called from a subclass the loaded object type must match that subclass.

Parameters:

filename (str | Path) – Path to the YAML file.

Return type:

Self

Returns:

The loaded object.

Raises:
  • ValueError – If the YAML file does not contain a ‘data’ field.

  • TypeError – If the loaded object type does not match the class used to call this method.

save_yaml(filename) None#

Save the object to a YAML file.

Parameters:
  • filename (str | Path) – Path to the YAML file.

  • self (Any)

Return type:

None

position: float#

Position of the focus

class corset.solver.ModeMatchingCandidate(problem, populations) None#

A candidate lens population for a mode matching problem.

Parameters:
classmethod load_yaml(filename) Self#

Load an object from a YAML file.

If this is called from a subclass the loaded object type must match that subclass.

Parameters:

filename (str | Path) – Path to the YAML file.

Return type:

Self

Returns:

The loaded object.

Raises:
  • ValueError – If the YAML file does not contain a ‘data’ field.

  • TypeError – If the loaded object type does not match the class used to call this method.

generate_initial_positions(randomize, rng=Generator(PCG64) at 0x7F88C8BE2420) ndarray#

Generate a set of initial positions for free lenses of the candidate.

Parameters:
  • randomize (bool) – Whether to generate random initial positions or evenly spaced positions.

  • rng (Generator, default: Generator(PCG64) at 0x7F88C8BE2420) – Random number generator to use for random positions.

Return type:

ndarray

Returns:

Array of initial positions for the lenses.

Raises:

ValueError – If there is not enough space in a range for the lenses with their margins.

optimize(filter_pred, random_initial_positions, equal_setup_tol, max_solutions, rng=Generator(PCG64) at 0x7F88C8BE26C0) list[ModeMatchingSolution]#

Optimize the candidate to find mode matching solutions.

Parameters:
  • filter_pred (Callable[[ModeMatchingSolution], bool]) – Predicate function that must return True for a solution to be accepted.

  • random_initial_positions (int) – Number of random initial positions to generate in addition to the equally spaced one.

  • equal_setup_tol (float) – Tolerance for considering two solutions as equal for eliminating duplicates.

  • max_solutions (int) – Maximum number of solutions to optimize and return.

  • rng (Generator)

Return type:

list[ModeMatchingSolution]

Returns:

List of optimized mode matching solutions for the candidate.

parametrized_focus_and_waist(positions) ndarray#

Compute the final beam focus and waist depending on the free element positions.

Parameters:

positions (ndarray) – Positions of the free elements.

Return type:

ndarray

Returns:

Array of final beam focus and waist.

parametrized_overlap(positions) float#

Compute the mode overlap depending on the free element positions.

Parameters:

positions (ndarray) – Positions of the free elements.

Return type:

float

Returns:

Mode overlap value.

save_yaml(filename) None#

Save the object to a YAML file.

Parameters:
  • filename (str | Path) – Path to the YAML file.

  • self (Any)

Return type:

None

property constraints: list[NonlinearConstraint | LinearConstraint]#

List of position constraint and potential beam constraint and focus constraints if there are any.

property focus_constraint: NonlinearConstraint#

Nonlinear constraints to ensure focus positions meet specified constraints.

property parametrized_setup: ParametrizedSetup#

Parametrized optical setup for the candidate.

populations: list[tuple[ThinLens | ThickLens, ...]]#

Lens populations for each range

property position_constraint: LinearConstraint#

Linear constraint ensuring lenses do not overlap, stay within ranges and do not swap order.

problem: ModeMatchingProblem#

The parent mode matching problem

property radius_constraint: NonlinearConstraint#

Nonlinear constraint to ensure beam radius is within aperture constraints.

class corset.solver.ModeMatchingProblem(setup, desired_beam, ranges, selection, min_elements, max_elements, constraints) None#

Mode matching problem definition.

Parameters:
classmethod lens_combinations(ranges, base_selection, min_elements, max_elements, current_populations=[]) Generator[list[tuple[ThinLens | ThickLens, ...]], None, None]#

Recursive helper function to generate all possible lens populations for the given ranges.

Parameters:
  • ranges (list[ShiftingRange]) – Remaining ranges to process.

  • base_selection (Sequence[ThinLens | ThickLens]) – Global selection of lenses to choose from.

  • min_elements (int) – Minimum number of elements remaining to place.

  • max_elements (int) – Maximum number of elements remaining to place.

  • current_populations (list[tuple[ThinLens | ThickLens, ...]], default: []) – Current lens populations for the processed ranges.

Yields:

list[tuple[Lens, …]] – The next lens populations for all ranges.

Return type:

Generator[list[tuple[ThinLens | ThickLens, ...]], None, None]

classmethod load_yaml(filename) Self#

Load an object from a YAML file.

If this is called from a subclass the loaded object type must match that subclass.

Parameters:

filename (str | Path) – Path to the YAML file.

Return type:

Self

Returns:

The loaded object.

Raises:
  • ValueError – If the YAML file does not contain a ‘data’ field.

  • TypeError – If the loaded object type does not match the class used to call this method.

candidates() Generator[ModeMatchingCandidate, None, None]#

Generate all possible range population candidates for the mode matching problem.

Return type:

Generator[ModeMatchingCandidate, None, None]

Returns:

Generator of ModeMatchingCandidate instances.

save_yaml(filename) None#

Save the object to a YAML file.

Parameters:
  • filename (str | Path) – Path to the YAML file.

  • self (Any)

Return type:

None

constraints: Sequence[Aperture | Passage | Focus]#

Beam constraints on the optical setup

desired_beam: Beam#

Desired output beam after the optical setup

property interleaved_elements: list[tuple[float, ThinLens | ThickLens] | int]#

List of all (potential) elements, ranges where elements can be placed are represented by their index instead of the (position, element) tuple. Used for easy construction of parametrized setups.

max_elements: int#

Maximum number of elements to use

min_elements: int#

Minimum number of elements to use

ranges: list[ShiftingRange]#

Ranges where lenses can be placed

property raw_radius_constraints: list[tuple[float, float]]#

List of all constraints as \(1/e\) beam radius constraint tuples (position, radius).

selection: Sequence[ThinLens | ThickLens]#

Selection of lenses to choose from for mode matching

setup: OpticalSetup#

Initial optical setup

class corset.solver.ModeMatchingSolution(candidate, positions) None#

A solution to a mode matching problem.

Implements _repr_png_() to show a plot of the solution setup in IPython environments produced by ModeMatchingSolution.plot_all().

Parameters:
classmethod load_yaml(filename) Self#

Load an object from a YAML file.

If this is called from a subclass the loaded object type must match that subclass.

Parameters:

filename (str | Path) – Path to the YAML file.

Return type:

Self

Returns:

The loaded object.

Raises:
  • ValueError – If the YAML file does not contain a ‘data’ field.

  • TypeError – If the loaded object type does not match the class used to call this method.

optimize_coupling(dimensions=None, min_abs_improvement=0.1, min_rel_improvement=0.5) ModeMatchingSolution | None#

Optimize the solution to reduce coupling between least coupled pair or any other pair while maintaining mode matching, returning a new solution if the coupling could be optimized significantly.

Note

This requires that there are at least three elements so that there is at least one degree of freedom left after ensuring perfect mode overlap. If there are fewer degrees of freedom, the it is impossible for the coupling to be improved and the function will always return None.

Parameters:
  • dimensions (tuple[int, int] | None, default: None) – The indices of the degrees of freedom for which the coupling should be optimized. If None, the minimum of all couplings is optimized.

  • min_abs_improvement (float, default: 0.1) – Minimum absolute improvement in coupling to return the new solution.

  • min_rel_improvement (float, default: 0.5) – Minimum relative improvement in coupling to return the new solution.

Return type:

ModeMatchingSolution | None

Returns:

A new ModeMatchingSolution with improved coupling if successful, otherwise None.

Raises:

ValueError – If the solution does not have ~100% mode overlap.

plot_all(*, figsize=None, width_ratios=None, tight_layout=None, setup_kwargs=None, reachability_kwargs=None, sensitivity_kwargs=None) tuple[Figure, tuple[ModeMatchingPlot, ReachabilityPlot, SensitivityPlot]]#

Plot all analyses, see corset.plot.plot_mode_match_solution_all()

Return type:

tuple[Figure, tuple[ModeMatchingPlot, ReachabilityPlot, SensitivityPlot]]

Parameters:
plot_reachability(*, displacement=None, num_samples=None, line_step=None, dimensions=None, focus_range=None, waist_range=None, confidence_interval=None, grid_resolution=None, ax=None) ReachabilityPlot#

Plot the reachability analysis, see corset.plot.plot_reachability()

Return type:

ReachabilityPlot

Parameters:
plot_sensitivity(*, dimensions=None, worst_overlap=None, x_displacement=None, y_displacement=None, z_displacement=None, num_samples_z=None, confidence_interval=None, force_contour_lines=None, grid_resolution=None, ax=None) SensitivityPlot#

Plot the sensitivity analysis, see corset.plot.plot_sensitivity()

Return type:

SensitivityPlot

Parameters:
plot_setup(*, setup_kwargs=None, desired_kwargs=None, ax=None, show_legend=None, legend_loc=None) ModeMatchingPlot#

Plot the solution setup, see corset.plot.plot_mode_match_solution_setup()

Return type:

ModeMatchingPlot

Parameters:
save_yaml(filename) None#

Save the object to a YAML file.

Parameters:
  • filename (str | Path) – Path to the YAML file.

  • self (Any)

Return type:

None

property analysis: ModeMatchingAnalysis#

Analysis data for this solution.

candidate: ModeMatchingCandidate#

The candidate that produced this solution

property overlap: float#

Mode overlap of the solution.

positions: ndarray#

Positions of the lenses in the solution

property setup: OpticalSetup#

Optical setup corresponding to this solution.

class corset.solver.ParametrizedSetup(initial_beam, elements) None#

Parametrized optical setup where some or all element positions are free parameters.

Parameters:
classmethod load_yaml(filename) Self#

Load an object from a YAML file.

If this is called from a subclass the loaded object type must match that subclass.

Parameters:

filename (str | Path) – Path to the YAML file.

Return type:

Self

Returns:

The loaded object.

Raises:
  • ValueError – If the YAML file does not contain a ‘data’ field.

  • TypeError – If the loaded object type does not match the class used to call this method.

save_yaml(filename) None#

Save the object to a YAML file.

Parameters:
  • filename (str | Path) – Path to the YAML file.

  • self (Any)

Return type:

None

substitute(positions, validate=True) OpticalSetup#

Substitute free parameters with given positions.

Parameters:
  • positions (list[float] | ndarray) – Positions to substitute for free parameters in order, must match number of free parameters.

  • validate (bool, default: True) – Whether to validate the positions in the resulting setup.

Return type:

OpticalSetup

Returns:

The resulting optical setup with substituted positions.

Raises:

ValueError – If the number of provided positions does not match the number of free parameters.

elements: list[tuple[float | None, ThinLens | ThickLens]]#

Optical elements as (position | None, element) tuples. None represents a free element / parameter.

property free_elements: list[int]#

List of indices of free elements (positions that are None).

initial_beam: Beam#

Initial beam before left most element

class corset.solver.Passage(left, right, radius, power=0.8646647167633873) None#

Passage constraint for a mode matching problem. A passage from left to right with given radius is represented (i.e. equivalent) to two Aperture constraints with radius at the left and right boundaries.

Parameters:
classmethod centered(center, width, radius, power=0.8646647167633873) Passage#

Convenience constructor for a passage centered at a given position.

Parameters:
  • center (float) – Center position of the passage.

  • width (float) – Width of the passage.

  • radius (float) – Passage radius.

  • power (float, default: 0.8646647167633873) – Minimum power fraction that must pass through the passage.

Return type:

Passage

Returns:

Passage instance centered at the given position.

classmethod load_yaml(filename) Self#

Load an object from a YAML file.

If this is called from a subclass the loaded object type must match that subclass.

Parameters:

filename (str | Path) – Path to the YAML file.

Return type:

Self

Returns:

The loaded object.

Raises:
  • ValueError – If the YAML file does not contain a ‘data’ field.

  • TypeError – If the loaded object type does not match the class used to call this method.

save_yaml(filename) None#

Save the object to a YAML file.

Parameters:
  • filename (str | Path) – Path to the YAML file.

  • self (Any)

Return type:

None

left: float#

Left boundary of the passage

power: float = 0.8646647167633873#

Minimum fraction of power that must pass through the passage (approximately). Since the passage is represented as two apertures, this is really just the power fraction of the respective apertures. If set to \(1 - e^{-2} \approx 0.865\), the beam’s \(1/e\) amplitude radius at the apertures is constrained to be smaller than the passage radius. See Aperture.power.

radius: float#

Passage radius

property radius_constraints: list[tuple[float, float]]#

Representation of the constraint as two normalized \(1/e\) beam radius constraints. A list of two tuples (position, radius) for the left and right boundaries.

right: float#

Right boundary of the passage

class corset.solver.ShiftingRange(left, right, min_elements=0, max_elements=inf, selection=<factory>) None#

Range where lenses can be placed.

Parameters:
classmethod load_yaml(filename) Self#

Load an object from a YAML file.

If this is called from a subclass the loaded object type must match that subclass.

Parameters:

filename (str | Path) – Path to the YAML file.

Return type:

Self

Returns:

The loaded object.

Raises:
  • ValueError – If the YAML file does not contain a ‘data’ field.

  • TypeError – If the loaded object type does not match the class used to call this method.

save_yaml(filename) None#

Save the object to a YAML file.

Parameters:
  • filename (str | Path) – Path to the YAML file.

  • self (Any)

Return type:

None

left: float#

Range left boundary

max_elements: int = inf#

Maximum number of lenses that can be placed in this range.

min_elements: int = 0#

Minimum number of lenses to be placed in this range

right: float#

Range right boundary

selection: Iterable[ThinLens | ThickLens]#

Optional set of lenses to use for this range, if empty the global selection is used.

class corset.solver.SolutionList(solutions) None#

List of mode matching solutions with convenient methods for filtering and sorting.

Supports (array) indexing, iteration, and other list-like operations. Implements _repr_html_() to show a pandas.DataFrame representation in IPython environments.

Parameters:

solutions (list[ModeMatchingSolution])

classmethod load_yaml(filename) Self#

Load an object from a YAML file.

If this is called from a subclass the loaded object type must match that subclass.

Parameters:

filename (str | Path) – Path to the YAML file.

Return type:

Self

Returns:

The loaded object.

Raises:
  • ValueError – If the YAML file does not contain a ‘data’ field.

  • TypeError – If the loaded object type does not match the class used to call this method.

filter(predicate) SolutionList#

Filter solutions based on a predicate function.

Parameters:

predicate (Callable[[ModeMatchingSolution], bool]) – A function that takes a ModeMatchingSolution and returns a boolean.

Return type:

SolutionList

Returns:

A new SolutionList containing only the solutions for which the predicate returns True.

query(expr) SolutionList#

Filter solutions based on a pandas.DataFrame.query() expression applied to the DataFrame representation.

Parameters:

expr (str) – Query string, see pandas.DataFrame.query() for details.

Return type:

SolutionList

Returns:

A new SolutionList containing only the solutions that satisfy the query.

save_yaml(filename) None#

Save the object to a YAML file.

Parameters:
  • filename (str | Path) – Path to the YAML file.

  • self (Any)

Return type:

None

sort_values(by, *, ascending=True, key=None) SolutionList#

Sort solutions based on a column or list of columns in the DataFrame representation.

Parameters:
  • by (str | list[str]) – Column name or list of column names to sort by.

  • ascending (bool, default: True) – Whether to sort in ascending order.

  • key (Callable[[Series], Series] | None, default: None) – Optional callable to transform the column values before sorting, see pandas.DataFrame.sort_values() for details.

Return type:

SolutionList

Returns:

A new SolutionList with solutions sorted by the specified columns.

sorted(key, reverse=False) SolutionList#

Sort solutions based on a key function.

Parameters:
Return type:

SolutionList

Returns:

A new SolutionList with solutions sorted by the specified key.

property df: DataFrame#

DataFrame representation of the solutions for convenient analysis.

solutions: list[ModeMatchingSolution]#

Underlying list of mode matching solutions

corset.solver.mode_match(setup, desired_beam, ranges, selection=[], min_elements=1, max_elements=inf, constraints=[], filter_pred=0.999, random_initial_positions=0, solutions_per_candidate=1, equal_setup_tol=0.001, random_seed=0, cache_dir=None, tqdm_kwargs={'delay': 2, 'desc': 'Optimizing Candidates', 'smoothing': 0.01})#

Solve a mode matching problem by optimizing lens positions while respecting constraints.

Parameters:
  • setup (Beam | OpticalSetup) – Initial optical setup or initial beam.

  • desired_beam (Beam) – Desired output beam after the optical setup.

  • ranges (list[ShiftingRange]) – Shifting ranges where lenses can be placed.

  • selection (Sequence[ThinLens | ThickLens], default: []) – Selection of lenses to choose from for mode matching.

  • min_elements (int, default: 1) – Minimum number of elements to use.

  • max_elements (int, default: inf) – Maximum number of elements to use.

  • constraints (Sequence[Aperture | Passage | Focus], default: []) – Beam constraints on the resulting optical setup.

  • filter_pred (Callable[[ModeMatchingSolution], bool] | float | None, default: 0.999) – Predicate function or minimum overlap float to filter solutions.

  • random_initial_positions (int, default: 0) – Number of random initial positions to generate per candidate.

  • solutions_per_candidate (int, default: 1) – Maximum number of solutions to optimize and return per candidate i.e. lens population.

  • equal_setup_tol (float, default: 0.001) – Tolerance for considering two solutions as equal for eliminating duplicates.

  • random_seed (int, default: 0) – Random seed for reproducibility.

  • cache_dir (Path | None, default: None) – If this is not None cached solutions and look for cached solutions in the provide directory. The cached is unbounded.

  • tqdm_args – Arguments for the tqdm progress bar.

  • tqdm_kwargs (dict)

Returns:

A SolutionList containing the optimized mode matching solutions.

Raises:
  • ValueError – If caching is requested but the filter predicate is not a float, i.e. a function object.

  • ValueError – If the mode matching problem is invalid, e.g contains out of order or overlapping parts.

Note

While most mode matching problems only have a single global optimum, some problems, especially constrained mode matching problems may have local imperfect optima. Since the solver uses a local optimization routine, it may not find the global optimum with the deterministic initial guesses. To give the solver a better chance of finding a solution for a given candidate, it may attempt the optimization with multiple random initial positions, specified by random_initial_positions. The number of initial guesses required to have a reasonable chance of finding an optimum (should it exists) increases with the constraint and setup complexity.

corset.solver.mode_overlap(delta_z, waist_a, waist_b, wavelength) float#

Compute the mode overlap between two Gaussian beams.

Parameters:
  • delta_z (float) – Axial distance between the beam waists.

  • waist_a (float) – Waist radius of the first beam.

  • waist_b (float) – Waist radius of the second beam.

  • wavelength (float) – Wavelength of the beams.

Return type:

float

Returns:

Mode overlap between the two beams.

corset.solver.PERFECT_OVERLAP = 0.999#

Threshold above which the overlap between two beams is considered to be perfect within numerical precision.