Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Python API リファレンス

import lensbench as lb の名前の一覧です(型スタブ lensbench.pyi から作る)。版・単位・座標の約束は Python API の約束、使い方は Python から使う。

目次

関数

関数説明
analysesThe analyses of the registry: a list of dicts {name, about, help, params}.
coating_catalogsRegistered coating catalogs: {catalog name: [coating names]}
defaultsThe default settings of an analysis of the registry, or of "optimize" or "zoom", as a dict…
interference_detectorInterferogram on the image surface: interpolates the ray grids (pupil², uniformly illumina…
interferogramInterferogram on the pupil (like OpticStudio's Interferogram): the wavefronts (OPD [waves]…
plugin_specA plugin's description → {"name", "kind", "doc", "config" (list of dicts of setting items)…
pluginsThe registered plugins → [(name, kind), ...]
progressPrint the progress on one line to standard error: lensbench:progress 3/10 message.
read_batchRead a batch result file (JSONL): (head dict, [{"i", "seed", "result"}] in numbering order…
register_coating_catalogRegister a coating catalog (replaces one with the same name).
register_pluginRegister a Python function as a plugin (replaces one with the same name).
register_shapeRegister a Python function as a user-defined shape (surface type USERSHAPE; replaces one w…
register_sourceRegister a Python function as a user-defined source (replaces one with the same name; for …
run_batchBatch run: calls func(i, system, seed) for each set of plan.
run_settingsSettings passed by lensbench run.
source_modelsRegistered user-defined source models: {name: description}
source_raysRays of a registered user-defined source model name with the settings config (dict) at the…
swap_searchCatalog lens swap search: runs in parallel the sets with the lens blocks of project (path …
trace_manyTrace many systems together in one call.
unregister_coating_catalogRemove a registered coating catalog (True if there was one)
unregister_pluginRemove a registration (True if there was one)
unregister_shapeRemove a registered shape (True if there was one)
unregister_sourceRemove a registered source (True if there was one)
verifyVerification: runs descriptions (*.verify.json) or folders containing them (one or a list)…
verify_compareUse only the comparison of verification: compares the outputs actual with the references e…
zoomZoom trajectory: solves vars ("G2.shift" or ("G2.shift", lower, upper)) for each state (sy…

クラス

クラス説明
CancelledErrorThe calculation was cancelled
ErrorBase of lensbench errors (a child of ValueError, so except ValueError also catches it)
GridA sweep grid: the Cartesian product of {"3.t": [10, 11, 12], "5.dx": [0, 0.01]} (the value…
InvalidErrorInvalid value or configuration
PluginA plugin with fixed settings.
ReadErrorError reading a file
SamplerSampling (Monte Carlo): adds perturbations from a distribution per parameter to the nomina…
SystemAn optical system (read from .zmx or a project file .json)
UnsupportedErrorUses an unsupported feature

定数

定数

名前型説明
API_VERSIONtuple[int, int]Python API version (goes up with changes that break compatibility; docs/python.md)

関数

analyses

analyses() -> list[Any]

The analyses of the registry: a list of dicts {name, about, help, params}. params lists the settings (name, type, default, unit, doc, and choices, min, len where they apply), the same as the keyword arguments of System.analyze

coating_catalogs

coating_catalogs() -> dict[str, list[str]]

Registered coating catalogs: {catalog name: [coating names]}

defaults

defaults(name: str) -> Any

The default settings of an analysis of the registry, or of "optimize" or "zoom", as a dict (the defaults of System.optimize, zoom and the analysis methods come from here)

interference_detector

interference_detector(sample: System, reference: System, field: _Field = ..., wave: int | None = None, pupil: int = 65, npx: int = 256, center: tuple[float, float] | None = None, width: float | None = None, sample_power: float = 1.0, reference_power: float = 1.0, delay: float = 0.0, polarized: bool = False, sample_input: str = 'x', reference_input: str = 'x', threads: int | None = None) -> _InterferenceDetector

Interferogram on the image surface: interpolates the ray grids (pupil², uniformly illuminated) of the two paths, sample and reference, onto the pixels of the image surface (npx², center center = (x, y), side width [mm]; the range both reach if omitted) and adds the fields. With polarized, superposes the fields of polarization traces (input polarizations sample_input and reference_input; coatings from the sample system). Returned dict: x and y (pixel centers [mm]), intensity, i_sample and i_reference ((npx, npx), rows = y), opd [waves] and visibility (only pixels both reach, NaN elsewhere), ok_sample and ok_reference, wavelength [µm], fold (fraction folded back)

interferogram

interferogram(beam1: System, beam2: System | None = None, field: _Field = ..., wave: int | None = None, n: int = 64, scale: float = 1.0, xtilt: float = 0.0, ytilt: float = 0.0, threads: int | None = None) -> _Interferogram

Interferogram on the pupil (like OpticStudio's Interferogram): the wavefronts (OPD [waves] relative to each chief ray and reference sphere) of beam 1 (beam1) and beam 2 (beam2; the reference sphere if None) are subtracted at the same normalized pupil coordinates, Δ = scale·(W1 − W2) + (xtilt·px + ytilt·py)/2 (tilts in fringes per pupil diameter), intensity (1 + cos 2πΔ)/2. For a multi-configuration system pass the system of System.config(k). The grid is the same as OpticStudio's Interferogram (p_i = (i − n/2 + 1)/(n/2 − 1); the pupil is normalized entrance pupil coordinates = OS with Use Exit Pupil off). Returned dict: p (normalized pupil coordinates of the grid), delta and intensity ((n, n), rows = py, NaN outside), pv and rms (of scale·(W1 − W2) [waves], without the tilts)

plugin_spec

plugin_spec(name: str) -> _PluginSpec

A plugin's description → {"name", "kind", "doc", "config" (list of dicts of setting items), "inputs", "outputs" (list of dicts of output name, dtype, shape and unit)}

plugins

plugins() -> list[tuple[str, str]]

The registered plugins → [(name, kind), ...]

progress

progress(done: int, total: int, message: str = '') -> None

Print the progress on one line to standard error: lensbench:progress 3/10 message. lensbench run picks up this line and logs it; a future GUI will use it to show progress

read_batch

read_batch(path: _StrPath) -> tuple[Any, list[Any]]

Read a batch result file (JSONL): (head dict, [{"i", "seed", "result"}] in numbering order)

register_coating_catalog

register_coating_catalog(name: str, files: Sequence[_StrPath] = ..., dat: str | None = None, models: Mapping[str, Any] | None = None) -> int

Register a coating catalog (replaces one with the same name). files are coating model (.lbcm, .lbcb), measured table (.lbct) or coating file (COATING.DAT format: MATE, COAT, TABLE) files, dat is text in the COATING.DAT format. models is {coating name: func} of coatings whose coefficients a Python function computes (for prototypes: only inside this Python process, not from the CLI or GUI): func(wl, n1, n2, cos1, path, from_substrate) -> {"rs", "rp", "ts", "tp"} (complex arrays like cos1, power-normalized amplitudes; path is "transmit", "mirror" (n2 is NaN) or "reflect"). It is called once per wavelength, indices, path and side with cos1 on a grid of 2001 points from 0 to 1, and the coefficients are interpolated linearly in cos1. The coatings are looked up by the surface's coating name before the coating file of the .zmx and the coating folder. Returns the number of coatings. A coating with the same name in another registered catalog is an error. Register before loading the systems that use it (a system reads its coatings once, at the first polarization trace)

register_plugin

register_plugin(name: str, func: Callable[..., Mapping[str, Any]], kind: str = 'analysis', needs_system: bool = False) -> None

Register a Python function as a plugin (replaces one with the same name). func(config: dict, inputs: dict[str, ndarray]) -> dict[str, array]. Arrays are passed together per call. When called with a system, func(config, inputs, system). With needs_system=True the system's coatings are read before passing it

register_shape

register_shape(name: str, func: Any, params: Any = None) -> None

Register a Python function as a user-defined shape (surface type USERSHAPE; replaces one with the same name; for prototypes: only inside this Python process, not from the CLI or GUI). func(config: dict, x: ndarray, y: ndarray) -> (z, dzdx, dzdy) gives the sag added to the conic and its gradient. params is {name: default} of its numeric settings. When a shape is prepared the function is called once on a grid of grid × grid points (setting, default 65) from −radius to radius mm (setting, default 10), and the sag is interpolated by bicubic Hermite interpolation of the values and gradients (the settings are not variables)

register_source

register_source(name: str, func: Any) -> None

Register a Python function as a user-defined source (replaces one with the same name; for prototypes: only inside this Python process, not from the CLI or GUI). func(config: dict, wl: float) -> dict returns start and direction ((rays, 3), object coordinates) and weight ((rays,)) for the wavelength wl [µm]. It is called once per wavelength

run_batch

run_batch(func: Callable[..., Any], plan: Any, n: int | None = None, out: _StrPath | None = None, threads: int | None = None, resume: bool = True, progress: Callable[[int, int], Any] | None = None, header: Any = None) -> list[Any]

Batch run: calls func(i, system, seed) for each set of plan. Passing an extension's Rust simulation (crate::ext::NativeTask) as func runs it on the set's system in Rust (without the GIL).

  • plan: a Sampler or Grid. system is the system with the values of the i-th set, seed a seed per task (for noise and the like)
  • n: number of sets (all for a Grid if omitted)
  • out: JSONL to write the results to (the first line has the version, system hash, seed and how the sets are made; then one set per line in the order finished). After a stop, resume=True continues the same file (an error if the head differs). None writes nothing
  • threads: number of threads (1 for sequential). progress: omitted or True prints progress and time left to standard error (every second), False prints nothing, a function is called with a dict (done total ran elapsed eta)
  • header: values added to the head (a dict that can go into JSON and so on; the same when resuming)

func returns a value that can go into JSON (dict, list, numbers, strings, numpy arrays and scalars; NaN and inf become None).

Returns a list of results in numbering order (read back from the file if out is given). If func raises, no new set is started and the same exception is raised after the running sets finish (the written results remain, so it can be resumed). The same with Ctrl-C

run_settings

run_settings() -> _RunSettings

Settings passed by lensbench run. All are read from environment variables; empty or None if not set

  • glass_dirs: folders to search for glass catalogs (LENSBENCH_GLASSCAT; System.load and others also read it)
  • coatings: coating tables and models (LENSBENCH_COATINGS; the default of coatings= of System.load)
  • threads: number of threads (LENSBENCH_THREADS; the default of calculations with threads= omitted)
  • out: output folder (LENSBENCH_OUT); for the script's own use
  • log: log file (LENSBENCH_LOG)
  • args: arguments passed to the script (same as sys.argv[1:])
  • under_run: whether started from lensbench run

source_models

source_models() -> dict[str, str]

Registered user-defined source models: {name: description}

source_rays

source_rays(system: System, name: str, config: Mapping[str, Any] | None = None, wave: int | None = None, frame: str = 'object') -> dict[str, Any]

Rays of a registered user-defined source model name with the settings config (dict) at the wavelength number wave (primary wavelength if omitted). frame is "object" (the object coordinate system, as trace_rays) or "global". Returned dict: start and direction ((rays, 3); directions as the source gave them) and weight ((rays,)). Pass start and direction to system.trace_rays(start, direction, waves=[wave], frame=frame)

swap_search(project: _StrPath, spec: Any, glass_dirs: Sequence[_StrPath] | None = None, lens_catalogs: Sequence[_StrPath] | None = None, top: int = 0, threads: int | None = None, out: _StrPath | None = None, resume: bool = True) -> Any

Catalog lens swap search: runs in parallel the sets with the lens blocks of project (path of a project file) swapped for the candidates of spec (a dict or JSON string; the same as the CLI's swap --spec: slots, vars, merit, iters, efl, state and so on) and optimizes the variables of each set. Returns a list of result dicts per set (smallest merit first; the first top if top > 0). Each dict is the same as the results of the CLI's swap --json (i, lenses, merit0, merit, image_merit, vars, efl, stop, iterations, total_track; error if it can't be evaluated). With out (JSONL) each set is written as it finishes; with resume it continues from the file of the same search (the batch form)

trace_many

trace_many(systems: Sequence[System], field: _Field | None, px: ArrayLike, py: ArrayLike, waves: Sequence[int] | None = None, last: int | None = None, record: bool | Sequence[int] = ..., pol: bool | int | None = None, pol_phase: bool = False, globals: bool = False, object: _ObjectPoint | None = None, grad: Sequence[str] | None = None, threads: int | None = None, pupil: str = 'normalized', dz: float | ArrayLike | None = None, land: bool = False) -> list[_TraceResult]

Trace many systems together in one call. Returns a list of dicts, one per system, each bit for bit the same as systems[i].trace(field, px, py, ...) (for any number of threads).

The arguments are as in System.trace, the same for all systems (grad parameter names are resolved per system). Parallel over both systems and rays, so all cores are used even with few rays per system. threads is the total number of threads (1 for sequential)

unregister_coating_catalog

unregister_coating_catalog(name: str) -> bool

Remove a registered coating catalog (True if there was one)

unregister_plugin

unregister_plugin(name: str) -> bool

Remove a registration (True if there was one)

unregister_shape

unregister_shape(name: str) -> bool

Remove a registered shape (True if there was one)

unregister_source

unregister_source(name: str) -> bool

Remove a registered source (True if there was one)

verify

verify(paths: Any, ci: bool = False) -> Any

Verification: runs descriptions (*.verify.json) or folders containing them (one or a list) with the registered plugins (bundled ones and those added with register_plugin) and returns a list of result dicts per verification (the same form as the reports of lensbench verify --json). ci=True skips verifications with ci: false

verify_compare

verify_compare(actual: Mapping[str, Any], expected: Mapping[str, Any], checks: Mapping[str, Any]) -> Any

Use only the comparison of verification: compares the outputs actual with the references expected (name → array) by checks (name → {abs, rel, exact, note}, the same as the checks of a description) and returns a list of result dicts per quantity. Every reference name needs checks

zoom

zoom(systems: Sequence[System], vars: Sequence[str | tuple[str, float, float]], efl: Sequence[float | None] | None = None, pmag: Sequence[float | None] | None = None, steps: int = 0, merit: str = 'spot', reference: str = 'centroid', rings: int = 3, iters: int = 50, tol: float = 1e-08, threads: int | None = None, method: str = 'lagrange', qr: bool = False, gtol: float = 0.0, active_set: bool = False, stopped_as_vignetted: bool = False) -> _Zoom

Zoom trajectory: solves vars ("G2.shift" or ("G2.shift", lower, upper)) for each state (systems: a system per zoom position, all of the same form). The merit is the RMS of the image (merit: "spot", "wavefront"; all fields, polychromatic) and the target of efl or pmag (a list of values per state; None for no target). steps is the number of points between neighboring states (continuation). method is how to meet the targets: "penalty" (raise the weight of the target term) or "lagrange" (augmented Lagrangian: shift the target of the term). qr, gtol and active_set are the DLS settings of each point, and stopped_as_vignetted drops stopped rays like vignetted rays (as in System.optimize). Returned dict: quantity ("efl", "pmag"), names (variable names), path (a list of point dicts: pos, state (state number; None for points in between), target, value (paraxial quantity), x, merit (merit of the image only), stop ("failed" if not solved; the point keeps its start values), error (why), iterations), systems (solved system per state), warnings

クラス

CancelledError

The calculation was cancelled

Error

Base of lensbench errors (a child of ValueError, so except ValueError also catches it)

Grid

A sweep grid: the Cartesian product of {"3.t": [10, 11, 12], "5.dx": [0, 0.01]} (the values themselves). The first axis changes slowest in numbering

メソッド・属性: Grid(…)・draw・system

Grid

Grid(system: System, axes: Any) -> Grid

Grid.draw

Grid.draw(i: int) -> dict[str, Any]

Values of the i-th set: {name: value}

Grid.system

Grid.system(i: int) -> System

The system with the values of the i-th set

InvalidError

Invalid value or configuration

Plugin

A plugin with fixed settings. Plugin(name, **config). run(**inputs) → dict, run_many([inputs, ...], threads=None) → [dict, ...]

メソッド・属性: Plugin(…)・config・kind・name・run・run_many

Plugin

Plugin(name: str, **config: Any) -> Plugin

Plugin.config

config: dict[str, Any]  # 属性

The settings (dict)

Plugin.kind

kind: str  # 属性

Plugin.name

name: str  # 属性

Plugin.run

Plugin.run(system: System | None = None, **inputs: Any) -> dict[str, Any]

Call once → a dict of named arrays (Rust plugins compute without the GIL). system is the lb.System passed to plugins that trace the system

Plugin.run_many

Plugin.run_many(inputs: Any, system: System | None = None, threads: int | None = None) -> list[Any]

Call with many inputs (a list of dicts) together → [dict, ...]. Parallel over inputs with threads threads (None for the default); results are in input order and independent of the number of threads. If any fails, the first error is raised

ReadError

Error reading a file

Sampler

Sampling (Monte Carlo): adds perturbations from a distribution per parameter to the nominal values of the system.

  • params: {"3.t": 0.02, "5.dx": ("uniform", -0.01, 0.01), "G.tx": ("trunc", 0.05, 2.0)} (a number alone is the σ of a normal distribution)
  • corr: correlation matrix (in the order of params). The marginal distributions stay as they are; correlation comes from a Gaussian copula
  • seed: random seed. The i-th set depends only on (seed, i) (not on the number of threads, resuming or order)

メソッド・属性: Sampler(…)・draw・seed・system

Sampler

Sampler(system: System, params: Any, corr: Sequence[Sequence[float]] | None = None, seed: int = 0) -> Sampler

Sampler.draw

Sampler.draw(i: int) -> dict[str, Any]

Values of the i-th set (nominal + perturbation): {name: value}

Sampler.seed

seed: int  # 属性

Sampler.system

Sampler.system(i: int) -> System

The system with the values of the i-th set

System

An optical system (read from .zmx or a project file .json)

メソッド・属性: active_config・add_glass_catalogs・add_pickup・add_solve・aiming・analyze・beam_paths・beam_table・beams・cardinal・config・config_count・config_names・configs・define_unit・delete_surface・dispersion_warnings・fiber_coupling・field_type・fields・find_surface・floating_clip・floating_clip・from_json・from_project・geo_mtf・get_param・ghost・ghost_origin・ghost_pairs・hash・huygens_mtf・huygens_psf・hxhy・image・image_sim・infinite・insert_surface・load・load_beams・load_configs・macro_warnings・make_thermal・mech_check・mech_clip・mech_clip・merit_jacobian・mtf・mtf_field・mtf_focus・name・object_of・optimize・pickups・primary・psf・pupil_reversed・remove_config_row・remove_pickup・remove_solve・rms・save・set_config・set_config_count・set_config_names・set_config_row・set_field_type・set_material・set_param・set_params・set_stop・set_surface・set_surface_type・set_unit_pivot・solve_ray・solves・stop・surface・surface_count・system_data・to_json・tolerance・trace・trace_rays・units・wavelengths・weights・with_params

System.active_config

active_config: int  # 属性

The configuration in the current system (from 1)

System.add_glass_catalogs

System.add_glass_catalogs(names: Sequence[str], dirs: Sequence[_StrPath] | None = None) -> list[str]

Read glass catalogs (AGF names, e.g. "SCHOTT") and add them to the system. dirs are where to search (default places if omitted). Returns the names of the catalogs not found

System.add_pickup

System.add_pickup(dst: _Surf, src: _Surf, what: str, scale: float = 1.0, offset: float = 0.0, src_what: str | None = None) -> None

Add a pickup: what of surface dst = scale × src_what of surface src + offset (replaces one with the same target and quantity). what is c r t k p1… dn disp semi before0–4 after0–4 (tilts and decenters before and after the surface: dx dy tx ty tz). src_what defaults to what (e.g. to take the after of a surface from the before of the source surface: what="after0", src_what="before0")

System.add_solve

System.add_solve(surf: _Surf, kind: str = 'marginal_height', value: float = 0.0, other: _Surf | None = None, param: float = 0.0) -> None

Add a solve on surface surf (replaces one on the same surface and quantity). kind is, for thickness, marginal_height (default), marginal_height_zone, chief_height, pupil_position, edge, opd, position, compensator, center_of_curvature; for curvature, marginal_angle, chief_angle, marginal_normal, chief_normal, aplanatic, element_power, concentric_surface, concentric_radius, f_number. value is its value (height, angle, length and so on), param is the pupil zone of marginal_height_zone and opd or the height of edge, other the surface for kinds that refer to another surface

System.aiming

aiming: str  # 属性

Ray aiming ("off", "paraxial", "real")

System.analyze

System.analyze(name: str, threads: int | None = None, **settings: Any) -> Any

Run an analysis of the registry by name, with the same settings and results as the CLI subcommand of that name and serve's analyze (lensbench.analyses() lists the names and settings). The settings are keyword arguments with the keys of the settings (field and wave are numbers from 1, e.g. max_freq=100); omitted ones take the defaults of the analysis definition (lensbench.defaults(name)). Analyses that read other configurations or the system file (interference, etc.) can't run here. threads is the number of threads. Returns the result as a dict (lists, not NumPy arrays)

System.beam_paths

System.beam_paths(path: _StrPath, glass_dirs: Sequence[_StrPath] | None = None, state: str | None = None, lens_catalogs: Sequence[_StrPath] | None = None) -> list[str]

The beam splitter paths of a project file (.json) (strings of T and R in the order the BSs are passed). Empty without a BS. Read each with load(path, beam_path=path)

System.beam_table

System.beam_table(path: _StrPath, field: int = 1, wave: int | None = None, grid: int = 21, reference: str | None = None, all: bool = False, glass_dirs: Sequence[_StrPath] | None = None, lens_catalogs: Sequence[_StrPath] | None = None, threads: int | None = None) -> _BeamTable

Beam table of a project file (.json), the same as the CLI lensbench beams and serve's analyze "beams": for each beam, the pupil-averaged coating and Fresnel transmission (unpolarized, including the splitting ratio), the fraction of vignetted rays of the pupil grid (side grid), the chief-ray optical path to the image surface [mm] and its difference from the reference beam (reference: a beam name; the first beam with role "reference" if omitted, else the first beam). field and wave are numbers from 1 (the primary wavelength if wave is omitted). Beams marked off are left out unless all. Returns a dict with field, wavelength_um, reference, beams (a list of rows) and notes

System.beams

System.beams(path: _StrPath) -> list[_Beam]

The beams of a project file (.json): named beam splitter paths, as written in the file. Each is a dict with name, path (T and R in the order the BSs are passed, None for the project's path), state (the state applied to the beam), role ("sample", "reference", "stray" or None), turn (the lens surface where the beam is partly reflected back, a dict of block, surface and pass, or None) and off (left out of the default set). Empty without beams. Read a beam with load(path, state=name) or several with load_beams

System.cardinal

System.cardinal(wave: int | None = None) -> _Cardinal

Cardinal points (like OpticStudio's Cardinal Points). wave is a wavelength number (from 1; primary wavelength if omitted).

The paraxial system from surface 1 to the surface before the image (Y-Z plane). Object-space positions are from the vertex of surface 1 and image-space positions from the vertex of the image surface, each along its local z [mm] (as in OpticStudio; with an odd number of mirrors n_image and f_image are negative). efl is in air (the same as EFFL), f_object and f_image are focal lengths in the media (negative in object space). bfl is from the last surface and ffl from surface 1 to the focus. inf for an afocal system. Returns the values of the system after changes such as set_param.

System.config

System.config(k: int) -> System

A new system with the values of configuration k (from 1) (the original system is not changed)

System.config_count

config_count: int  # 属性

Number of configurations (1 without a table)

System.config_names

System.config_names(spec: str) -> list[str]

The names per configuration of a material or coating row of the table (configs() gives their indices)

System.configs

System.configs() -> list[tuple[str, list[float]]]

The multi-configuration table: a list of (parameter name, values per configuration). Material and coating rows hold indices into their names (config_names)

System.define_unit

System.define_unit(name: str, spans: Sequence[tuple[int, int]], pivot: tuple[float, float, float] = ...) -> None

Define a lens or group. spans is a list of surface ranges (first, last) (two when the same lens is passed twice, such as the way out and back of a double pass), pivot the center of rotation (coordinates with the vertex of the first surface of the first range as origin). Then changed with "name.dx" and so on

System.delete_surface

System.delete_surface(s: _Surf) -> list[str]

Delete surface s. Returns a list describing the pickups, solves and multi-configuration rows that referred to it (also as warnings)

System.dispersion_warnings

System.dispersion_warnings() -> list[str]

Warnings for materials whose index is computed at wavelengths outside the valid range of the dispersion formula (LD of the AGF; the formula is extended)

System.fiber_coupling

System.fiber_coupling(na_source: float, na_receiver: float | None = None, wave: int | None = None, source: tuple[float, float] = ..., receiver: tuple[float, float] = ..., grid: int = 101, na_max: float | None = None, pol: bool = False, clip_stop: bool = True) -> _FiberCoupling

Coupling efficiency into a single-mode fiber (like OpticStudio's FICL). The source is the object point source (local [mm] on the object surface), the receiver the local point receiver on the image surface, both Gaussian modes with a far-field 1/e² NA (na_receiver defaults to na_source). Directions with sin θ ≤ na_max in object space (min(3·NA/n, 0.999) if omitted) are sampled on a grid × grid and the overlap integral is taken in the direction space of the receiver. dict: eta (coupling efficiency), system (fraction of the source power reaching the receiver), receiver (eta/system), phase_step (largest phase difference between neighboring grid points [rad]; a warning above π/2, increase grid). With pol=True also the polarized overlap with coatings jones ((2, 2) complex, [exit x/y, input x/y]; the coupling of input polarization e is |jones @ e|²). With clip_stop=True (default) light passing outside the system stop (a circle of the stop radius without an aperture) counts as system loss (as FICL). Finite-object systems only

System.field_type

field_type: Any  # 属性

The field type: "angle", "object_height", "paraxial_image_height", "real_image_height", or ("solve", ("dirsum", surface1, surface2)) and so on for a field given by a condition

System.fields

fields: list[tuple[float, float]]  # 属性

Fields (x, y)

System.find_surface

System.find_surface(target: str) -> int

Find a surface by number or name (comment) and return its surface number

System.floating_clip

floating_clip: bool  # 属性

Whether rays outside floating apertures (surfaces with fixed semi-diameters, FLAP in .zmx) are vignetted (default True, as in OpticStudio). Set False to compare with the older model that doesn't vignette at semi-diameters

System.floating_clip

System.floating_clip(value: bool) -> None

System.from_json

System.from_json(text: str, glass_dirs: Sequence[_StrPath] | None = None) -> System

Make a system from the JSON string of a system file (the coatings paths are used as they are). glass_dirs: folders to search for the glass catalogs first (then LENSBENCH_GLASSCAT and the catalogs already read)

System.from_project

System.from_project(project: Any, base: _StrPath | None = None, glass_dirs: Sequence[_StrPath] | None = None, state: str | None = None, lens_catalogs: Sequence[_StrPath] | None = None, coatings: Sequence[_StrPath] | None = None, coating_file: _StrPath | None = None, beam_path: str | None = None) -> System

Expand a project (a system built from blocks) from a JSON string or dict, without a file.

  • project: a JSON string of the same form as a project file, or a dict
  • base: the folder that relative paths (such as the path of a zmx block) are based on (current folder if omitted)
  • the rest as in load. Pickups of an imported .zmx that can't be kept in the expansion (referring outside the range and so on) are fixed at their values and reported in warnings

System.geo_mtf

System.geo_mtf(field: _Field, freqs: ArrayLike, wave: int | None = None, n: int = 128, diff_limit: bool = False, threads: int | None = None, axes: str = 'field') -> _MtfResult

Geometric MTF: from the distribution of ray positions. n is a guide for the number of pupil quadrature points; diff_limit applies the diffraction-limited MTF. The returned dict has the same form as mtf. axes is "field" (default; tangential along the field direction) or "pupil" (tangential along the pupil y, as in OpticStudio's FFT MTF); they differ only for fields with an x component.

System.get_param

System.get_param(spec: str) -> float

The current value of a parameter. spec is "surface.kind" (e.g. "3.t", "L1 front.c"). kind is c r k a2 to a16 t dx dy tx ty tz dn disp. Lenses and groups are "name.kind" (e.g. "lens2.tx", "G1.shift") with kind dx dy tx ty tz shift dn disp

System.ghost

System.ghost(a: _Surf, b: _Surf) -> System

Ghost: the system with the path reflected at surface a and then at surface b (b < a) unfolded into sequential surfaces (coating coefficients and polarization traces work as they are). Surfaces by number or comment. The original surface of each surface of the unfolded system is in ghost_origin

System.ghost_origin

System.ghost_origin(a: _Surf, b: _Surf) -> Any

For each surface of a ghost system (ghost(a, b)) the original surface number (None for coordinate breaks put in between), and the reflecting surfaces (a, b)

System.ghost_pairs

System.ghost_pairs(first: int = 1, last: int | None = None) -> list[tuple[int, int]]

Pairs of double reflections [(a, b), ...] (a > b, a reflects first). Surfaces first..=last (1 to the image surface if omitted; the image surface only with a coating)

System.hash

hash: str  # 属性

The hash of the system ("sha256:…", the same as the system file). Stamp it on analysis results to check later that the system is the same

System.huygens_mtf

System.huygens_mtf(field: _Field, freqs: ArrayLike, wave: int | None = None, pupil: int | None = None, image: int = 128, pixel: float | None = None, threads: int | None = None, axes: str = 'field', exact: bool = False, device: str = 'auto') -> _MtfResult

Huygens MTF: Fourier transform of the Huygens PSF (frequencies on the image surface). The returned dict has the same form as mtf, plus device as in huygens_psf. axes is "field" (default; tangential along the field direction) or "pupil" (tangential along the pupil y, as in OpticStudio's FFT MTF); they differ only for fields with an x component. exact=True uses the exact sum of huygens_psf (several times slower); device is as in huygens_psf.

System.huygens_psf

System.huygens_psf(field: _Field, wave: int | None = None, pupil: int | None = None, image: int = 128, pixel: float | None = None, threads: int | None = None, exact: bool = False, device: str = 'auto') -> _PsfResult

Huygens PSF: sums the secondary waves from each point of the reference sphere of the exit pupil on the image surface (for tilted image surfaces and strongly aberrated systems). The returned dict has the same form as psf, plus device (where the sum was computed: "cpu", or "gpu: " and the adapter name); x and y are local image surface coordinates relative to center (axes are x̂, ŷ) By default each pupil sample's phase and amplitude are approximated by a quadratic over small blocks of the image grid (the block size is chosen so that the phase differs from the exact value by at most 1e-6 rad, checked on the corner and center blocks of the grid; the intensity typically agrees with the exact sum to 1e-7 of the unaberrated peak); exact=True sums every sample exactly at every image point (several times slower). device is where the sum is computed when exact is False: "auto" (default; a GPU if one is present, otherwise the CPU), "cpu", or "gpu" (the GPU path even on a software adapter; falls back to the CPU with a warning). The GPU sums in single precision (the intensity agrees with the exact sum to about 5e-7 of the unaberrated peak).

System.hxhy

System.hxhy(i: int) -> tuple[float, float]

Normalized field (hx, hy) of field number i (from 1)

System.image

image: int  # 属性

Surface number of the image surface

System.image_sim

System.image_sim(image: Any, field_height: float | None = None, psf_grid: tuple[int, int] = ..., aberrations: str = 'diffraction', pixel: float | None = None, size: tuple[int, int] | None = None, relative_illumination: bool = True, rgb_waves: tuple[int, int, int] | None = None, wave: int | None = None, pupil: int | None = None, psf_points: int = 64, map_grid: int = 17, field: int | None = None, flip_source: str = 'none', rotate: int = 0, flip_image: str = 'none', threads: int | None = None) -> dict[str, Any]

Image simulation (as OpticStudio's Image Simulation): places image ((height, width) gray or (height, width, 3) RGB, row 0 at the top = field +y) in the object field, field_height (full height in field units; √2 × the largest field if omitted) high and centered on the axis (or on field, a field number from 1; the detector is then centered on its chief ray image), and images it onto a detector with the chief ray positions (distortion, lateral color), relative illumination and, with aberrations="diffraction" the FFT PSF (or "geometric", the ray density of a pupil grid, or "huygens", the Huygens PSF) on a psf_grid of fields (interpolated between them). Gray uses all weighted wavelengths (or wave, from 1), RGB one wavelength per channel (rgb_waves, from 1; the wavelengths 1 to 3, shortest as B, if omitted). pixel is the detector pixel [lens units] (the on-axis image of one source pixel if omitted), size (width, height) the detector pixels. flip_source ("none", "top-bottom", "left-right" or "both") and rotate (counterclockwise, 0, 90, 180 or 270 degrees, after the flip) turn the source, flip_image the detector image. Returns image (same layout; 1 is the on-axis value of an unaberrated uniform source of 1), pixel, center, field_height and warnings

System.infinite

infinite: bool  # 属性

Whether the object is at infinity

System.insert_surface

System.insert_surface(at: int, **kw: Any) -> None

Insert a surface before surface at (at is 1 to the image surface). Values as keywords (the names of surface(): type material r t and so on). The medium after the inserted surface is its material (air if omitted)

System.load

System.load(path: _StrPath, glass_dirs: Sequence[_StrPath] | None = None, cfg: int = 1, state: str | None = None, lens_catalogs: Sequence[_StrPath] | None = None, coatings: Sequence[_StrPath] | None = None, coating_file: _StrPath | None = None, wavelengths: Sequence[float] | None = None, beam_path: str | None = None) -> System

Read a system. path is a .zmx or a project file (.json).

  • glass_dirs: folders to search for glass catalogs (AGF)
  • cfg: the multi-configuration number of a .zmx (from 1)
  • state: the name of a state or a beam of a project file (System.beams(path) lists the beams)
  • beam_path: the beam splitter path of a project file (T and R in the order the BSs are passed, e.g. "TR"). The possible paths are System.beam_paths(path)
  • lens_catalogs: lens catalogs (.zmx or folders) to search for the catalog lenses of a project file
  • coatings: files of coating tables (LBCT) and models (LBCM) used in polarization traces
  • coating_file: replaces the system's coating file (COATING.DAT format)
  • wavelengths: replaces the wavelengths [µm] (.zmx only; InvalidError for a system file or project file. Weights are 1, the primary wavelength number is kept)

System.load_beams

System.load_beams(path: _StrPath, beams: Sequence[str] | None = None, all: bool = False, glass_dirs: Sequence[_StrPath] | None = None, lens_catalogs: Sequence[_StrPath] | None = None, coatings: Sequence[_StrPath] | None = None, coating_file: _StrPath | None = None) -> dict[str, System]

Read the systems of the beams of a project file (.json) at once. Returns a dict from the beam name to its System, each the same as load(path, state=name) (the beam's path, state and turn applied), in the order of beams (the order of the file if omitted). beams are names; the beams not marked off if omitted (all of them with all=True). Use it to trace the beams together, e.g. trace_many(list(d.values()), ...). glass_dirs, lens_catalogs, coatings and coating_file as in load

System.load_configs

System.load_configs(path: _StrPath, configs: Sequence[int] | None = None, glass_dirs: Sequence[_StrPath] | None = None, coatings: Sequence[_StrPath] | None = None, coating_file: _StrPath | None = None) -> list[System]

Read the systems of several configurations of a multi-configuration .zmx at once. configs is a list of configuration numbers (from 1); all if omitted (an empty list is an error). Returns a list of System, each the same as load(path, cfg=k). Use it to trace switches such as the sample and reference arms or the stop diameter (APMX, APER and so on) together with trace_many(..., object=point) on the same object point and pupil grid

System.macro_warnings

System.macro_warnings() -> list[str]

ZPL Macro Solves fixed at their saved values without solving (no macro, unsupported commands and so on), with the reasons

System.make_thermal

System.make_thermal(temps: Sequence[float], pressures: Sequence[float] | None = None) -> tuple[System, list[str]]

Thermal configurations (OpticStudio's Make Thermal): a new system whose configuration 1 is this system (its current configuration) and one configuration per temperature of temps [°C] (pressures [atm], as many, or the system pressure) with the curvatures, thicknesses, aspheric coefficients and sizes expanded by the TCE of the glasses and of the air spaces (the TCE column of the surface). Returns (system, warnings)

System.mech_check

System.mech_check(fields: Sequence[int] | None = None, waves: Sequence[int] | None = None, grid: int = 21) -> _MechCheck

Vignetting by the mechanical parts (mechanics of the project). The same as the CLI's mech-check.

Traces the rays inside the unit circle of a square pupil grid (grid rays on a side) for each field in fields and wavelength in waves (both from 1; all if omitted) and counts the fraction [%] that leaves the bores of the parts. Returns a dict: pupil_rays (rays per field and wavelength), mech_clip (whether the other analyses also vignette at the parts), pupil (px, py: the pupil points), parts (name, surface, clipped_max_pct, first_max_pct and bores of each part), results (field, wave, rays, failed, failed_pct, optical_pct, passed_pct, state and parts=[{name, clipped_pct, first_pct}] per field and wavelength; state gives per pupil point 0 passes, -1 aperture, -2 stopped, k >= 1 first cut by part k). clipped counts the rays that leave a part's bore (also those cut earlier), first the rays first cut by that part in the order the light passes, optical the rays cut by an aperture of the system before the parts. fit checks the placement: a list of dicts of kind (collision, protrude, loose, overlap, rod, rod_mismatch), error, part, other, surface, value [mm] and message.

System.mech_clip

mech_clip: bool  # 属性

Whether rays leaving the bores of the mechanical parts (mechanics of the project) are vignetted in the ray trace (default True). Set False to see the vignetting only with mech_check. No effect without mechanical parts

System.mech_clip

System.mech_clip(value: bool) -> None

System.merit_jacobian

System.merit_jacobian(vars: Sequence[str | tuple[str, float, float]], merit: str | None = ..., reference: str = 'centroid', rings: int = 3, jac: str = 'auto', threads: int | None = None, terms: Any = None) -> tuple[Any, Any]

Return the residuals r of the optimization merit and the Jacobian J ([residual][variable]) at the current variable values (for running the iterations yourself. Arguments as in optimize; terms work too). The merit is the square root of Σ r² / Σ weights. Residuals are in term order (terms of the default merit, then terms in order), each multiplied by the square root of its weight

System.mtf

System.mtf(field: _Field, freqs: ArrayLike, wave: int | None = None, n: int | None = None, threads: int | None = None, method: str = 'auto', each_wave: bool = False, axes: str = 'field') -> _MtfResult

Diffraction MTF (the same as the CLI's mtf). field is a number (from 1) or a normalized field (hx, hy), wave a wavelength number (polychromatic if omitted), n a guide for the number of quadrature points of the pupil overlap (automatic if omitted). method is "auto" (default; "interp", or "fft" when n is omitted, the quadrature has more than 1024 points and there are 8 or more frequencies), "interp" (interpolated quadrature), "fft" (autocorrelation of the pupil function by FFT, all frequencies at once; fast with many frequencies, about 1e-4 from the quadrature) or "direct" (for checking). Returned dict: freqs, tangential, sagittal (numpy), cutoff (tangential and sagittal cutoff frequencies [cycles/mm] at the calculated wavelength; the primary wavelength for polychromatic). each_wave=True also returns waves (a list of dicts per wavelength, faster than computing them separately) besides the polychromatic one (can't be used with wave). axes is "field" (default; tangential along the field direction) or "pupil" (tangential along the pupil y, as in OpticStudio's FFT MTF); they differ only for fields with an x component.

System.mtf_field

System.mtf_field(freqs: ArrayLike, h: ArrayLike, axis: str = 'y', wave: int | None = None, n: int | None = None, threads: int | None = None, axes: str = 'field') -> _FieldMtf

Field MTF: the diffraction MTF for each normalized field h (0 to 1, in the direction axis "y" or "x"). tangential and sagittal are (frequency, h) arrays, field_value the field values (system units). axes is "field" (default; tangential along the field direction) or "pupil" (tangential along the pupil y, as in OpticStudio's FFT MTF); they differ only for fields with an x component.

System.mtf_focus

System.mtf_focus(field: _Field, freqs: ArrayLike, dz: ArrayLike, wave: int | None = None, n: int | None = None, threads: int | None = None, axes: str = 'field') -> _ThroughFocusMtf

Through-focus MTF: the diffraction MTF with the image surface shifted by dz [lens units] (changes the thickness before the image surface; thickness solves are not solved again). tangential and sagittal are (frequency, dz) arrays. Points that can't be calculated are NaN, with the reasons in warnings. axes is "field" (default; tangential along the field direction) or "pupil" (tangential along the pupil y, as in OpticStudio's FFT MTF); they differ only for fields with an x component.

System.name

name: str  # 属性

System.object_of

System.object_of(field: _Field) -> list[float]

The object of a field (number or (hx, hy)): an object point (x, y) [mm] for a finite object, a direction (l, m, n) at infinity

System.optimize

System.optimize(vars: Sequence[str | tuple[str, float, float]], merit: str | None = ..., reference: str = 'centroid', rings: int = 3, iters: int = 50, jac: str = 'auto', threads: int | None = None, terms: Any = None, qr: bool = False, gtol: float = 0.0, active_set: bool = False, stopped_as_vignetted: bool = False, starts: int = 0, seed: int = 1, keep: int = 5, spread: float = 0.5, glass: Any = None) -> _OptimizeResult

Return the system optimized by damped least squares (DLS) (the original system is not changed). vars is a list of variables, each "7.t" or ("7.t", lower, upper) (None for no bound on that side). The default merit function merit is "spot" (RMS spot) or "wavefront" (RMS wavefront), over all fields (field weights) and wavelengths. None for only the terms. jac is "auto" (analytic for terms with 16 or more analytic columns, central differences for the others), "fd" (all central differences) or "forward" (all forward differences, half the traces of central differences). qr solves each step by QR instead of the normal equations, gtol stops when the largest cosine between the residuals and a variable's column is below it (0: no test), active_set fixes variables a step would take out of range at the bound. stopped_as_vignetted drops stopped rays (total internal reflection, missing a surface) like vignetted rays instead of failing the evaluation.

starts of 2 or more runs a global search: the optimization is repeated from starts start points (the current values first; variables with both bounds drawn uniformly in their range, others within ±spread × max(|value|, typical size) of the value, by the random seed) in parallel, and the best keep distinct solutions are kept. glass is a dict {"surfaces": [1, 3], "catalogs": ["SCHOTT"], "candidates": 8, "passes": 2} for glass substitution after the optimization: the glass of each surface is chosen among the candidates nearest in nd and vd to its current medium, re-optimizing the variables for each (model glasses and surfaces with dn/disp are always replaced by a real glass, real glasses only when the merit improves; catalogs default to the glasses loaded for the system). The candidates can be narrowed like OpticStudio's glass substitution template: max_cost (relative cost), max_cr, max_fr, max_sr, max_ar, max_pr (resistance classes), status (a list of "standard", "preferred", "obsolete", "special", "melt") and exclude (glass names, "NAME@CATALOG" for one catalog); glasses without the value are kept, glasses marked "exclude substitution" in the catalog are never used, and a current glass that fails the filter is always replaced. nd_step (0.01), vd_step (1) and dpgf_step (None) weigh the closeness (Δnd/nd_step)² + (Δvd/vd_step)² (+ (ΔPgF/dpgf_step)²). Where the surface's material differs between configurations, each group of configurations with the same material is substituted separately.

terms is a list of dicts of terms to add, of the form {"type": "ray", "field": 1, "py": 1, "q": "y", "target": 0, "weight": 1}; the types are spot, wavefront, mtf, paraxial (q: efl, pmag, enpp, epd, expp, expd, wfno, pwfn, isfn, pimh, totr, obsn, isna), ray (q: x, y, z, l, m, n in local coordinates of surface surf), centroid (centroid of the beam on the image surface, q: x, y), opd, zernike, coupling, zplm (OPTRETURN of a ZPL macro) and plugin (output of a registered plugin; the same as the CLI's --term). {"type": "user", "fn": f, "jac": g, "name": ..., "weight": ...} is a term defined by Python functions: f(systems) takes a list of System and returns the residuals per system as a (len(systems), number of residuals) array (the systems for differences are passed together in one call). With g(system, names), the partial derivatives of the residuals (number of residuals, len(names)) are computed with it.

Returned dict: system (optimized system), x0, x (variable values), merit0, merit, history (merit per iteration), iterations, evals, stop ("converged", "small_step", "small_gradient", "no_progress", "max_iter", "jacobian_failed"), note (details of why it stopped), inactive (numbers of variables considered ineffective and not moved), term_values0, term_values (values per term of terms), term_value_kinds ("quantity": the value itself for terms with a target, "rms": √Σr² for the others), global_search (with starts ≥ 2: ran, failed, skipped (starts not begun because it was stopped), best_start, solutions with start, merit and x, best first), glass (with glass: changes with surface, from, to, target_nd, target_vd, nd, vd, merit and configs (positions in the given configurations, from 1, only when not all); materials as (surface, name) of the first configuration; config_materials as (surface, names per configuration) where they differ; reset as (parameter, value) of the fixed dn/disp set to 0; tried; merit_before)

System.pickups

System.pickups() -> list[_Pickup]

Pickups: dicts of dst, src, what (c t k p1… before0–4 after0–4 and so on), scale and offset, with src_what when the source quantity differs from what

System.primary

primary: int  # 属性

Primary wavelength number (from 1)

System.psf

System.psf(field: _Field, wave: int | None = None, pupil: int | None = None, image: int = 128, pixel: float | None = None, plane: str = 'image', threads: int | None = None) -> _PsfResult

Diffraction PSF: DFT of the pupil function (the same as MTF). The intensity i is a (y, x) array, normalized so that the center of the polychromatic PSF of the same pupil without aberrations is 1 (peak is a guide to the Strehl ratio). x and y are coordinates from the image point center of the chief ray at the primary wavelength [lens units] on the plane given by plane: "image" (default) the image surface (local x, y; the same frequencies as mtf), "chief" the plane perpendicular to the chief ray (as OpticStudio's FFT PSF; finer by 1/cos in oblique fields). axes are the grid directions (unit vectors in image space). pupil is the side of the pupil grid (automatic if omitted: phase difference between neighboring samples at most π/2), image the side of the image grid, pixel the spacing of the image grid (1 / (2 × cutoff frequency) on that plane if omitted). Also returns plane, pupil (the value used), phase_step (largest phase difference between neighboring pupil samples [rad]), enclosed (fraction of the light inside the image grid) and warnings (notes such as undersampling)

System.pupil_reversed

pupil_reversed: bool  # 属性

Whether the entrance pupil of a finite object is before the object (systems where pupil="normalized" is reversed from "signed")

System.remove_config_row

System.remove_config_row(spec: str) -> None

Remove a row of the table (the system's value stays as it is)

System.remove_pickup

System.remove_pickup(dst: _Surf, what: str) -> None

Remove the pickup of what on surface dst (the value stays as it is)

System.remove_solve

System.remove_solve(surf: _Surf, what: str = 't') -> None

Remove the solve of what ("t" thickness / "c" curvature) on surface surf (the value stays as it is)

System.rms

System.rms(field: _Field | None = None, vs: str | None = None, x: ArrayLike | None = None, wave: int | None = None, axis: str = 'y', reference: str = 'centroid', rings: int = 6, threads: int | None = None, field_wave: bool = False) -> _Rms | _RmsSweep

RMS: spot radius (spot, spot_x, spot_y [lens units]), wavefront error wfe [waves], and the Strehl ratio approximation strehl = exp(−(2π wfe)²). The abscissa vs is "field" (x is the normalized field along axis), "focus" (x is the image surface shift), "wavelength" (x is the wavelength [µm], monochromatic) or None (one point at field). reference is "centroid" or "chief", rings the number of rings of the Gaussian quadrature of the pupil. field is used when vs is focus, wavelength or None. With field_wave=True, the fields of real image height (and fields given by conditions) of monochromatic field and wavelength sweeps are solved with the chief ray at the analysis wavelength (as in OpticStudio)

System.save

System.save(path: _StrPath) -> None

Save to a system file (lensbench's own JSON, format version 2). What you wrote is saved: surfaces, glass names, parameter changes, pickups, solves, lenses and groups, the multi-configuration table, dn and disp; reading it back with System.load traces bit for bit the same. Glasses are written by name with the name and hash of their catalogs (the catalogs are searched again when reading). The paths of the coating tables and models (coatings=) are written too A warning is given for a catalog with no file whose values match the system's glasses (its hash is left empty and can't be checked on reading)

System.set_config

System.set_config(k: int) -> None

Switch the current system to configuration k

System.set_config_count

System.set_config_count(n: int) -> None

Set the number of configurations to n (added configurations take the current values; 1 removes the table)

System.set_config_names

System.set_config_names(spec: str, names: Sequence[str]) -> None

Add a material or coating row to the table (replaces the same parameter): spec is N.material or N.coating, names the name per configuration (an empty coating name is no coating)

System.set_config_row

System.set_config_row(spec: str, values: Sequence[float]) -> None

Add a row to the table (replaces the same parameter): spec is the same name as in set_param, values the values per configuration

System.set_field_type

System.set_field_type(kind: str, cond: Any = None, fields: Sequence[tuple[float, float]] | None = None) -> None

Change the field type and values. kind is the same name as field_type. For "solve" give the condition in cond (("position", surface), ("dirsum", surface1, surface2), ("dirdiff", surface1, surface2); surfaces by number or name); the object whose chief ray at the primary wavelength makes the field (x, y) the target of the condition is solved (again when parameters change). fields also replaces the field (x, y) values (weights and vignetting factors go back to the defaults)

System.set_material

System.set_material(s: _Surf, material: str) -> None

The material of surface s: a glass name (the system's catalogs; add more with add_glass_catalogs), "nd,vd[,dpgf]", "" or "AIR", "MIRROR"

System.set_param

System.set_param(spec: str, value: float) -> None

Change a parameter (without rebuilding the system). Pickup targets are solved again from their source surfaces (a pickup target itself can't be changed)

System.set_params

System.set_params(changes: Mapping[str, float] | Sequence[tuple[str, float]]) -> None

Change several at once: {"3.t": 10.0, "5.dx": 0.01} or [("3.t", 10.0), ...]

System.set_stop

System.set_stop(s: _Surf) -> None

Make surface s the stop

System.set_surface

System.set_surface(s: _Surf, **kw: Any) -> None

Change values of surface s with keywords (the names of surface(), except mirror, stop and n; material for the material)

System.set_surface_type

System.set_surface_type(s: _Surf, kind: str) -> None

The type of surface s (STANDARD EVENASPH COORDBRK JONESMAT PARAXIAL TOROIDAL FRESNELS). Values the new type doesn't have go back to 0

System.set_unit_pivot

System.set_unit_pivot(name: str, pivot: tuple[float, float, float]) -> None

Change the center of rotation of a lens or group

System.solve_ray

System.solve_ray(unknown: str, residual: Any, object: _ObjectPoint | None = None, field: _Field | None = None, pupil: tuple[float, float] = ..., wave: int | None = None, tol: float = 1e-12, max_iter: int = 50) -> _SolveRay

Solve a real ray with two unknowns and two residuals by Newton's method.

  • unknown: "object" (x and y of the object point [mm], finite object) or "pupil" (pupil coordinates px and py)
  • residual: one of ("position", surface, (x, y)) (local position on the surface − target), ("dirsum", surface1, surface2) (sum of the direction cosines l and m) and ("dirdiff", surface1, surface2) (difference)
  • object: the object (an object point (x, y) or a direction (l, m, n)). The initial value when the unknown is the object point. The object of field if omitted
  • field: the field when object is omitted (number or (hx, hy); on axis if omitted)
  • pupil: pupil coordinates. The initial value when the unknown is the pupil coordinates
  • wave: wavelength number (primary wavelength if omitted)

Returned dict: object, pupil, residual, iterations (can be passed as they are to trace(None, [px], [py], object=...))

System.solves

System.solves() -> list[_Solve]

Solves: dicts of surf, what ("t" thickness / "c" curvature), kind (name of the kind), value, param and other

System.stop

stop: int  # 属性

Surface number of the stop

System.surface

System.surface(s: _Surf) -> _Surface

A dict of the values of surface s (type comment t c r k asph cx material mirror coating semi stop ignore aperture cb cb_order cb_return focal jones dn disp n). r is the radius of curvature (inf for a plane), aperture a dict or None

System.surface_count

surface_count: int  # 属性

Number of surfaces (including the object and image surfaces)

System.system_data

System.system_data() -> _SystemData

System data (lowercase OpticStudio operand names: effl, epdi, enpp, expd, expp, wfno, pwfn, isfn, pimh, pmag, totr, obsn, isna). At the primary wavelength, values of the system after changes

System.to_json

System.to_json() -> str

The content of the system file (a JSON string). Warns like save

System.tolerance

System.tolerance(spec: Any = None, terms: Any = None, vendors: Any = None, configs: Sequence[System] | None = None, threads: int | None = None, reversed: Sequence[str] | None = None) -> Any

Monte Carlo tolerance simulation. spec is a dict of the same settings as the CLI's lensbench tolerance --spec (trials, seed, dist, preset, catalog, catalog_tols, lenses, groups, tols, compensators, comp_iters, merit, rings, ref, terms, sensitivity, percentiles, samples). None for the default (the general tolerance set on all lenses, RMS wavefront, 100 trials). terms is a list as in optimize, added after the terms of spec (Python function terms {"type": "user", ...} also work, for using measured values and the like as the criterion). vendors maps block ids to vendors (used for the default tolerances of catalog lenses). configs are additional configurations (this system is configuration 1; perturbations are the same in all configurations). reversed is the list of ids of blocks of lenses placed reversed (used to decide front and back of wedge_face in spec by the lens's original orientation; systems made with from_project carry the reversed mark, so it isn't needed).

Returned dict: nominal (merit, terms, comp), merit (statistics: n, mean, std, min, max, percentiles), cdf (merit in ascending order), terms (label, nominal, stats, cdf per term), compensators (name, nominal, stats, values per trial), tilt_magnitudes (magnitude of the tx, ty pair of compensators [arcmin]), merit_values (merit per trial), sensitivity (change of the merit at lo and hi of each tolerance, worst first; with inverse, lo and hi are the tightened limits), rss_estimate (nominal + root-sum-square of the mean of the squared lo and hi changes), comp_mode, inverse (mode, value, limit, tolerances with lo0, hi0, lo, hi and the tightened sides, tightened), correlation (correlation r with the perturbation and r_abs with |perturbation|), tolerances, trials, failed, errors (with samples true, also deltas and eval per trial)

System.trace

System.trace(field: _Field | None, px: ArrayLike, py: ArrayLike, waves: Sequence[int] | None = None, last: int | None = None, record: bool | Sequence[int] = ..., pol: bool | int | None = None, pol_phase: bool = False, globals: bool = False, object: _ObjectPoint | None = None, grad: Sequence[str] | None = None, threads: int | None = None, pupil: str = 'normalized', dz: float | ArrayLike | None = None, land: bool = False, pol_grid: Any = None) -> _TraceResult

Trace rays and return a dict of numpy arrays.

  • field: a field number (from 1) or a normalized field (hx, hy). None when object is given
  • px, py: normalized pupil coordinates (1-D, same length; lists and float32 also work)
  • waves: a list of wavelength numbers (from 1). All wavelengths if omitted
  • last: stop at this surface (the image surface if omitted)
  • record: True also returns the intersections at all surfaces on the way (rec_*, shape (wavelength, surface, ray)). A list of surface numbers gives only those surfaces (except ignored surfaces and those after last; faster for systems with many surfaces)
  • pol: the wavelength number for a polarization trace (True for the primary wavelength). Returns complex128 (ray, 2, 2) in jones. Columns are the input polarization (unit vectors of local x and y on the object side), rows the x and y components of the exit field in local coordinates of the last surface. The z components are jones_z ((ray, 2)). With coating amplitudes and phases; the phase convention is E ∝ exp(−ikL). NaN for stopped rays
  • pol_phase: True multiplies jones by the propagation phase exp(−ik·OPL) (not by default; the optical path length is opl)
  • pol_grid: does the polarization trace on a coarse grid of normalized pupil coordinates [−1, 1]² (n points or (nx, ny), at least 4 per axis, e.g. 25) and interpolates the Jones matrices without the propagation phase to all rays with a 2-D cubic spline (not-a-knot) (faster than a polarization trace of all rays). Stopped or vignetted grid points are filled from the nearest valid point of the grid. Grid points missing inside the pupil (px² + py² ≤ 1) are returned in pol_grid_missing ((point, 2) of px, py); rays in cells within 2 points of them get NaN jones and True in pol_grid_bad ((ray,) bool). Only when pupil is "normalized" or "signed"
  • globals: True also returns the global positions and directions gx, gy, gz, gl, gm, gn and the start points and directions p0, k0 ((wavelength, ray, 3))
  • object: the object directly instead of a field: an object point (x, y) [mm] for a finite object, a direction (l, m, n) for an infinite object. No vignetting factors are applied
  • grad: a list of parameters ("3.t", "objx" and so on) to differentiate the optical path length by. Returns dOPL/dp in grad ((wavelength, ray, parameter)). The derivative with the start point and the intersection with the last surface (local x, y) fixed. objx and objy for finite objects only
  • land: with grad, True also returns in grad_land ((wavelength, ray, parameter, 4)) the derivative of the landing point and direction at the last surface d(x, y, l, m)/dp. The derivative with the start position and direction fixed (the same ray is launched and only the system changes; not solved again even with pupil="stop" or aimed rays)
  • dz: puts the detector on the plane z = dz in local coordinates of the last surface (a plane following the tilts and decenters of the surface). x, y, z, opl, opl_os and the global positions become the values on that plane, grad the derivative with x and y on that plane fixed, and grad_land is on that plane too. record is not changed. Can't be used with pol_phase=True
  • threads: number of threads (1 for sequential; all cores if omitted). The results are bit for bit the same for any number of threads
  • pupil: with "normalized" (default) px and py are normalized pupil coordinates (as in OpticStudio; in finite-object systems with the entrance pupil before the object, px = 1 passes the −x side of the stop, and the direction flips across telecentricity). "signed" is the pupil coordinate with the sign flipped for those systems (px = 1 always on the same side of the stop; opposite in sign to normalized for systems where System.pupil_reversed is True). With "stop" they are local coordinates [mm] on the stop surface, and the real ray through that point is solved for each ray (independent of the system's aiming and entrance pupil position; no vignetting factors; rays that can't be solved have err at the stop surface)

Returned arrays (shape (wavelength, ray)): x, y, z, l, m, n (position and direction cosines in local coordinates of the last surface), opl (optical path length), opl_os (OpticStudio's raw optical path length), lens_opd (phase of ideal lenses), err and vig (number of the surface where the ray stopped or was vignetted, 0 if it passed), ok (err and vig both 0). Also waves (numbers), last, hx and hy for a field, object for an object. With record, rec_surfaces and rec_x … rec_opl (rec_gx, rec_gy, rec_gz are global)

System.trace_rays

System.trace_rays(start: ArrayLike, direction: ArrayLike, waves: Sequence[int] | None = None, last: int | None = None, record: bool | Sequence[int] = ..., pol: bool | int | None = None, pol_phase: bool = False, globals: bool = False, frame: str = 'object', grad: Sequence[str] | None = None, threads: int | None = None, dz: float | ArrayLike | None = None, land: bool = False) -> _TraceResult

Trace from start positions and directions given directly. The returned dict is the same as [trace] (without hx, hy and object).

  • start, direction: (ray, 3) arrays. Directions are normalized (a zero vector is a stopped ray). The optical path length is from the start position
  • frame: "object" (default; local coordinates of the object surface for a finite object, the coordinates before the transform of surface 1 for an infinite object) or "global"
  • the other arguments are as in trace. objx and objy of grad are derivatives with the start positions moving with the object surface

System.units

System.units() -> list[_Unit]

Lenses and groups: dicts of name, spans (list of surface ranges [first, last]), pivot, motion (dx dy tx ty tz), shift and auto

System.wavelengths

wavelengths: list[float]  # 属性

Wavelengths [µm]

System.weights

weights: list[float]  # 属性

System.with_params

System.with_params(changes: Mapping[str, float] | Sequence[tuple[str, float]]) -> System

Return a new changed system (the original system is not changed; a light copy)

UnsupportedError

Uses an unsupported feature