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.
- 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:
- 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.
- 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:
- 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.
- class corset.solver.ModeMatchingCandidate(problem, populations) None#
A candidate lens population for a mode matching problem.
- Parameters:
problem (ModeMatchingProblem)
- 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:
- 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:
- Return type:
- 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:
- 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.
- parametrized_overlap(positions) float#
Compute the mode overlap depending on the free element positions.
- 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.
- 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:
- 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:
- Returns:
Generator of
ModeMatchingCandidateinstances.
- 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.
- 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).
- 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 byModeMatchingSolution.plot_all().- Parameters:
candidate (ModeMatchingCandidate)
positions (ndarray)
- 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:
- 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. IfNone, 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:
- Returns:
A new
ModeMatchingSolutionwith 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:
- Parameters:
self (ModeMatchingSolution)
confidence_interval (float | None)
grid_resolution (int | None)
ax (Axes | None)
- 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:
- 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:
- Parameters:
- property analysis: ModeMatchingAnalysis#
Analysis data for this solution.
- candidate: ModeMatchingCandidate#
The candidate that produced this 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.
- 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:
- 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.
- substitute(positions, validate=True) OpticalSetup#
Substitute free parameters with given positions.
- Parameters:
- Return type:
- Returns:
The resulting optical setup with substituted positions.
- Raises:
ValueError – If the number of provided positions does not match the number of free parameters.
- 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
Apertureconstraints with radius at the left and right boundaries.- classmethod centered(center, width, radius, power=0.8646647167633873) Passage#
Convenience constructor for a passage centered at a given position.
- Parameters:
- Return type:
- 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:
- 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.
- 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.
- 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:
- 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.
- 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 apandas.DataFramerepresentation 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:
- 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 aModeMatchingSolutionand returns a boolean.- Return type:
- Returns:
A new
SolutionListcontaining only the solutions for which the predicate returnsTrue.
- query(expr) SolutionList#
Filter solutions based on a
pandas.DataFrame.query()expression applied to the DataFrame representation.- Parameters:
expr (
str) – Query string, seepandas.DataFrame.query()for details.- Return type:
- Returns:
A new
SolutionListcontaining only the solutions that satisfy the query.
- 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, seepandas.DataFrame.sort_values()for details.
- Return type:
- Returns:
A new
SolutionListwith solutions sorted by the specified columns.
- sorted(key, reverse=False) SolutionList#
Sort solutions based on a key function.
- Parameters:
key (
Callable[[ModeMatchingSolution],float]) – A function that takes aModeMatchingSolutionand returns a float for sorting.reverse (
bool, default:False) – Whether to sort in descending order.
- Return type:
- Returns:
A new
SolutionListwith 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 notNonecached 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
SolutionListcontaining 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.
- corset.solver.PERFECT_OVERLAP = 0.999#
Threshold above which the overlap between two beams is considered to be perfect within numerical precision.