Saw Tooth Geometric Correction Procedure

Note: The package DerivedData should be available (see the section "Loading of the required packages"):

The procedure performs the saw tooth reduction by simple geometric correction of the two curves. For all measurements it registers the correction result in the table MAS_PDA.AUX_CRYOGEO_SAW_TOOTH.  For the steps other than ITP20-GEO it compares the shape with the shape on this step.
The procedure can be run on a set of measurements. The query for the measurements is to be specified in the section "Get the list of magnets" (change the black text inside the qoutes). The query should return the magnet number, step, blockage status and the measurement ID. The procedure is designed to be used for the steps from WP08, but can be run also for any other steps. When writing the query:

	* Be careful to select only valid measurements (FINAL_MEAS = 'T'). The procedure is not designed to treat invalid measurements.
	* Also, do not remove the conditions on the number of points. With less points at each run the saw tooth analysis has no sense.
	* Be careful with the large number of measurements and createReport or exportPlots options, Mathematica can crash with the growing volume of graphics. 
	
Sections "Get the list of magnets" and "Results" contain non initialization cells and should be run manually.
If you need to show and export the plots of the original and corrected data and the new mid-plane, change the value of the exportPlots to 1 in the section "Magnet analysis".
If you need to prepare the report on the measurement , change the value of the createReport to 1 in the section "Magnet analysis".

The message Transpose::"nmtx": "The first two levels of the one-dimensional list cannot be transposed." appears if for the magnet the ITP20-GEO axis measurement does not have "connection" or "lyre" measurements (it has "combined" instead). 
The message FindMinimum::"reged": "The point (-1000.) is at the edge of the search region {-1000., 16000.} in coordinate 1 and the computed search direction points outside the region". appears a few times when calculating the scale for the difference plots and can be ignored.
Please, report any other error messages to Natalia Emelianenko.

To be able to retrieve the data from the database, specify the correct MAS_ALL password here:

MyPassword =  "trinite";

\(\(SetDirectory["C:\geom reports special\tube_measurements\dipoles\correction_procedure\MEB_reports"];\)\)

Loading of the required packages

<< Statistics`LinearRegression`

<< Graphics`Graphics`

<< Graphics`Colors`

<< Graphics`MultipleListPlot`

<< Statistics`MultiDescriptiveStatistics`

<< LinearAlgebra`MatrixManipulation`

<< Graphics`ImplicitPlot`

<< DatabaseLink`

<< DerivedData.m

Definitions (auxiliary functions, nominal values, known errors)

getRows[list_List, text_, column_] := 
        list[[First[Transpose[Position[list[[All, column]], text]]], 
            All]];

textSize = 12; angleY  =  0;  angleZ  = 0; 
    magnetsList = {};

\(\(allmonths\  = \ {"January", \ "February", \ "March", \ "April", \ "May", \ "June", "July", \ "August", \ "September", \ "October", \ "November", "December"};\)\)

BlockDiagonalMatrix[mat : {_?MatrixQ .. }] := 
        Module[{colLengths, offsets, padfunc}, 
          colLengths = Last /@ Dimensions /@ mat; 
          offsets = Most[FoldList[Plus, 0, colLengths]]; 
          padfunc[x_, 
              y_] := PadRight[#, Tr[colLengths], 0, 
                  offsets[[y[[1]]]]] & /@ x; 
          Flatten[MapIndexed[padfunc, mat], 1]];

    
ProductMatrix[a_List, 
        b_List] := 
Transpose[
          AppendColumns[
            Table[a, {Length[b]}]]]×
AppendColumns[
          Table[b, {Length[a]}]]

Distance between curves (presented as two lists), should be used with norm=1 (average absolute distance) or norm = ∞ (max absolute distance)

fitDiff[One_List,  Two_List] :=
Module[{lowerBound,  upperBound,  diff,  pointSet,  a,  
              rms},
diff[
                  x_]  :=  {x, Interpolation[One, 
                        InterpolationOrder -> 1][
                      x] - Interpolation[Two, 
                        InterpolationOrder -> 1][x]};
lowerBound  =  
                Max[{Min[One[[All, 1]]], Min[Two[[All, 1]]]}];
upperBound  =  
                Min[{Max[One[[All, 1]]], Max[Two[[All, 1]]]}];
pointSet = 
                Select[Select[
                    Union[One[[All, 1]], 
                      Two[[All, 1]]], # ≥ 
                        lowerBound &], # ≤ upperBound &];
points = Map[diff, pointSet];
fitLinear=Regress[points,Table[x^a, {a, 0, 1}],x,RegressionReport->{BestFit,BestFitParameters,FitResiduals}];
a = FitResiduals /. fitLinear ;
rms  = 
                Sqrt[Total[a^2]/(Length[a] - 1)];
{(BestFitParameters /. fitLinear)[[1]], (BestFitParameters /. fitLinear)[[2]],rms}];

Distance[One_List,  Two_List,  
          norm_]  := 
Module[{lowerBound,  upperBound,  
            diff,  pointSet}, 
diff[
              x_]  :=  Interpolation[One, InterpolationOrder -> 1][
                x] - Interpolation[Two, InterpolationOrder -> 1][
                x]; 
lowerBound  =  
            Max[{Min[One[[All, 1]]], 
                Min[Two[[All, 1]]]}]; 
upperBound  =  
            Min[{Max[One[[All, 1]]], 
                Max[Two[[All, 1]]]}]; 
pointSet = 
            Select[Select[
                Union[One[[All, 1]], 
                  Two[[All, 1]]], # ≥ 
                    lowerBound &], # ≤ 
                  upperBound &]; 
Norm[Map[diff, pointSet], 
              norm]/If[norm >  1, 1, Length[pointSet]]];

Nominal shape of the dipole in the horizontal plane

shapeInner  =  
        97.26225185277093` - 0.0025902538340244544` x + 
          4.3657921007967315`*^-8 (x^2) + 8.508665458319123`*^-11 (x^3) - 
          3.088176843754341`*^-14 (x^4) + 6.873966585339741`*^-18 (x^5) - 
          9.684813179035071`*^-22 (x^6) + 8.656259521837845`*^-26 (x^7) - 
          4.7534259232247706`*^-30 (x^8) + 1.461975014084606`*^-34 (x^9) - 
          1.9271804789245223`*^-39 (x^10);
