=== OUT OF DATE !!! === 

Please check for newer version of BpmLab at 
https://intranet.cells.es/Divisions/Accelerators/RF_Diagnostics/Diagnostics/OrbitPosition/Tools/bpmlab

========================== BPM Geometry Selectors ===================

A combination of vacuum chamber cross-sections and electrode shapes for BPM construction. Based on the selections, a BPM is created following a pre-defined scenario whose geometrical parameters can be further modified in the Parameter Tree on the left. To view the updated BPM geometry press OUTLINE. 


========================== BPM Presets ==============================

Several real-life BPMs are directly available as editable Presets. A user can create and add his own preset by editing the presets.m file (or by contacting the author).


========================== Parameter Tree ===========================

All editable geometry-related parameters are listed in the Tree, together with some mesh and mapping settings. Its is recommended to press ENTER to confirm any changes. To edit matrices or vectors press F2 for a more user-friendly input. 

Electrode input sequence (important!): Right-Top-Left-Bottom or RightTop-LeftTop-LeftBottom-RightBottom.. 


========================== OUTLINE & MESH ===========================

Here the user can visualize the cross section of a BPM based on the Parameter Tree settings. By pressing Scatter, the closed geometry outlines are spread with a number of points based on the MIN/MAX mesh edge lengths and Refinement setting. By pressing Generate Mesh these points are optimized to become the nodes of triangular mesh with equidistant Delaunay triangulation properties. 

- Left axes:            show an outline of the BPM geometry and the initial non-optimized distribution of nodes.
- Right axes:           show the mesh optimization in real-time and the final mesh.
- Right-bottom axes:    show precision of node locations near all boundaries. Color-codes match the electrodes colors, while the black stands for the vacuum chamber. Useful for checking if some node is far off boundary (happens rarely). 
- Load mesh if exists:  a quick way to load the pre-generated mesh and save some time (only for supplied presets!). For new presets, the mesh vars must be saved manually for this to work. Check it off to enable the buttons below. 
- Outline:              draws/updates the BPM cross-section geometry.
- Scatter:              distributes/re-distributes nodes for mesh generation. Useful for tuning the initial min/max mesh sizes. 
- Generate mesh:        Starts the mesh generation, which stops either if converged, or if the Mesher Timeout is reached. 
- Stop:                 Stops the mesh generation and displays its current state.


============================== FIELDS ===============================

Here the finite-element solver calculates the electrostatic potential excitation of each electrode with 1 V while grounding the others (including the vacuum chamber) by solving the Poisson's equation with Dirichlet boundary conditions. In case of BPM rotational/mirrored 4-fold symmetries the amount of simulations can be reduced from 4 to 1. The 4x potential solutions are then combined via the Green's reciprocity theorem to obtain the electrode response to any excitation location (i.e. beam position) inside the vacuum chamber. 

How to use symmetry: 
Rotational symmetry - for circular BPMs with 4-fold symmetry and electrodes centered at 0/90/180/270 degrees. 
Mirrored symmetry - for skewed, elliptic, synchrotron BPMs with 2-fold symmetry. 
None - no symmetry (4 electrostatic simulations). Uses one of the two above-mentioned electrode input sequences for difference-over-sum calculations.  

- Left axes:            show the simulated electrostatic excitations of each electrode. It is useful to check if the the electrode sequence matches the axes titles (important for difference-over-sum conventions). 
- Right axes:           shows the electrostatic solution to Poisson's equation on the generated mesh, either for a single electrode or for manual boundary excitation(s).
- Symmetry:             saves some seconds if a BPM has exploitable symmetries.  Auto-detected for presets. 
- Single simulation:    simulates a single electrostatic field distribution based on boundary potentials and volume force values (no real application for this functionality yet). 
- Volume force:         a value used to assemble the right-hand side of the Poisson's equation (default is 0).
- Boundary potentials:  potential assignment for each boundary in Volts: [elec1, elec2,.. body]. 


================================ MAP ================================

The BPM response map is calculated based on the map settings in the Properties Tree and the chosen difference-over-sum (DOS) treatment (the recommended one is highlighted). 
The user selects the region of interest (ROI) where the linear scaling factors for H and V planes need to be calculated (usually within a few mm from the origin). 
The simulated BPM response map (uncalibrated DOS values) are stored in the Matlab workspace under the SIMSET.dosGridX and SIMSET.dosGridY variables. 

- Left axes:            shows the maps of original positions and the corresponding BPM response, scaled with calculated linear kx, ky factors. 
- Right axes:           shows the error map of the BPM response with respect to original positions. The error map is color-coded in mm so that every position which has an error above 100 um (default, changeable) is red. 
- Region of interest: 	specify the limits where the linear scaling factors need to be extracted. 
- Slope Drop:           shows the change in the characteristic slope for X and Y axes (in %) with respect to the characteristic slope at the nearest-to-zero position. Useful for understanding how far the selected ROI is from the linear region around the BPM origin. 
- kx,ky factors:        calculated scaling factors based on the ROI. 
- DOS treatments:       select the appropriate DOS convention. The recommended one is highlighted.
Orthogonal/4: x=(r-l)/(r+l), y=(t-b)/(t+b) for BPMs with rotational symmetry. 
Orthogonal/2: x=(tr+br-tl-bl)/(tr+br+tl+bl), y=(tr+tl-br-bl)/(tr+br+tl+bl) for BPMs with mirrored symmetry. 
Diagonal:     x=1/2*((tr-bl)/(tr+bl)-(tl-br)/(tl+br)), y=1/2*((tr-bl)/(tr+bl)+(tl-br)/(tl+br)) also  for BPMs with mirrored symmetry. 
- kx,ky override:    	for manual scaling factors input. The response map and the error map will refresh accordingly after pressing the Refresh button. 
- Refresh map:          recalculate the map based on manual scaling factors. 