shapeOuter  =  -97.25706662452652` - 
          0.0025900689224389504` x + 3.9189436336648223`*^-8 (x^2) + 
          8.93087016422862`*^-11 (x^3) - 3.2678815981823696`*^-14 (x^4) + 
          7.318992962299414`*^-18 (x^5) - 1.0378141472544362`*^-21 (x^6) + 
          9.3421351109016`*^-26 (x^7) - 5.169247894681955`*^-30 (x^8) + 
          1.602236800172889`*^-34 (x^9) - 
          2.128100113155082`*^-39 (x^10);

Y-coordinates of the laser trackers in millimeters

trackerConn  =  -1000. ; trackerLyre  =  16000. ;

Errors (laser error is 5ppm, mole error), step from flange for the curve fit

errorLaser = 5.0 (10^(-6)); errorMole = 0.07;  
    stepCell  =  200;

Definition of the queries

Axis measurement data

getAxis[magnet_,  step_String] := 
      SQLExecute[
        conn, 
"select magnet_nu, step, aperture, side, \
avg(1000*dx) dx, 1000*y y, avg(1000*dz) dz 
   from CRYOGEO_AXIS
   where magnet_nu = `1` 
   and final_meas = 'T'
   and step in (`2`,'ITP20-GEO')
   group by magnet_nu, step, aperture, side, 1000*y
   order by step, aperture, side, y", {magnet,  step}]

Flanges data for ITP20-GEO

getFlanges[magnet_] := 
      SQLExecute[
        conn, 
"select magnet_nu, step, side, aperture, \
1000*DX dx,
	case when side = 'connection'
		then 1000*DY - 64
		else 1000*DY + 15158 + 64 end as y, 1000*DZ dz
	from CRYOGEO_FLANGES
	where final_meas = 'T'
	and magnet_nu = `1`
	and step = 'ITP20-GEO'
	order by magnet_nu, step, side, aperture, y", {magnet}]

End covers data

getEndCovers [magnet_,  step_String] :=  
      SQLExecute[
        conn, 
"select magnet_nu, step, side, \
1000*CENTER_DX dx,
	case when side='connection'
		then 1000*CENTER_DY
		else 1000*CENTER_DY+15157 end as y, 1000*CENTER_DZ dz
	from CRYOGEO_END_COVERS
	where final_meas='T'
	and magnet_nu = `1`
	and step in ('ITP20-GEO',`2`)
	order by magnet_nu,step,side,1000*y", {magnet,  step}]

Classes

\(\(\(getClasses[magnet_, \ step_String] := \ 
      SQLExecute[
        conn, 
"select ITP20.magnet_nu magnet,WP08.step step,ITP20.class ITP20_CLASS,WP08.class WP08_CLASS
	from
	(select magnet_nu,step,class from CRYOGEO_CLASSIFICATION 
	 where magnet_nu= `1`
	 and step = 'ITP20-GEO') ITP20,
	(select magnet_nu,step,class from CRYOGEO_CLASSIFICATION 
	 where magnet_nu= `1`
	 and step = `2`) WP08
	where ITP20.magnet_nu = WP08.magnet_nu", {magnet, \ step}]\)\(
\)
    \)\)

\(\(register[
\ \ MAGNET_, \ MEASID_, \ FINAL_String, \ 
          STEP_String, \ 
\ \ DISTAVGA1_, \ DISTMAXA1_, 
          DISTAVGA2_, \ DISTMAXA2_, \ 
	DIFFSHIFTA1_\ , \ DIFFSLOPEA1_, \ 
          DIFFRMSA1_, 
	DIFFSHIFTA2_\ , \ DIFFSLOPEA2_, \ DIFFRMSA2_, 
	
          CORRDISTAVGA1_, CORRDISTMAXA1_, \ CORRDISTAVGA2_\ , \ 
          CORRDISTMAXA2_, 
	NEWPLANESHIFT_, \ NEWPLANEX_, \ 
          NEWPLANEY_, \ 
	SHIFTCONNA1_, \ \ SHIFTLYREA1_\ , \ 
          SHIFTCONNA2_, \ SHIFTLYREA2_, \ ANGLEZ_]\  := \ 
        SQLExecute[
          conn, 
"insert into MAS_PDA.aux_cryogeo_saw_tooth 
   values (`1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`,
   `11`, `12`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `24`, `25`, `26`, sysdate)", 
{\ MAGNET, \ 
            MEASID, \ FINAL, \ STEP, \ 
\ \ DISTAVGA1, \ 
            DISTMAXA1, DISTAVGA2, \ DISTMAXA2, \ 
	DIFFSHIFTA1\ , \ 
            DIFFSLOPEA1, \ DIFFRMSA1, 
	DIFFSHIFTA2, \ DIFFSLOPEA2, \ 
            DIFFRMSA2, 
	CORRDISTAVGA1, CORRDISTMAXA1, \ CORRDISTAVGA2\ , \ 
            CORRDISTMAXA2, 
	NEWPLANESHIFT, \ NEWPLANEX, \ NEWPLANEY, \ 
	
            SHIFTCONNA1, \ \ SHIFTLYREA1, \ SHIFTCONNA2, \ SHIFTLYREA2, \ 
            ANGLEZ}];\)\)

Definition of the correction procedure

analyseMagnet[magnet_,  step_]:=Module[
{magnetData},
CompoundExpression[
magnetData  =  getAxis[magnet, step];

  
magnetITP20  =  
                  getRows[magnetData, "ITP20-GEO",  2];
oneConnFirmAll = getRows[
                      getRows[magnetITP20, 1. , 3], "connection", 
                      4][[All, {5, 6, 7}]];
oneLyreFirmAll = getRows[
                      getRows[magnetITP20, 1. , 3], "lyre", 
                      4][[All, {5, 6, 7}]];
twoConnFirmAll = getRows[
                      getRows[magnetITP20, 2. , 3], "connection", 
                      4][[All, {5, 6, 7}]];
twoLyreFirmAll = getRows[
                      getRows[magnetITP20, 2. , 3], "lyre", 
                      4][[All, {5, 6, 7}]];

If[
                  Length[oneConnFirmAll] == 
                    0, oneConnFirmAll = getRows[
                          getRows[magnetITP20, 1. , 3], "combined", 
                          4][[All, {5, 6, 7}]];];
	If[
                  Length[twoConnFirmAll] == 
                    0, twoConnFirmAll = getRows[
                          getRows[magnetITP20, 2. , 3], "combined", 
                          4][[All, {5, 6, 7}]];];

oneConnFirm  =  oneConnFirmAll[[All, {2, 3}]][[Ordering[
                        oneConnFirmAll[[All, 2]]]]];oneLyreFirm  =  oneLyreFirmAll[[All, {2, 
                          3}]][[Ordering[
                        oneLyreFirmAll[[All, 2]]]]];
twoConnFirm =  twoConnFirmAll[[All, {2, 3}]][[Ordering[
                        twoConnFirmAll[[All, 2]]]]];
twoLyreFirm  =  twoLyreFirmAll[[All, {2, 3}]][[Ordering[
                        twoLyreFirmAll[[All, 2]]]]];

  
dataFlanges  =  
                  getFlanges[magnet];
oneConnFirmFlange  =  getRows[
                      getRows[getRows[dataFlanges, 1. , 4], "connection", 
                        3],  "ITP20-GEO", 2][[All, {6,  7}]];oneLyreFirmFlange  = getRows[
                      getRows[getRows[dataFlanges, 1. , 4], "lyre", 
                        3],  "ITP20-GEO", 2][[All, {6,  7}]];twoConnFirmFlange  =  getRows[
                      getRows[getRows[dataFlanges, 2. , 4], "connection", 
                        3],  "ITP20-GEO", 2][[All, {6,  7}]];twoLyreFirmFlange  =  getRows[
                      getRows[getRows[dataFlanges, 2. , 4], "lyre", 
                        3],  "ITP20-GEO", 2][[All, {6,  7}]];

  
Clear[endcovers];
endcovers = getEndCovers[magnet,  step];

  
classes  =  
                  getClasses[magnet,  step];

  
magnetWP08  = 
                  Complement[magnetData,  magnetITP20];
magnetWP08 = 
                  If [Length[magnetWP08]  ==  0, magnetITP20, 
                    magnetWP08];
oneConnCERNAll = getRows[
                      getRows[magnetWP08, 1. , 3], "connection", 
                      4][[All, {5, 6, 7}]];
oneLyreCERNAll = getRows[
                      getRows[magnetWP08, 1. , 3], "lyre", 
                      4][[All, {5, 6, 7}]];
twoConnCERNAll = getRows[
                      getRows[magnetWP08, 2. , 3], "connection", 
                      4][[All, {5, 6, 7}]];
twoLyreCERNAll = getRows[
                      getRows[magnetWP08, 2. , 3], "lyre", 
                      4][[All, {5, 6, 7}]];
oneConnCERN  =  
                  Union[oneConnCERNAll[[All, {2, 3}]]];
oneLyreCERN  =  
                  Union[oneLyreCERNAll[[All, {2, 3}]]];
twoConnCERN  =  
                  Union[twoConnCERNAll[[All, {2, 3}]]];
twoLyreCERN  =  
                  Union[twoLyreCERNAll[[All, {2, 3}]]];

fitDiffA1  =  
                  fitDiff[oneConnCERN, oneLyreCERN];
pointsOne  =  points;fitLinearOne =  fitLinear;

fitDiffA2  =  
                  fitDiff[twoConnCERN, twoLyreCERN];
pointsTwo  =  points;fitLinearTwo =  fitLinear;

minR = 
                  1.2*Min[pointsOne[[All, 2]], 
                      pointsTwo[[All, 
                          2]], 
FindMinimum[
                          BestFit /. fitLinearOne, {x, -1000, -1000, 
                            16000}][[1]], 
FindMinimum[
                          BestFit /. fitLinearTwo, {x, -1000, -1000, 
                            16000}][[1]]];
 maxR = 
                  1.1*Max[pointsOne[[All, 2]], 
                      pointsTwo[[All, 
                          2]], 
FindMaximum[
                          BestFit /. fitLinearOne, {x, -1000, -1000, 
                            16000}][[1]], 
FindMaximum[
                          BestFit /. fitLinearTwo, {x, -1000, -1000, 
                            16000}][[1]]];
diff := DisplayTogetherArray[
DisplayTogether[ListPlot[pointsOne, 
                            PlotJoined  ->  True],Plot[
                            BestFit /. fitLinearOne, {x, -1000, 16000}],
PlotRange -> {minR, maxR},
Axes ->  True,
\(TextStyle -> {FontWeight -> "Bold", FontSize -> textSize}\), PlotLabel->
"MB " <> 
                              ToString[
                                magnet]  <>  " A1, difference. " , Background->Floral],
DisplayTogether[ListPlot[pointsTwo, 
                            PlotJoined  ->  True],Plot[
                            BestFit /. fitLinearTwo, {x, -1000, 16000}],
PlotRange -> {minR, maxR},
Axes ->  True,
\(TextStyle -> {FontWeight -> "Bold", FontSize -> textSize}\), PlotLabel->
"MB " <> 
                              ToString[
                                magnet]  <>  " A2, difference. " , Background->Floral],ImageSize ->  900];

 (* 
                    distances between curves of the CERN measurements *) 
sawToothAvg1 =  
                  SetAccuracy[Distance[oneConnCERN, oneLyreCERN, 1], 4];
sawToothMax1 =  
                  SetAccuracy[
                    Distance[oneConnCERN, oneLyreCERN, ∞], 4];
  
sawToothAvg2 =  
                  SetAccuracy[Distance[twoConnCERN, twoLyreCERN, 1], 4];
sawToothMax2 =  
                  SetAccuracy[
                    Distance[twoConnCERN, twoLyreCERN, ∞], 4];
  

  
fitOneConn =Regress[
Select[
                        oneConnCERN, #[[1]] > 
                            Min[oneConnCERN[[All, 1]]]  +  
                              stepCell &],
Table[x^a, {a, 0, 1}],x,RegressionReport->{BestFit,BestFitParameters}];
fitOneLyre =Regress[
Select[
                        oneLyreCERN, #[[1]] < 
                            Max[oneLyreCERN[[All, 1]]]  -  
                              stepCell &],
Table[x^a, {a, 0, 1}],x,RegressionReport->{BestFit,BestFitParameters}];
fitTwoConn =Regress[
Select[
                        twoConnCERN, #[[1]] > 
                            Min[twoConnCERN[[All, 1]]]  + stepCell &],
Table[x^a, {a, 0, 1}],x,RegressionReport->{BestFit,BestFitParameters}];
fitTwoLyre =Regress[
Select[
                        twoLyreCERN, #[[1]] < 
                            Max[twoLyreCERN[[All, 1]]]  -  
                              stepCell &],
Table[x^a, {a, 0, 1}],x,RegressionReport->{BestFit,BestFitParameters}];

  
ygrekOneConn  =  
                  Min[oneConnCERN[[All, 1]]] +  stepCell;
ygrekOneLyre  =  
                  Max[oneLyreCERN[[All, 1]]] - stepCell;
zetOneConn  =  BestFit /. 
                      fitOneConn /. x ->  ygrekOneConn;
zetOneLyre  =  BestFit /. 
                      fitOneLyre /. x ->  ygrekOneLyre;
slopeOne  =  (zetOneLyre - 
                        zetOneConn)/(ygrekOneLyre  -  ygrekOneConn);
shiftOne  =  
                  zetOneConn - slopeOne ygrekOneConn;
refOne  =  
                  slopeOne x  +  shiftOne;

ygrekTwoConn  =  
                  Min[twoConnCERN[[All, 1]]] + stepCell;
ygrekTwoLyre  =  
                  Max[twoLyreCERN[[All, 1]]] - stepCell;
zetTwoConn  =  BestFit /. 
                      fitTwoConn /. x ->  ygrekTwoConn;
zetTwoLyre  =  BestFit /. 
                      fitTwoLyre /. x ->  ygrekTwoLyre;
slopeTwo  =  (zetTwoLyre - 
                        zetTwoConn)/(ygrekTwoLyre  -  ygrekTwoConn);
shiftTwo  =  
                  zetTwoConn - slopeTwo ygrekTwoConn;
refTwo  =  
                  slopeTwo x  +  shiftTwo;

  
orig :=DisplayTogetherArray[DisplayTogether[
Graphics[{RGBColor[0, 1, 0], 
                              Thickness[0.007], 
                              Circle[First[oneConnCERN], 
                                Scaled[{0.01, 0.02}]]}],
Graphics[{RGBColor[0, 0, 
                                1], Thickness[0.007], 
                              Circle[Last[oneLyreCERN], 
                                Scaled[{0.01, 0.02}]]}],
Graphics[{RGBColor[1, 0, 
                                0], Thickness[0.007], 
                              Circle[First[oneConnFirmFlange], 
                                Scaled[{0.01, 0.02}]]}],
Graphics[{RGBColor[1, 0, 
                                0], Thickness[0.007], 
                              Circle[First[oneLyreFirmFlange], 
                                Scaled[{0.01, 0.02}]]}],
  
ListPlot[oneConnCERN, 
                            PlotJoined  -> True,  
                            PlotStyle -> {Green}], 
ListPlot[oneLyreCERN,  
                            PlotJoined  -> True,  
                            PlotStyle -> {Blue}],ListPlot[Union[oneConnFirm, oneLyreFirm],  
                            PlotJoined  -> True,  
                            PlotStyle -> {Red}], PlotRange -> {-0.8, 0.8},
Axes ->  True,
\(TextStyle -> {FontWeight -> "Bold", FontSize -> textSize}\), PlotLabel->
"MB "<>ToString[magnet] <> " A1, max saw tooth " <>  ToString[sawToothMax1,TraditionalForm] , Background->Floral],
DisplayTogether[
Graphics[{RGBColor[0, 1, 0], 
                              Thickness[0.007], 
                              Circle[First[twoConnCERN], 
                                Scaled[{0.01, 0.02}]]}],
Graphics[{RGBColor[0, 0, 
                                1], Thickness[0.007], 
                              Circle[Last[twoLyreCERN], 
                                Scaled[{0.01, 0.02}]]}],
Graphics[{RGBColor[1, 0, 
                                0], Thickness[0.007], 
                              Circle[First[twoConnFirmFlange], 
                                Scaled[{0.01, 0.02}]]}],
Graphics[{RGBColor[1, 0, 
                                0], Thickness[0.007], 
                              Circle[First[twoLyreFirmFlange], 
                                Scaled[{0.01, 0.02}]]}],
  
ListPlot[twoConnCERN, 
                            PlotJoined  -> True,  
                            PlotStyle -> {Green}], 
ListPlot[twoLyreCERN,  
                            PlotJoined  -> True,  
                            PlotStyle -> {Blue}],ListPlot[Union[twoConnFirm, twoLyreFirm],  
                            PlotJoined  -> True,  
                            PlotStyle -> {Red}], PlotRange -> {-0.8, 0.8},
Axes ->  True,
\(TextStyle -> {FontWeight -> "Bold", FontSize -> textSize}\), PlotLabel-> 
"MB "<> ToString[magnet] <> " A2, max saw tooth " <>  ToString[sawToothMax2,TraditionalForm], Background->Floral], ImageSize ->  900];

  
devOneConn =  (BestFit /. 
                        fitOneConn) -  refOne;
devOneLyre =  (BestFit /. 
                        fitOneLyre) -  refOne;
devTwoConn =  (BestFit /. 
                        fitTwoConn) -  refTwo;
devTwoLyre =  (BestFit /. 
                        fitTwoLyre) -  refTwo;

  
addOneConn[{abs_,  ord_}]  :=  
                  If[abs  ≤  ygrekOneConn,  {abs, 
                      ord},  {abs,  ord - devOneConn /. x -> abs}];
corrOneConn = 
                  Map[addOneConn, oneConnCERN];
addOneLyre[{abs_,  ord_}]  :=  
                  If[abs  ≥  ygrekOneLyre,  {abs, 
                      ord},  {abs,  ord -  devOneLyre /. x -> abs}];
corrOneLyre = 
                  Map[addOneLyre, oneLyreCERN];

addTwoConn[{abs_,  ord_}]  :=  
                  If[abs  ≤  ygrekTwoConn,  {abs, 
                      ord},  {abs,  ord - devTwoConn /. x -> abs}];
corrTwoConn = 
                  Map[addTwoConn, twoConnCERN];
addTwoLyre[{abs_,  ord_}]  :=  
                  If[abs  ≥  ygrekTwoLyre,  {abs, 
                      ord},  {abs,  ord -  devTwoLyre /. x -> abs}];
corrTwoLyre = 
                  Map[addTwoLyre, twoLyreCERN];

  
corrsawToothMax1  =  
                  Distance[corrOneConn,  corrOneLyre,  ∞];
corrsawToothMax2  =  
                  Distance[corrTwoConn,  corrTwoLyre,  ∞];
corrsawToothAvg1  =  
                  Distance[corrOneConn,  corrOneLyre,  1];
corrsawToothAvg2  =  
                  Distance[corrTwoConn,  corrTwoLyre,  1];

  
ply :=DisplayTogetherArray[DisplayTogether[
Plot[refOne,  {x,  -1000,  16000},  
                            PlotStyle -> {Black}],
ListPlot[corrOneConn, 
                            PlotJoined  -> True,  
                            PlotStyle -> {Green}], 
ListPlot[corrOneLyre,  
                            PlotJoined  -> True,  
                            PlotStyle -> {Blue}],PlotRange -> {-0.8, 0.8}, Background->Floral,
\(TextStyle -> {FontWeight -> "Bold", FontSize -> textSize}\), 
PlotLabel->
"MB"  <>  
                              ToString[
                                magnet]  <>  " A1, corr + reference \
line"],
DisplayTogether[
Plot[refTwo,  {x,  -1000,  16000},  
                            PlotStyle -> {Black}],
ListPlot[corrTwoConn, 
                            PlotJoined  -> True,  
                            PlotStyle -> {Green}], 
ListPlot[corrTwoLyre,  
                            PlotJoined  -> True,  
                            PlotStyle -> {Blue}],PlotRange -> {-0.8, 0.8}, Background->Floral,
\(TextStyle -> {FontWeight -> "Bold", FontSize -> textSize}\), 
PlotLabel-> 
ToString[
                                magnet]  <>  " A2, corr + reference \
line"],
ImageSize -> 900];

  
findXone[{dx_, dy_}] := 
                  dx + (shapeOuter /. x ->  dy);
realXoneConn =  
                  Map[findXone, oneConnCERNAll[[All, {1, 
                            2}]][[Ordering[
                          oneConnCERNAll[[All, 2]]]]]];
realXoneLyre =  
                  Map[findXone, oneLyreCERNAll[[All, {1, 
                            2}]][[Ordering[
                          oneLyreCERNAll[[All, 2]]]]]];
findXtwo[{dx_, dy_}] := 
                  dx + (shapeInner /. x ->  dy);
realXtwoConn =  
                  Map[findXtwo, twoConnCERNAll[[All, {1, 
                            2}]][[Ordering[
                          twoConnCERNAll[[All, 2]]]]]];
realXtwoLyre =  
                  Map[findXtwo, twoLyreCERNAll[[All, {1, 
                            2}]][[Ordering[
                          twoLyreCERNAll[[All, 2]]]]]];
oneConn3D  =  
                  Transpose[
{realXoneConn, 
                      corrOneConn[[All, 1]], 
                      corrOneConn[[All, 2]]}];
oneLyre3D  =  
                  Transpose[
{ realXoneLyre, 
                      corrOneLyre[[All, 1]], 
                      corrOneLyre[[All, 2]]}];
twoConn3D  =  
                  Transpose[
{realXtwoConn, 
                      corrTwoConn[[All, 1]], 
                      corrTwoConn[[All, 2]]}];
twoLyre3D  =  
                  Transpose[
{ realXtwoLyre, 
                      corrTwoLyre[[All, 1]], 
                      corrTwoLyre[[All, 2]]}];

  
fitCorr3DNominal=Regress[Join[Rest[oneConn3D],  Most[oneLyre3D],  
                        Rest[twoConn3D],  Most[twoLyre3D]],{1, x,  y},{x, y},
Weights  -> 
Join[
                            1. /(errorMole^2  + ((errorLaser^2) ((Rest[corrOneConn][[All, 1]] -  
                                        trackerConn)^2))), 
1. /(errorMole^2  + ((errorLaser^2) ((trackerLyre - Most[corrOneLyre][[All, 
                                        1]])^2))), 
1. /(errorMole^2  + ((errorLaser^2) ((Rest[
                                        corrTwoConn][[All, 1]] -  
                                        
                                        trackerConn)^2))), 
1. /(errorMole^2  + ((errorLaser^2) ((trackerLyre - Most[corrTwoLyre][[All, 1]])^2)))],
RegressionReport->{BestFit, ParameterCITable,ParameterConfidenceRegion}];
newAxisNominal = 
                  BestFit /. fitCorr3DNominal;

  
newMidPlane := Plot3D[newAxisNominal,{x, -100, 100},{y, -1000,  16000},
AxesLabel ->  {"x [mm] \
  ", "y [mm]", "z [mm]  "}, Mesh  ->  True, BoxRatios ->  {1, 3, 1}, ImageSize ->  400,
 Background->Floral, TextStyle -> {FontWeight -> "Bold", 
                          FontSize -> textSize}, PlotLabel  ->  
                        ToString[magnet]  <>  "\nz = "  <>  
                          ToString[ newAxisNominal, StandardForm]];

  
A=CoefficientList[newAxisNominal, {x}][[2]];
B = CoefficientList[newAxisNominal, {y}][[2]];
CZ =  -1;
vectorXNew  =  
                  Solve[{
(x^2) + (y^2) + (z^2) == 
                        1. , 
A x  +  B y  +  
                          CZ z  ==  
                        0. , 
(1/(Sqrt[1 + (B^2)])) y  +  (B/(Sqrt[1 + (B^2)])) z  ==  0. }, {x, y, z}];
solution = 
                  First[First[
                      Position[x /. vectorXNew, _?(# > 0.  &)]]];
RotationMatrix = 
{
{x /. vectorXNew[[solution]], 
                      y /. vectorXNew[[solution]], 
                      z /. vectorXNew[[solution]]}, 
{0, 1/(Sqrt[1 + (B^2)]), 
                      B/(Sqrt[1 + (B^2)])}, 
{-A/(Sqrt[(A^2) + (B^2) + (CZ^2)]), -B/(Sqrt[(A^2) + (B^2) + (CZ^2)]), -CZ/(Sqrt[(A^2) + (B^2) + (CZ^2)])}};

  
MidPlaneShift= CoefficientList[newAxisNominal, {x, y}][[1]][[1]];
TranslationMatrix = {{0. }, {0. }, {MidPlaneShift}};

   
oneConnNew  = 
                  Partition[
                    Flatten[
 
                      Table[ RotationMatrix . (oneConn3D[[i]]  -  
                              TranslationMatrix), {i, 1, 
                          Length[oneConn3D]}], 2], 3];
oneLyreNew  = 
                  Partition[
                    Flatten[
 
                      Table[ RotationMatrix . (oneLyre3D[[i]]  -  
                              TranslationMatrix), {i, 1, 
                          Length[oneLyre3D]}], 2], 3];
twoConnNew  = 
                  Partition[
                    Flatten[
 
                      Table[ RotationMatrix . (twoConn3D[[i]]  -  
                              TranslationMatrix), {i, 1, 
                          Length[twoConn3D]}], 2], 3];
twoLyreNew  = 
                  Partition[
                    Flatten[
 
                      Table[ RotationMatrix . (twoLyre3D[[i]]  -  
                              TranslationMatrix), {i, 1, 
                          Length[twoLyre3D]}], 2], 3];

  
recoverXone[{dx_, dy_}] := 
                  dx - (shapeOuter /. x ->  dy);
recoverXoneConn =  
                  Map[recoverXone, oneConnNew[[All, {1, 2}]]];
recoverXoneLyre =  
                  Map[recoverXone, oneLyreNew[[All, {1, 2}]]];
recoverXtwo[{dx_, dy_}] := 
                  dx - (shapeInner /. x ->  dy);
recoverXtwoConn =  
                  Map[recoverXtwo, twoConnNew[[All, {1, 2}]]];
recoverXtwoLyre =  
                  Map[recoverXtwo, twoLyreNew[[All, {1, 2}]]];
delta1Conn3D  =  
                  Transpose[
{(10^(-3)) oneConnNew[[All, 2]], (10^(-3)) recoverXoneConn, (10^(-3)) 
                        oneConnNew[[All, 3]]}];
delta1Lyre3D  =  
                  Transpose[
{(10^(-3)) oneLyreNew[[All, 2]], (10^(-3)) recoverXoneLyre, (10^(-3)) 
                        oneLyreNew[[All, 3]]}];
delta2Conn3D  =  
                  Transpose[
{(10^(-3)) twoConnNew[[All, 2]], (10^(-3)) recoverXtwoConn, (10^(-3)) 
                        twoConnNew[[All, 3]]}];
delta2Lyre3D  =  
                  Transpose[
{ 
                      (10^(-3)) twoLyreNew[[All, 2]], (10^(-3)) 
                        recoverXtwoLyre, (10^(-3)) 
                        twoLyreNew[[All, 3]]}];
class  =  
                  First[GeoClassification[
Transpose[
                        Join[ delta1Conn3D,  delta1Lyre3D]], 
                      Transpose[Join[ delta2Conn3D,  delta2Lyre3D]]]];

  
Clear[endcITP20,  endcWP08,  
                  endConnFirm,  endLyreFirm,  endConnCERN, endLyreCERN,  
                  endConnCERNNew,  endLyreCERNNew ];
\(If[Length[endcovers]\  > \ 0, 
                  CompoundExpression[
endcITP20\  = 
                      getRows[
                        getRows[endcovers, \ magnet, \ 1], "ITP20-GEO", \ 
                        2]; 
endcWP08\  = \ 
                      Complement[getRows[endcovers, \ magnet, \ 1], \ 
                        endcITP20]; 
endcWP08 = 
                      If\ [Length[endcWP08] == 0, endcITP20, 
                        endcWP08]; 
endConnFirm\  = \ \(getRows[endcITP20, "connection", 
                          3]\)[\([All, {4, 5, 
                            
                            6}]\)]; 
endLyreFirm\  = \ \(getRows[endcITP20, "lyre", 
                          3]\)[\([All, {4, 5, 
                            6}]\)]; 
endConnCERN\  = \ \(getRows[endcWP08, "connection", 
                          3]\)[\([All, {4, 5, 
                            6}]\)]; 
endLyreCERN\  = \ \(getRows[endcWP08, "lyre", 
                          3]\)[\([All, {4, 5, 
                            6}]\)]; 
endConnCERNNew\  = \ 
                      Partition[
                        Flatten[
                          Table[\ 
                            RotationMatrix . \((endConnCERN[\([i]\)]\  - \ 
                                  TranslationMatrix)\), {i, 1, 
                              Length[endConnCERN]}], 2], 
                        3]; 
endLyreCERNNew\  = \ 
                      Partition[
                        Flatten[
                          Table[\ 
                            RotationMatrix . \((endLyreCERN[\([i]\)]\  - \ 
                                  TranslationMatrix)\), {i, 1, 
                              Length[endLyreCERN]}], 2], 3];], Null]\);

  
sawToothAvg1New  = 
                  SetAccuracy[
                    Distance[oneConnNew[[All, {2, 3}]], 
                      oneLyreNew[[All, {2, 3}]], 1], 4];
sawToothAvg2New  = 
                  SetAccuracy[
                    Distance[twoConnNew[[All, {2, 3}]], 
                      twoLyreNew[[All, {2, 3}]], 1], 4];
sawToothMax1New  = 
                  SetAccuracy[
                    Distance[oneConnNew[[All, {2, 3}]], 
                      oneLyreNew[[All, {2, 3}]], ∞], 4];
sawToothMax2New  = 
                  SetAccuracy[
                    Distance[twoConnNew[[All, {2, 3}]], 
                      twoLyreNew[[All, {2, 3}]], ∞], 4];
  

  
new := DisplayTogetherArray[
DisplayTogether[
Graphics[{RGBColor[0, 1, 0], 
                              Thickness[0.007], 
                              Circle[oneConnNew[[1, {2, 3}]], 
                                Scaled[{0.01, 0.02}]]}],
Graphics[{RGBColor[0, 0, 
                                1], Thickness[0.007], 
                              Circle[Last[oneLyreNew[[All, {2, 3}]]], 
                                Scaled[{0.01, 0.02}]]}],
Graphics[{RGBColor[1, 0, 
                                0], Thickness[0.007], 
                              Circle[First[oneConnFirmFlange], 
                                Scaled[{0.01, 0.02}]]}],
Graphics[{RGBColor[1, 0, 
                                0], Thickness[0.007], 
                              Circle[First[oneLyreFirmFlange], 
                                Scaled[{0.01, 0.02}]]}],
ListPlot[
                            oneConnNew[[All, {2, 3}]],  
                            PlotJoined ->  True,  
                            PlotStyle ->  {Green},  
                            PlotRange ->  {-0.8,  0.8}],
ListPlot[
                            oneLyreNew[[All, {2, 3}]],  
                            PlotJoined ->  True,  
                            PlotStyle ->  {Blue},  
                            PlotRange ->  {-0.8,  0.8}],
ListPlot[
                            Union[oneConnFirm, oneLyreFirm],  
                            PlotJoined  -> True,  
                            PlotStyle -> {Red},  
                            PlotRange -> {-0.8, 0.8}], 
\(TextStyle -> {FontWeight -> "Bold", FontSize -> textSize}\),PlotLabel->"MB " <> ToString[magnet] <> 
" A1 corr, max saw tooth "<>ToString[sawToothMax1New, TraditionalForm]<>"\n " <> magnetsList[[i, 3]],
Axes ->  True, Background->Floral, PlotRange -> {-0.8, 0.8}],
DisplayTogether[
Graphics[{RGBColor[0, 1, 0], 
                              Thickness[0.007], 
                              Circle[twoConnNew[[1, {2, 3}]], 
                                Scaled[{0.01, 0.02}]]}],
Graphics[{RGBColor[0, 0, 
                                1], Thickness[0.007], 
                              Circle[Last[twoLyreNew[[All, {2, 3}]]], 
                                Scaled[{0.01, 0.02}]]}],
Graphics[{RGBColor[1, 0, 
                                0], Thickness[0.007], 
                              Circle[First[twoConnFirmFlange], 
                                Scaled[{0.01, 0.02}]]}],
Graphics[{RGBColor[1, 0, 
                                0], Thickness[0.007], 
                              Circle[First[twoLyreFirmFlange], 
                                Scaled[{0.01, 0.02}]]}],
ListPlot[
                            twoConnNew[[All, {2, 3}]],  
                            PlotJoined ->  True, 
                            PlotStyle ->  {Green}, 
                            PlotRange ->  {-0.8,  0.8}], 
ListPlot[
                            twoLyreNew[[All, {2, 3}]],  
                            PlotJoined ->  True, 
                            PlotStyle ->  {Blue}, 
                            PlotRange ->  {-0.8,  0.8}], 
ListPlot[
                            Union[twoConnFirm, twoLyreFirm],  
                            PlotJoined  -> True,  
                            PlotStyle -> {Red},  
                            PlotRange -> {-0.8, 0.8}], TextStyle -> {FontWeight -> "Bold", 
                              FontSize -> textSize}, PlotLabel->"MB "<> ToString[magnet] <> 
" A2 corr, max saw tooth "<>ToString[sawToothMax2New, TraditionalForm],
Axes ->  True,Background->Floral, PlotRange -> {-0.8, 0.8}],
ImageSize ->  
                        900];

]
];

Definition of the Magnet Analysis Procedure

analysis := CompoundExpression[
	i =  0; \(results\  = \ {{
"Magnet", "Step", "Adjustment", "Saw tooth A1", "Saw tooth A2", "Corr A1", "CorrA2", 
"GA Shift", \ "GA Slope by X", \ "GA Slope by Y", "GA Shift SE", "GA Slope by X SE", \ "GA Slope by Y SE", 
"Firm endc conn", "Firm endc lyre", "Orig endc conn", "Orig endc lyre", "Corr endc conn", "Corr endc lyre", 
"Shift A1 conn", "Shift A2 conn", "Shift A1 lyre", "Shift A2 lyre", "Shift average", "Shift max", 
"ITP20 class", "WP08 class", "New class", "New Z y", "New Z z", "DB"}}\);
If[createReport  ==  1, 
            nb = NotebookCreate[]];
If[createReport  ==  1, 
            NotebookWrite[nb,  
              Cell["Saw tooth analysis report", "Title"]]];
today = Date[];
printDate  = 
            ToString[today[[3]]] <> " " <> 
              allmonths[[today[[2]]]] <> " " <>  
              ToString[today[[1]]];
If[createReport  ==  1, 
            NotebookWrite[nb,  Cell[printDate, "Subsubtitle"],  
              After]];
Do[CompoundExpression[
	\(conn = 
                    OpenSQLConnection[
                      JDBC["oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:@(DESCRIPTION=(FAILOVER=on)(LOAD_BALANCE=off) (ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=orapdb2.cern.ch)(PORT=1521)) (ADDRESS=(PROTOCOL=TCP)(HOST=orapdb1.cern.ch)(PORT=1521))) (CONNECT_DATA=(SERVICE_NAME=PDB.WORLD) (FAILOVER_MODE=(TYPE=SELECT)(METHOD=BASIC))))"], 
                      Username -> "MAS_ALL", 
                      Password -> \ MyPassword]\);
	i = i + 1;
	magnet = magnetsList[[i, 1]];
	If[createReport  ==  1, 
                    NotebookWrite[nb, Cell[ToString[magnet], "Section"], 
                      After]];
	step  =  magnetsList[[i, 2]];
	measid  =  magnetsList[[i,  4]];
	adjustment  =  magnetsList[[i, 3]];
	analyseMagnet[magnet,  step];
	classITP20  =  First[
                        getRows[classes, magnet, 1]][[3]];
	classWP08  =  First[
                        getRows[classes, magnet, 1]][[4]];
	If[createReport  ==  1, 
                    NotebookWrite[nb, 
                      Cell["Step: "  <>  
                          step  <>  ", adjustment: "  <>  
                          adjustment, "Text"], After]];
	If[createReport  ==  1, 
                    NotebookWrite[nb, 
                      Cell["Saw tooth statistics [mm] before and after the \
correction", "Text"], After]];
	\(If[
                    createReport\  == \ 
                      1, 
		NotebookWrite[nb, 
                      Cell[BoxData[
                          ToBoxes[
	{{"", "Avg A1", "Max A1", "Avg A2", "Max A2"}, 
	{"Original", \ sawToothAvg1, sawToothMax1, sawToothAvg2, 
                                  sawToothMax2}, 
	{"Corrected", \ sawToothAvg1New, \ \ sawToothMax1New, \ 
                                  sawToothAvg2New, \ sawToothMax2New\ }\ }\  // 
                              TableForm]], 
	"Output"], After]]\);
	SE=First[ParameterCITable/.fitCorr3DNominal][[All, 2]];
	\(If[createReport\  == \ 1, 
                    NotebookWrite[nb, 
                      Cell["Mid-plane fit after the correction", "Text"], After]]\);
	If[createReport  ==  1,NotebookWrite[nb,Cell[BoxData[ToBoxes[ParameterCITable /. 
                                      fitCorr3DNominal]],"Output"],After]];
	If[createReport  ==  1, 
                    NotebookWrite[nb, 
                      Cell[BoxData[
                          ToBoxes["Classification"]], "Text"], 
                      After]];
	If[createReport  ==  1,NotebookWrite[nb,
	Cell[BoxData[ToBoxes[
{{"ITP20-GEO", 
                                        classITP20}, {step, 
                                        classWP08}, {"Corrected", 
                                        class}} // TableForm]],"Output"],After]];
	\(If[createReport\  == \ 1, 
                    NotebookWrite[nb, 
	
                      Cell[BoxData[
                          ToBoxes["Correction shifts at the nominal flanges positions [mm]"]], "Text"], After]]\);
	
	xA1Conn = shapeOuter /. x ->  -64. ;
	xA2Conn = shapeInner /. x ->  -64. ;
	xA1Lyre = 
                    shapeOuter /. x ->  15158.   +  64. ;
	xA2Lyre = 
                    shapeInner /. x ->  15158.   +  64. ;

	shiftA1Conn  =  
                    SetAccuracy[
                      newAxisNominal /. {x ->  xA1Conn,  
                          y ->  -64. }, 4];
	shiftA2Conn  =  
                    SetAccuracy[
                      newAxisNominal /. {x ->  xA2Conn,  
                          y ->  -64. }, 4];
	shiftA1Lyre  = 
                    SetAccuracy[
                      newAxisNominal /. {x ->  xA1Lyre,  
                          y ->  15158.   +  64. }, 4] ;
	shiftA2Lyre  = 
                    SetAccuracy[
                      newAxisNominal /. {x ->  xA2Lyre,  
                          y ->  15158.   +  64. }, 4];
	
	\(If[createReport\  == \ 1, 
                    NotebookWrite[nb, 
	
                      Cell[BoxData[
                          ToBoxes[
	{{"", "X", "Y", "Shift"}, 
	{"Connection A1", 
                                  SetAccuracy[xA1Conn, 4], \(-64. \), 
                                  shiftA1Conn}, 
			\ \ {"Connection A2", SetAccuracy[xA2Conn, 4], \(-64. \), 
                                  shiftA2Conn}, 
	{"Lyre A1", \ \ \ \ \ \ \ \ \ \ \ \ \ SetAccuracy[xA1Lyre, 4], 15158. \  + \ 64. , 
                                  shiftA1Lyre}, 
	{"Lyre A2", \ \ \ \ \ \ \ \ \ \ \ \ \ SetAccuracy[xA2Lyre, 4], 15158. \  + \ 64. , 
                                  shiftA2Lyre}} // 
                              TableForm]], "Output"], After]]\); 

	angleY  =  
                    1000*(π/2  - 
                          ArcCos[-B/(Sqrt[(A^2) + (B^2) + (CZ^2)])]);
	angleZ  =  
                    1000*ArcCos[-CZ/(Sqrt[(A^2) + (B^2) + (CZ^2)])];

\(reg = 
                    register[magnet, \ measid, \ "T", \ 
                      step, \ 
sawToothAvg1, \ 
                      sawToothMax1, sawToothAvg2, \ sawToothMax2, \ 
	
                      fitDiffA1[\([1]\)], fitDiffA1[\([2]\)], 
                      fitDiffA1[\([3]\)], 
	fitDiffA2[\([1]\)], 
                      fitDiffA2[\([2]\)], fitDiffA2[\([3]\)], 
	
                      sawToothAvg1New, \ sawToothMax1New, sawToothAvg2New, \ 
                      sawToothMax2New, \ 
	MidPlaneShift\ , \ A\ , \ 
                      B, 
shiftA1Conn, \ \ shiftA1Lyre\ , \ 
                      shiftA2Conn, \ shiftA2Lyre, \ angleZ]\);
\(results = \ 
                    Join[results, {Flatten[{magnet, \ step, \ 
                            adjustment, 
		sawToothAvg1, 
                            sawToothAvg2, sawToothAvg1New, 
                            sawToothAvg2New, 
		MidPlaneShift, A, \ B, \ \ SE[\([1]\)], \ SE[\([2]\)], \ 
                            SE[\([3]\)], 
		\(First[
                                endConnFirm]\)[\([3]\)], \(First[
                                endLyreFirm]\)[\([3]\)], 
		\(First[endConnCERN]\)[\([3]\)], \(First[
                                endLyreCERN]\)[\([3]\)], 
		\(First[endConnCERNNew]\)[\([3]\)], \(First[
                                endLyreCERNNew]\)[\([3]\)], 
		shiftA1Conn, shiftA2Conn, shiftA1Lyre, 
                            shiftA2Lyre, 
	\ Mean[{shiftA1Conn, shiftA2Conn, shiftA1Lyre, 
                                shiftA2Lyre}], 
	
                            Max[{Abs[shiftA1Conn], Abs[shiftA2Conn], 
                                Abs[shiftA1Lyre], 
                                Abs[shiftA2Lyre]}], 
		classITP20, classWP08, class, angleY, \ angleZ, \ reg}]}]\);

CloseSQLConnection[conn];

If[createReport  ==  1, 
                    NotebookWrite[nb, Cell["Original data", "Text"], 
                      After]];
If[createReport  ==  1,\(NotebookWrite[nb, \ 
	
                          Cell[GraphicsData["PostScript", \ 
                              DisplayString[orig], \ "Graphics"]]]\)];
If[createReport  ==  1, 
                    NotebookWrite[nb, 
                      Cell["Difference between connection and lyre \
curves", "Text"], After]];
If[createReport  ==  1,\(NotebookWrite[nb, \ 
	
                          Cell[GraphicsData["PostScript", \ 
                              DisplayString[diff], \ "Graphics"]]]\)];
If[createReport  ==  1, 
                    NotebookWrite[nb, 
                      Cell["Corrected data in the original reference system\
", "Text"], After]];
If[createReport  ==  1,\(NotebookWrite[nb, \ 
	
                          Cell[GraphicsData["PostScript", \ 
                              DisplayString[ply], \ "Graphics"]]]\)];
If[createReport  ==  1, 
                    NotebookWrite[nb, 
                      Cell["Corrected data in the reference system based on \
the new mid-plane", "Text"], After]];
If[createReport  ==  1,\(NotebookWrite[nb, \ 
	
                          Cell[GraphicsData["PostScript", \ 
                              DisplayString[new], \ "Graphics"]]]\)];
If[createReport  ==  1, 
                    NotebookWrite[nb, Cell["New mid-plane", "Text"], 
                      After]];
If[createReport  ==  1,\(NotebookWrite[nb, \ 
	
                          Cell[GraphicsData["PostScript", \ 
                              DisplayString[
                                newMidPlane], \ "Graphics"]]]\)];
If[exportPlots  ==  1,
CompoundExpression[
Export["C:\\geom reports \
special\\tube_measurements\\dipoles\\correction_procedure\\" <> 
                                ToString[magnet] <> "_orig.wmf",orig,"WMF"];
Export["C:\\geom reports \
special\\tube_measurements\\dipoles\\correction_procedure\\" <> 
                                ToString[magnet] <> "_new.wmf",new,"WMF"];
Export["C:\\geom reports \
special\\tube_measurements\\dipoles\\correction_procedure\\" <> 
                                ToString[magnet] <> "_plane.wmf",newMidPlane,"WMF"];], Null]], {Length[magnetsList]}]]

Get the list of the magnets

Select the magnets ready to be installed in the tunnel with their last step at WP08. The criteria are: max distance between curves more than bundle error (0.08mm) and mole centring error (0.07mm), the difference between curves close to linear (linear fit R2 > 0.7 and rms < 0.06mm (average rms)).

\(conn = 
          OpenSQLConnection[
            JDBC["oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:@(DESCRIPTION=(FAILOVER=on)(LOAD_BALANCE=off) (ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=orapdb2.cern.ch)(PORT=1521)) (ADDRESS=(PROTOCOL=TCP)(HOST=orapdb1.cern.ch)(PORT=1521))) (CONNECT_DATA=(SERVICE_NAME=PDB.WORLD) (FAILOVER_MODE=(TYPE=SELECT)(METHOD=BASIC))))"], 
            Username -> "MAS_ALL", Password -> \ MyPassword];\)
magnetsList  =  
        SQLExecute[
          conn, 
"select \
magnet_nu,step,nvl(decode(blockage_status,'as \
is','none',blockage_status),'none'),meas_id
	from CRYOGEO_MEAS_ENV A
	WHERE meas_id not in (select meas_id from MAS_PDA.AUX_CRYOGEO_SAW_TOOTH)
	and step like 'WP08%' and final_meas = 'T'
	and not exists (select 1 from cryogeo_meas_env where magnet_nu = A.magnet_nu \
and step like 'WP08%' and step > A.step)
	and 19<(select count(*) from CRYOGEO_AXIS where meas_id=A.meas_id and \
aperture=1 and side='connection') 
	and 19<(select count(*) from CRYOGEO_AXIS where meas_id=A.meas_id and \
aperture=1 and side='lyre') 
	and 19<(select count(*) from CRYOGEO_AXIS where meas_id=A.meas_id and \
aperture=2 and side='connection') 
	and 19<(select count(*) from CRYOGEO_AXIS where meas_id=A.meas_id and \
aperture=2 and side='lyre') 
	order by magnet_nu"];
CloseSQLConnection[
        conn];

{ToString[Length[magnetsList]] <>  " magnets"}

Results

exportPlots  =  0; createReport  =  0;

analysis;

Export["results.csv",results,"CSV"]