================================ LINEARITY ==========================

Here a user can analyze the characteristic curves for all horizontal and vertical sweeps. The user-specified ROI from the Map tab is shaded in grey. 

- Left axes:            shows a super-position of characteristic plots for horizontal map lines. 
- Right axes:           shows a super-position of characteristic plots for vertical map lines. 


================================ POLYNOMIAL CORRECTION ==============

To suppress the nonlinear distortion of a BPM response map, the user can craft a pair of polynomials, intended for fast on-line application by a BPM front-end: single-term polys, which only take care of axial corrections, or cross-term polys, which take into account the coupling between the electrodes. The 2D cross-terms are generally much more accurate but require a few more coefficients, hence more computations. 
The coefficients are stored in Matlab's workspace under the POLYFITS.hor_poly and POLYFITS.ver_poly variables. 

- Left axes:            shows the corrected map, based on polynomial settings. BLUE dots correspond to the fitted region of interest, while the RED dots are excluded from the fit area but were affected in some way by the polynomials. 
- Right axes:           shows the error map of the polynomial-corrected BPM response with respect to original positions. The error map is color-coded in mm so that every position which has an error above 100 um (changeable) is red. 
- Region of Interest:   select the area where the polynomial needs to be effective.
- Max power:            max power of the polynomials (same for x and y).
- Polynomial type:      select between the 1D single-term or the 2D cross-term polynomial types. 
- Compare polys:        in order to balance between the minimal polynomial power and its correction accuracy, it is useful see the comparison of axial and diagonal error of a range of polynomials of different powers. In the opened figure, the left-bottom half-plane (white-shaded) of top-plots shows a regoin limited by the 50 um generic accuracy limit, and the ROI limit on the right for both H and V axial points. The minimal efficient poly power is the one that is more linear in this area and exits through its right side. 


================================ VOLTAGE INVERSION ==================

Here a direct inversion of the electrode voltages back to corresponding beam positions can be done by providing a data file with recorded BPM signals. It uses a model behavior of a constructed BPM through iterative numerical optimization to estimate the beam position from where those signals were induced. This procedure is slower than polynomial position reconstruction and is intended for offline post-processing, offering much more precision with respect to polynomial correction. For testing and playing around there is a DEMO MODE: in reality it is a Backwards Convergence Test of the FEM model of a BPM using self-generated signals, inverting them back to positions inducing them. This type of correction usually shows excellent beam position recovery with machine precision and works very fast in background mode. The results of inversion for X and Y beam coordinates are stored in Matlab's workspace in the OPTRES.x_inverted and OPTRES.y_inverted variables. 

- Left axes:            in Import Voltages mode shows the on-going inversion process (scaled DOS values (red) and optimized values (blue)); in Demo Mode shows the known beam positions, the scaled DOS positions, and the optimized positions.
- Right axes:           shows the 4x electrode signals as functions of time (natural sequence) color-coded as the electrodes.  
- Import BPM voltages:  this area is for importing BPM data.
- Source:               select a file for inversion: *.MAT,*.CSV,*.TXT containing a 4-column vector corresponding to 4x voltages/bins recorded from electrodes/ADC. The sequence of columns must correspond to the above-mentioned electrode input sequence. The MAT file can contain a structure variable called "data" with 4-column matrix, each column corresponding to electode signal sequence; it can also contain 4 matrices called A, B, C and D, corresponding to electrode button sequence, even in mukti-turn mode. They will be converted to 1D vectors. 
- Remove offset:        remove static offset from inverted data. 
- Demo mode:            For self testing the inversion and playing with the model. 
- Uniform Grid:         For generating a uniform rectangular "beam position" grid using the FEM model and inverting the electrode potentials back to the "actual beam positions". 
- Scattered grid:       For generating a non-uniform scattered "beam position" grid using the FEM model and inverting the electrode potentials back to the "actual beam positions". 
- Search mode:          select the type of initial guess search for faster inversion. Both usually produce identical results; however, the Nearest DOS Value sometimes works faster for BPMs with mirrored symmetry. 
- Run in background:    when ON, disables the Right Axes refresh until finished. To speed up the inversion for large data sets (up to 70% faster!). 
- Invert:               Start the voltages inversion back to beam positions. 
- Stop:                 Stop the inversion. 


================================ CORRECTION COMPARISON ==============

For demonstrative purposes to compare the accuracy of both types of correction: by polynomials and by the voltages inversion. 
	
- Left axes:            shows the error map of the polynomial-corrected BPM response with respect to original positions. 
- Right axes:           shows the error map of inverted signals (in Demo Mode).


================================ CHANGELOG ==========================

1.07    2017.04.28    Added "ELI-NP dump" geometry
1.08 	2018.03.06    curve fitting toolbox-free (Removed PrepareSurfceData()); allow load ABCD data file (ESRF  type) for inversion
1.09 	2018.03.16    Added Inversion compatibility with Matlab 2017a
1.10 	2018.03.16    Started changing graphic syntax to better support newer matlabs (>= 2016). Will focus on this version from now on, stopping support of older matlabs. 
1.11 	2018.04.07    optimization toolbox-free (minFunc to substitute fminunc()); coherence, sum-signal, noise gen; altered ESRF bpm
1.12 	2018.xx.yy    shoebox geom, better symmetry exploit for maps, adequate abcd-treatment selector, 
