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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
|
/* $Id: vmmoswavecalib.c,v 1.2 2013/03/25 11:43:04 cgarcia Exp $
*
* This file is part of the VIMOS Pipeline
* Copyright (C) 2002-2004 European Southern Observatory
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* $Author: cgarcia $
* $Date: 2013/03/25 11:43:04 $
* $Revision: 1.2 $
* $Name: $
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <pilmemory.h>
#include <pilmessages.h>
#include <cpl_msg.h>
#include <piltranslator.h>
#include "vmimage.h"
#include "vmmatrix.h"
#include "vmtable.h"
#include "vmgrismtable.h"
#include "vmextractiontable.h"
#include "vmlinecatalog.h"
#include "vmdistmodels.h"
#include "vmmath.h"
#include "vmfit.h"
#include "vmmosutils.h"
#include "vmmoswavecalib.h"
#include "cpl.h"
/**
* @name vmmoswavecalib MOS Wavelength Calibration
*
* @doc
* The module collects MOS wavelenght calibration related functions.
*/
/**@{*/
/**
* @memo
* Fit an Inverse Dispersion Relation Model.
*
* @return EXIT_SUCCESS / EXIT_FAILURE
*
* @param inputImage Arc Lamp exposure
* @param extractionTable Extraction Table
* @param lineCat Line Catalog
* @param arcWidth Window used for determining the peak of a
* centered arc line (in CCD pixels).
* @param refineIDS flag to signal the need to refine the first guess
* IDS from the Extraction Table
*
* @doc
* Identify lines in Arc Spectrum, fit dispersion relation for
* every row in te Extraction Table. Calibrate X positioning of slit
*
* @author M. Scodeggio
*/
int VmSpDerDispOld(VimosImage *inputImage, VimosExtractionTable *extractionTable,
VimosTable *lineCat, int arcWidth, int refineIDS)
{
const char modName[] = "VmSpDerDisp";
int i, j, k;
int xOut, yOut;
int numRows, totNumRows;
int numPoints;
int foundLines;
int nPixBelow, nPixAbove;
int imageXlen, imageYlen;
int numLines;
int numLinesDone;
int disOrder;
int widthBuffer = 2;
int yExpect;
float yExpectFloat;
int validFit, invalidFit, totInvalidFit;
int slitCount = 0;
float lambdaCen;
float pos;
/*** float offset; ***/
int tolMax;
/*** float fitTol=2.0; ***/
float lambda2pix;
float mm2pix;
float pixWidth;
float lambdaWidth;
float nSigma=3.0;
int windowWidth, zeros;
int bigWindowWidth = 30;
VimosFloatArray *searchSpectrum;
double *coeffs = NULL;
double datVal;
double xOutF;
double frac;
double fitVariance;
VimosDpoint *buffer = NULL;
VimosDistModel1D *tunedModel;
VimosExtractionSlit *slit;
VimosFloatArray *spectrum;
VimosFloatArray *tmpSpectrum;
/*** VimosFloatArray *offsetArray; ***/
/*** VimosDistModel2D *optModX, *optModY; ***/
VimosColumn *wLen;
char comment[80];
if (NULL == (searchSpectrum = newFloatArray(bigWindowWidth + 1))) {
return EXIT_FAILURE;
}
cpl_msg_info (modName, "Finding Inverse Dispersion relation Matrix");
/*
* Note: all code related to offsets of the Y coordinate returned
* from model are commented with ***'s before and after, to be
* easily restored. There is no reason to use offsets, as they
* are not saved to header, and the central wavelength has nothing
* special with respect to any other wavelength.
*/
imageXlen = inputImage->xlen;
imageYlen = inputImage->ylen;
slit = extractionTable->slits;
readIntDescriptor(extractionTable->descs,
pilTrnGetKeyword("DispersionOrd"), &disOrder, comment);
readIntDescriptor(extractionTable->descs,
pilTrnGetKeyword("NumPixBelow"), &nPixBelow, comment);
readIntDescriptor(extractionTable->descs,
pilTrnGetKeyword("NumPixAbove"), &nPixAbove, comment);
readFloatDescriptor(extractionTable->descs,
pilTrnGetKeyword("WlenCen"), &lambdaCen, comment);
readFloatDescriptor(extractionTable->descs,
pilTrnGetKeyword("OptDistY", 0, 1), &mm2pix, comment);
readFloatDescriptor(extractionTable->descs,
pilTrnGetKeyword("Dispersion", 1, 0, 0), &lambda2pix, comment);
numPoints = nPixBelow+nPixAbove+1;
spectrum = newFloatArray(numPoints);
tmpSpectrum = newFloatArray(numPoints);
numLines = lineCat->cols->len;
wLen = findColInTab(lineCat, "WLEN");
buffer = newDpoint(numLines);
/* get the number of spectra rows in this Extraction Table */
totNumRows = numRowsInExtSlits(slit);
/* create buffer to hold offset for all rows and all skylines */
/*** offsetArray = newFloatArray(totNumRows); ***/
numLinesDone = 0;
totInvalidFit = 0;
while (slit) {
/* ALEX: when IFU, do nothing if dead fiber */
if (slit->IFUfibTrans != -1.)
{
numRows = slit->numRows;
pixWidth = mm2pix * slit->width + widthBuffer;
lambdaWidth = pixWidth / lambda2pix;
if (arcWidth < 0) windowWidth = 3*pixWidth;
else windowWidth = arcWidth;
/*** Begin duplicated part ***/
i = numRows/2;
if (refineIDS)
{
/*
* Extract spectrum from central row (far from possible
* contaminations)
* for "tuning" the first guess.
*/
slit->invDisQuality->data[i] = 1;
/* extract spectrum for this row */
for (j = -nPixBelow; j <= nPixAbove; j++) {
/* compute Y-CCD-pixel of spectrum */
yOut = slit->ccdY->data[i] + j;
/* compute X-pixel of spectrum */
xOutF = slit->ccdX->data[i] + computeDistModel1D(slit->crvPol[i],
yOut);
xOut = xOutF; /* Make it integer (truncation) */
if (xOut >= 0 && xOut+1 < imageXlen) {
if (yOut >= 0 && yOut < imageYlen) {
/* simple linear interpolation */
frac = xOutF-xOut;
datVal= ( (1.0-frac)*inputImage->data[xOut + yOut*imageXlen] +
frac*inputImage->data[xOut+1+yOut*imageXlen] );
}
else {
/*
* The spectrum is dispersed beyond the CCD frame.
* Fill with zeroes...
*/
datVal = 0.;
}
/* store in buffer */
spectrum->data[nPixBelow+j] = datVal;
}
else {
/*
* Mark as invalid the part of the slit extending beyond the
* CCD frame.
*/
slit->invDisQuality->data[i] = 0;
break;
}
}
/*
* NEW: pre-tuning of first guess. (C.Izzo)
*/
if (slit->invDisQuality->data[i]) {
tunedModel = findMaxMatchIndex(slit->invDis[i], lineCat,
lambdaWidth, spectrum, nPixBelow);
}
else {
tunedModel = newDistModel1D(slit->invDis[i]->order);
tunedModel->offset = slit->invDis[i]->offset;
for(j=0; j<=slit->invDis[i]->order; j++)
tunedModel->coefs[j] = slit->invDis[i]->coefs[j];
}
}
/*** End of duplicated part ***/
else {
tunedModel = newDistModel1D(slit->invDis[i]->order);
tunedModel->offset = slit->invDis[i]->offset;
for(j=0; j<=slit->invDis[i]->order; j++)
tunedModel->coefs[j] = slit->invDis[i]->coefs[j];
}
invalidFit = 0;
slitCount++;
for (i = 0; i < numRows; i++)
{
/* TBD: checks on convergence!!! */
/* extract spectrum for this row */
for (j = -nPixBelow; j <= nPixAbove; j++) {
/* compute Y-CCD-pixel of spectrum */
yOut = slit->ccdY->data[i] + j;
/* compute X-pixel of spectrum */
xOutF = slit->ccdX->data[i] + computeDistModel1D(slit->crvPol[i],
yOut);
xOut = xOutF; /* Make it integer (truncation) */
if (xOut >= 0 && xOut+1 < imageXlen) {
if (yOut >= 0 && yOut < imageYlen) {
/* simple linear interpolation */
frac = xOutF-xOut;
datVal= ( (1.0-frac)*inputImage->data[xOut + yOut*imageXlen] +
frac*inputImage->data[xOut+1+yOut*imageXlen] );
}
else {
/*
* Fill with zeroes parts of the spectrum dispersed beyond
* the CCD frame.
*/
datVal = 0.;
}
/* store in buffer */
spectrum->data[nPixBelow+j] = datVal;
}
else {
/*
* Mark as invalid the part of the slit extending beyond the
* CCD frame.
*/
slit->invDisQuality->data[i] = 0;
break;
}
}
/*
* Go immediately to next slit row if current row is outside CCD
*/
if (slit->invDisQuality->data[i] == 0) continue;
/*
* Loop over lines in Line Catalog
*/
foundLines = 0;
for (j = 0 ; j < numLines; j++) {
/*
* Compute expected offset from slit position of location of
* arc line j
*/
yExpectFloat = computeDistModel1D(tunedModel,
wLen->colValue->fArray[j]);
yExpect = yExpectFloat;
if (refineIDS) {
/*
* Check whether yExpect and the search interval are included
* in the extracted spectral range: if not, skip current line
*/
if ((yExpect+nPixBelow-bigWindowWidth/2 < 0) ||
(yExpect+nPixBelow+bigWindowWidth/2 > numPoints)) continue;
/*
* Extract a wide portion of spectrum around the expected
* position, were to look for the closest peak.
*/
for (k = 0; k <= bigWindowWidth; k++) {
searchSpectrum->data[k] =
log10(MAX(spectrum->data[yExpect+nPixBelow+1-
bigWindowWidth/2+k], 1.));
}
/*
* Upgrade the expected position
*/
yExpect += findClosestPeak(searchSpectrum->data, bigWindowWidth)
- bigWindowWidth/2;
}
/*
* Extract a smaller window, centered on this raw position
* of the closest peak, and find peak's accurate position.
*/
if ((yExpect+nPixBelow-windowWidth/2 < 0) ||
(yExpect+nPixBelow+windowWidth/2 > numPoints)) continue;
for (k = 0; k <= windowWidth; k++) {
tmpSpectrum->data[k] =
spectrum->data[yExpect+nPixBelow+1-windowWidth/2 + k];
}
/*
* Added to check that we are not close to the edge of a
* truncated spectrum
*/
zeros = 0;
for (k = 0; k <= windowWidth; k++)
if (fabs(tmpSpectrum->data[k]) < 0.000000001)
zeros++;
if (zeros > 0)
continue; /* Line not found */
if (VM_TRUE == findPeak1D(tmpSpectrum->data, windowWidth+1,
&pos, 2)) {
pos += yExpect-windowWidth/2;
}
else {
continue; /* Line not found */
}
/*
* Add position of arc line in buffer
*/
buffer[foundLines].x = wLen->colValue->fArray[j] - lambdaCen;
buffer[foundLines].y = pos;
foundLines++;
}
/*
* Free old array of coefficients, if exists
*/
if (coeffs != NULL) {
cpl_free(coeffs);
coeffs = NULL;
}
/*
* Fit new inverse dispersion relation
*/
do {
tolMax = 0;
validFit = 1;
coeffs=fit1DPoly(slit->invDis[i]->order,buffer,foundLines,
&fitVariance);
/* printf("%d %d %d %f \n", slit->slitNo, i, foundLines,
sqrt(rmsError));*/
if (coeffs == NULL) {
/*
cpl_msg_warning(modName, "One invalid fit");
*/
slit->invDisQuality->data[i] = validFit = 0;
if (foundLines >= 2*slit->invDis[i]->order) {
invalidFit++;
}
break;
}
/*
* Copy coefficients in inverse dispersion relation for this row
*/
for (k = 0; k <= slit->invDis[i]->order; k++) {
slit->invDis[i]->coefs[k] = coeffs[k];
}
slit->invDisRms->data[i] = sqrt(fitVariance);
slit->invDis[i]->offset = 0.0;
/* cull bad lines */
for (k = 0; k < foundLines; k++) {
yExpectFloat = computeDistModel1D(slit->invDis[i], buffer[k].x);
yExpect = yExpectFloat;
if( fabs(yExpectFloat-buffer[k].y) > nSigma*sqrt(fitVariance) ){
tolMax = 1;
if (k != foundLines-1) {
for (j = k; j < foundLines-1; j++) {
buffer[j].x = buffer[j+1].x;
buffer[j].y = buffer[j+1].y;
}
k--;
}
foundLines--;
}
}
/* until all lines are ok */
} while ( (foundLines > slit->invDis[i]->order+2) && (tolMax > 0) );
if (foundLines < 2*slit->invDis[i]->order) {
/*
cpl_msg_warning(modName,
"Too few lines for a valid fit: fit rejected!");
*/
slit->invDisQuality->data[i] = validFit = 0;
invalidFit++;
}
/* store wavelength shift on CCD */
slit->invDis[i]->offset = lambdaCen;
if (validFit) {
/*** offsetArray->data[numLinesDone] =
computeDistModel1D(slit->invDis[i], lambdaCen); ***/
numLinesDone++;
}
}
if (invalidFit) {
totInvalidFit += invalidFit;
cpl_msg_warning(modName, "Slit %d: %d of %d rows IDS fit failure.",
slitCount, invalidFit, numRows);
}
if (refineIDS)
deleteDistModel1D(tunedModel); /*** Added ***/
} /* ALEX: end if dead fiber */
slit = slit->next;
}
if (totInvalidFit == totNumRows) {
cpl_msg_error(modName, "The IDS fit failed in all slit rows!");
return EXIT_FAILURE;
}
else {
if (totInvalidFit) {
cpl_msg_warning(modName, "All slits: %d of %d rows IDS fit failure.",
totInvalidFit, totNumRows);
}
}
/* determine median offset for CCD */
/*** offset = medianWirth(offsetArray->data, numLinesDone); ***/
/* Test: remove the offset!!! (C.Izzo) */
/*** offset = 0.; ***/
/* get parameters of Optical Distortion Model from Extraction Table */
/*** readOptDistModel(extractionTable->descs, &optModX, &optModY); ***/
/* add offset */
/*** optModY->coefs[0][0] += offset; ***/
/* and write coefficients back to Table */
/*** writeOptDistModel(&(extractionTable->descs), optModX, optModY); ***/
/* loop over slits to update slit positions */
/*** slit = extractionTable->slits; ***/
/*** while (slit) {
* ALEX: the update of crvPol and invDis is done ALSO for dead fibers *
* (no IF on IFUfibTrans) as in VmSpCalShifts *
numRows = slit->numRows; ***/
/* loop over all rows of a slit */
/*** for (i = 0; i < numRows; i++) { ***/
/* add offset to slit position */
/*** slit->ccdY->data[i] += offset;
slit->crvPol[i]->offset += offset;
slit->invDis[i]->coefs[0] -= offset;
}
slit = slit->next;
}
deleteFloatArray(searchSpectrum);
writeIntDescriptor(&(extractionTable->descs),
pilTrnGetKeyword("NumPixBelow"), nPixBelow + offset, "");
writeIntDescriptor(&(extractionTable->descs),
pilTrnGetKeyword("NumPixAbove"), nPixAbove - offset, "");
***/
return EXIT_SUCCESS;
}
/**
* @memo
* Fit an Inverse Dispersion Relation Model.
*
* @return EXIT_SUCCESS / EXIT_FAILURE
*
* @param inputImage Arc Lamp exposure
* @param extractionTable Extraction Table
* @param lineCat Line Catalog
* @param arcWidth Window used for determining the peak of a
* centered arc line (in CCD pixels).
* @param refineIDS flag to signal the need to refine the first guess
* IDS from the Extraction Table
*
* @doc
* Identify lines in Arc Spectrum, fit dispersion relation for
* every row in te Extraction Table. Calibrate X positioning of slit
*
* @author C. Izzo
*/
int VmSpDerDisp(VimosImage *inputImage, VimosExtractionTable *extractionTable,
VimosTable *lineCat, int arcWidth, float level)
{
const char modName[] = "VmSpDerDisp";
int i, j, k;
int xOut, yOut;
int numRows, totNumRows;
int numPoints;
int foundLines;
int nPixBelow, nPixAbove;
int imageXlen, imageYlen;
int numLines;
int disOrder;
int widthBuffer = 0;
int validFit, invalidFit, totInvalidFit;
int slitCount = 0;
float lambdaCen, lambdaChecklo, lambdaCheckhi;
float lambda2pix;
float mm2pix;
float pixWidth;
/* float lambdaWidth; */
float pixelCen, pixelLo, pixelHi;
float *check[3];
/* int windowWidth; */
double *coeffs = NULL;
double datVal;
double xOutF;
double frac;
double fitVariance;
int npeaks;
double *peaks;
double *lines;
double **output;
double min_disp;
double max_disp;
double min, max, span;
double tolerance = 0.05;
VimosDpoint *buffer = NULL;
VimosExtractionSlit *slit;
VimosFloatArray *spectrum;
VimosColumn *wLen;
char comment[80];
cpl_msg_info (modName, "Finding Inverse Dispersion relation Matrix");
/*
* Note: all code related to offsets of the Y coordinate returned
* from model are commented with ***'s before and after, to be
* easily restored. There is no reason to use offsets, as they
* are not saved to header, and the central wavelength has nothing
* special with respect to any other wavelength.
*/
imageXlen = inputImage->xlen;
imageYlen = inputImage->ylen;
slit = extractionTable->slits;
readIntDescriptor(extractionTable->descs,
pilTrnGetKeyword("DispersionOrd"), &disOrder, comment);
readIntDescriptor(extractionTable->descs,
pilTrnGetKeyword("NumPixBelow"), &nPixBelow, comment);
readIntDescriptor(extractionTable->descs,
pilTrnGetKeyword("NumPixAbove"), &nPixAbove, comment);
readFloatDescriptor(extractionTable->descs,
pilTrnGetKeyword("WlenCen"), &lambdaCen, comment);
readFloatDescriptor(extractionTable->descs,
pilTrnGetKeyword("OptDistY", 0, 1), &mm2pix, comment);
readFloatDescriptor(extractionTable->descs,
pilTrnGetKeyword("Dispersion", 1, 0, 0), &lambda2pix, comment);
max_disp = min_disp = 1 / lambda2pix;
max_disp += max_disp / 5.5;
min_disp -= min_disp / 5.5;
numPoints = nPixBelow+nPixAbove+1;
spectrum = newFloatArray(numPoints);
numLines = lineCat->cols->len;
wLen = findColInTab(lineCat, "WLEN");
lines = cpl_malloc(numLines * sizeof(double));
for (j = 0; j < numLines; j++)
lines[j] = wLen->colValue->fArray[j];
buffer = newDpoint(numLines);
/* get the number of spectra rows in this Extraction Table */
totNumRows = numRowsInExtSlits(slit);
totInvalidFit = 0;
while (slit) {
numRows = slit->numRows;
pixWidth = mm2pix * slit->width + widthBuffer;
/* lambdaWidth = pixWidth / lambda2pix;
if (arcWidth < 0) windowWidth = 3*pixWidth;
else windowWidth = arcWidth; */
min = max = slit->ccdY->data[0];
for (i = 1; i < numRows; i++) {
if (min > slit->ccdY->data[i])
min = slit->ccdY->data[i];
if (max < slit->ccdY->data[i])
max = slit->ccdY->data[i];
}
span = (max - min) * mm2pix + 3;
invalidFit = 0;
slitCount++;
for (i = 0; i < numRows; i++)
{
slit->invDisQuality->data[i] = 1;
/* extract spectrum for this row */
for (j = -nPixBelow; j <= nPixAbove; j++) {
/* compute Y-CCD-pixel of spectrum */
yOut = slit->ccdY->data[i] + j;
/* compute X-pixel of spectrum */
xOutF = slit->ccdX->data[i] + computeDistModel1D(slit->crvPol[i],
yOut);
xOut = xOutF; /* Make it integer (truncation) */
if (xOut >= 0 && xOut+1 < imageXlen) {
if (yOut >= 0 && yOut < imageYlen) {
/* simple linear interpolation */
frac = xOutF-xOut;
datVal= ( (1.0-frac)*inputImage->data[xOut + yOut*imageXlen] +
frac*inputImage->data[xOut+1+yOut*imageXlen] );
}
else {
/*
* Fill with zeroes parts of the spectrum dispersed beyond
* the CCD frame.
*/
datVal = 0.;
}
/* store in buffer */
spectrum->data[nPixBelow+j] = datVal;
}
else {
/*
* Mark as invalid the part of the slit extending beyond the
* CCD frame.
*/
slit->invDisQuality->data[i] = 0;
break;
}
}
/*
* Go immediately to next slit row if current row is outside CCD
*/
if (slit->invDisQuality->data[i] == 0) continue;
peaks = collectPeaks(spectrum->data, numPoints,
level, pixWidth, &npeaks);
if (peaks) {
output = identPeaks(peaks, npeaks, lines, numLines,
min_disp, max_disp, tolerance, &foundLines);
if (output) {
for (j = 0; j < foundLines; j++) {
buffer[j].x = output[1][j] - lambdaCen;
buffer[j].y = output[0][j] - nPixBelow - 1;
}
cpl_free(output[0]);
cpl_free(output[1]);
cpl_free(output);
}
cpl_free(peaks);
}
else
foundLines = 0;
validFit = 0;
if (foundLines >= 1.5*slit->invDis[i]->order) {
/*
* Free old array of coefficients, if exists
*/
if (coeffs != NULL) {
cpl_free(coeffs);
coeffs = NULL;
}
/*
* Fit new inverse dispersion relation
*/
coeffs = fit1DPoly(slit->invDis[i]->order, buffer, foundLines,
&fitVariance);
if (coeffs != NULL && fitVariance < 1.0) {
/*
* Copy coefficients of dispersion relation for this row
*/
for (k = 0; k <= slit->invDis[i]->order; k++)
slit->invDis[i]->coefs[k] = coeffs[k];
slit->invDisRms->data[i] = sqrt(fitVariance);
validFit = 1;
}
}
if (!validFit) {
slit->invDisQuality->data[i] = 0;
invalidFit++;
}
/* store wavelength shift on CCD */
slit->invDis[i]->offset = lambdaCen;
}
/*
* Check if all fits are belonging to the same slit (it may not
* be the case, due to misalignments).
*/
check[0] = cpl_malloc(numRows * sizeof(float));
check[1] = cpl_malloc(numRows * sizeof(float));
check[2] = cpl_malloc(numRows * sizeof(float));
lambdaChecklo = lambdaCen - (nPixBelow / lambda2pix) / 2;
lambdaCheckhi = lambdaCen + (nPixAbove / lambda2pix) / 2;
for (j = 0, k = 0; k < numRows; k++) {
if (slit->invDisQuality->data[k] != 0) {
check[0][j] = computeDistModel1D(slit->invDis[k], lambdaChecklo);
check[1][j] = computeDistModel1D(slit->invDis[k], lambdaCen);
check[2][j] = computeDistModel1D(slit->invDis[k], lambdaCheckhi);
++j;
}
}
if (j > 0) {
pixelLo = medianPixelvalue(check[0], j);
pixelCen = medianPixelvalue(check[1], j);
pixelHi = medianPixelvalue(check[2], j);
if (fabs(pixelCen) > 30) {
for (k = 0; k < numRows; k++) {
if (slit->invDisQuality->data[k] != 0) {
slit->invDisQuality->data[k] = 0;
++invalidFit;
}
}
}
for (j = 0, k = 0; k < numRows; k++) {
if (slit->invDisQuality->data[k] != 0) {
if (fabs(check[0][j] - pixelLo) > span
|| fabs(check[1][j] - pixelCen) > span
|| fabs(check[2][j] - pixelHi) > span) {
slit->invDisQuality->data[k] = 0;
++invalidFit;
}
++j;
}
}
}
cpl_free(check[0]);
cpl_free(check[1]);
cpl_free(check[2]);
if (invalidFit) {
totInvalidFit += invalidFit;
cpl_msg_warning(modName, "Slit %d: %d of %d rows IDS fit failure.",
slitCount, invalidFit, numRows);
}
slit = slit->next;
}
deleteDpoint(buffer);
deleteFloatArray(spectrum);
cpl_free(lines);
if (totInvalidFit == totNumRows) {
cpl_msg_error(modName, "The IDS fit failed in all slit rows!");
return EXIT_FAILURE;
}
else {
if (totInvalidFit) {
cpl_msg_warning(modName, "All slits: %d of %d rows IDS fit failure.",
totInvalidFit, totNumRows);
}
}
return EXIT_SUCCESS;
}
/**
* @memo
* Fit a Inverse Dispersion Relation to wavelength calibrations
* obtained for each row of each slit spectrum.
*
* @return EXIT_SUCCESS / EXIT_FAILURE
*
* @param extractionTable Input Extraction Table
* @param grismTable Input (and perhaps output) Grism Table
* @param grismFlag Flag to indicate whether to update or not
* the Grism Table with the new Curvature Model
*
* @doc
* Just fit a polynomial in two variables to the coefficients
* of the polynomials fitting the wavelength/pixel relations
* for each spectra found in an Arc Lamp Exposure.
*
* @author M. Scodeggio
*/
int VmSpDispMatrix(VimosExtractionTable *extractionTable,
VimosTable *grismTable, int grismFlag)
{
int i, j;
int numSlits;
int slitDone;
int polOrder, xOrder, yOrder;
int numRows, numGoodRows;
double rmsFit;
double minSlity, maxSlity;
double *coeff;
double *c = NULL;
double medianCoeff;
int xord = 2;
VimosExtractionSlit *slit;
VimosPixel *coefArray;
VimosDpoint *list;
VimosDistModelFull *idsMat;
char comment[80];
numSlits = 0;
slit = extractionTable->slits;
while (slit) {
numSlits++;
slit = slit->next;
}
coefArray = newPixel(2*numSlits);
list = newDpoint(2*numSlits);
readIntDescriptor(extractionTable->descs, pilTrnGetKeyword("DispersionOrd"),
&polOrder, comment);
readIntDescriptor(extractionTable->descs, pilTrnGetKeyword("DispersionOrdX"),
&xOrder, comment);
readIntDescriptor(extractionTable->descs, pilTrnGetKeyword("DispersionOrdY"),
&yOrder, comment);
/* note that for the moment we keep the order in X equal to the one in Y!! */
idsMat = newDistModelFull(polOrder, xOrder, xOrder);
slit = extractionTable->slits;
minSlity = maxSlity = slit->maskY->data[0];
while (slit) {
if (slit->maskY->data[0] > maxSlity)
maxSlity = slit->maskY->data[0];
if (slit->maskY->data[0] < minSlity)
minSlity = slit->maskY->data[0];
slit = slit->next;
}
for (i = 0; i <= polOrder; i++) {
slit = extractionTable->slits;
slitDone = 0;
while (slit) {
numRows = slit->numRows;
coeff = (double *) cpl_malloc(numRows*sizeof(double));
/*
* Skip columns where the solution is not available
*/
for (numGoodRows = 0, j = 0; j < numRows; j++) {
if (slit->invDisQuality->data[j] != 0) {
coeff[numGoodRows] = slit->invDis[j]->coefs[i];
numGoodRows++;
}
}
if (numGoodRows) {
medianCoeff = medianDouble(coeff, numGoodRows);
if (maxSlity - minSlity > 1.0) {
coefArray[slitDone].x = slit->maskX->data[numRows/2];
coefArray[slitDone].y = slit->maskY->data[numRows/2];
coefArray[slitDone].i = medianCoeff;
}
else {
list[slitDone].x = slit->maskX->data[numRows/2];
list[slitDone].y = medianCoeff;
}
slitDone++;
cpl_free(coeff);
}
slit = slit->next;
}
if (maxSlity - minSlity > 1.0) {
/* ugly!!!! */
deleteDistModel2D(idsMat->coefs[i]);
/*
* Note: the offsets are always set to zero.
*/
if (fitDistModel2D(coefArray, slitDone, xOrder, 0.0, 0.0,
&(idsMat->coefs[i]), &rmsFit) == VM_FALSE)
return EXIT_FAILURE;
}
else {
c = fit1DPoly(xord, list, slitDone, NULL);
if (c) {
for (j = 0; j <= xord; j++)
idsMat->coefs[i]->coefs[j][0] = c[j];
free(c);
c = NULL;
}
else {
deleteDpoint(list);
deletePixel(coefArray);
deleteDistModelFull(idsMat);
return EXIT_FAILURE;
}
}
}
writeInvDispMatrix(&(extractionTable->descs), idsMat);
if (grismFlag)
writeInvDispMatrix(&(grismTable->descs), idsMat);
deleteDpoint(list);
deletePixel(coefArray);
deleteDistModelFull(idsMat);
return EXIT_SUCCESS;
}
int VmSpCalShifts(VimosImage *inputImage, VimosTable *grismTable,
VimosExtractionTable *extractionTable, int grismFlag,
int lineWidth, int fuzz)
{
int i, j, k;
int jMin, jMax;
int xOut, yOut;
int numRows;
int numPoints;
int numSlits;
int bigWindowWidth = 30;
int windowWidth = 20;
VimosUlong32 index;
int nPixBelow, nPixAbove;
int imageXlen, imageYlen;
int numLinesDone;
int numSkyLines;
int yExpect;
int outOfImage = 0;
float pos;
float offSet;
float yExpectFloat;
float xStart, xEnd;
VimosFloatArray *searchSpectrum;
double upVal, loVal;
double datVal;
double xOutF;
double frac;
VimosExtractionSlit *slit;
VimosFloatArray *spectrum;
VimosFloatArray *tmpSpectrum;
VimosFloatArray *skyLines;
VimosFloatArray *offsetArray;
VimosFloatArray *offsetYArray;
VimosFloatArray *tmpArray;
VimosDistModel2D *optModX, *optModY;
char modName[] = "VmSpCalShifts";
/*ALEX */
char insMode[80];
cpl_msg_debug(modName,"Calibrating shifts");
if (NULL == (searchSpectrum = newFloatArray(bigWindowWidth + 1))) {
return EXIT_FAILURE;
}
imageXlen = inputImage->xlen;
imageYlen = inputImage->ylen;
slit = extractionTable->slits;
if (lineWidth > 0) windowWidth = lineWidth;
readIntDescriptor(extractionTable->descs, "ESO PRO SPECT LLEN LO",
&nPixBelow, NULL);
readIntDescriptor(extractionTable->descs, "ESO PRO SPECT LLEN HI",
&nPixAbove, NULL);
readSkyLines(extractionTable->descs, &numSkyLines, &skyLines);
/* length in pixels of an extracted spetral row */
numPoints = nPixBelow+nPixAbove+1;
/*ALEX: determine numSlit depending on MOS or IFU: if IFU, numSlit equal to
number of good fibers (to prevent zeros in medianWirth on offsetYArray */
readStringDescriptor(inputImage->descs, pilTrnGetKeyword("InstrumentMode"),
insMode, NULL);
if (!strncmp(insMode,"MOS",3))
{
/* get the number of slits in this Extraction Table */
numSlits = numSlitsInExtTable(extractionTable);
}
else if (!strncmp(insMode,"IFU",3))
{
numSlits = 0;
while (slit) {
if ( (slit->IFUfibTrans) >= 0.0)
{
numSlits++;
}
slit = slit->next;
}
}
else
{
cpl_msg_error(modName,"Unable to determine Instrument Mode");
return EXIT_FAILURE;
}
/* ALEX end */
/* create buffers to hold extracted spectral row */
spectrum = newFloatArray(numPoints);
tmpSpectrum = newFloatArray(numPoints);
offsetYArray = newFloatArray(numSlits);
/* ALEX: restart */
slit = extractionTable->slits;
/* loop over all slits: determine offset in Y0 */
while (slit) {
/* ALEX: when IFU, do the following except for dead fibers */
if ( (slit->IFUfibTrans) >= 0.0)
{
/* get number of rows for this slit */
numRows = slit->numRows;
/* create buffer to hold offset for all rows and all skylines */
offsetArray = newFloatArray(numRows*numSkyLines);
/* done nothing sofar */
numLinesDone = 0;
/* loop over all rows of this slit */
for (i = 0; i < numRows; i++) {
/* check that this row has a wavelength solution */
if (slit->invDisQuality->data[i] == 0)
continue;
/* extract spectrum for this row */
for (j = -nPixBelow; j <= nPixAbove; j++) {
/* compute Y-pixel of spectrum */
yOut = slit->ccdY->data[i] + j;
/* compute X-pixel of spectrum */
xOutF = slit->ccdX->data[i]+computeDistModel1D(slit->crvPol[i],yOut);
xOut = xOutF;
if (yOut >= 0 && yOut < imageYlen
&& xOut > 1 && xOut < imageXlen - 1) {
/* simple linear interpolation */
frac = xOutF-xOut;
datVal = ( (1.0-frac)*inputImage->data[xOut + yOut*imageXlen] +
frac*inputImage->data[xOut+1+yOut*imageXlen] );
}
else {
/*
* The spectrum is dispersed beyond the CCD frame.
* Fill with zeroes...
*/
datVal = 0.;
}
/* store in buffer */
spectrum->data[nPixBelow+j] = datVal;
}
/* loop over skylines */
for (j = 0 ; j < numSkyLines; j++) {
/* compute expected offset from slit position of location of sky */
/* line j */
yExpectFloat = computeDistModel1D(slit->invDis[i], skyLines->data[j]);
yExpect = yExpectFloat;
/*
* Check whether yExpect and the search interval are included
* in the extracted spectral range: if not, skip current line
*/
if ((yExpect+nPixBelow-windowWidth/2 < 0) ||
(yExpect+nPixBelow+windowWidth/2 > numPoints)) continue;
/*
* Extract a window, centered on this raw position
* of the closest peak, and find peak's accurate position.
*/
for (k = 0; k <= windowWidth; k++) {
tmpSpectrum->data[k] =
spectrum->data[yExpect+nPixBelow+1-windowWidth/2 + k];
}
if(VM_TRUE == findPeak1D(tmpSpectrum->data,windowWidth+1,&pos,2)) {
pos += yExpect-windowWidth/2;
}
else {
continue; /* Line not found */
}
/* add position of sky line in buffer */
offsetArray->data[numLinesDone] = pos-yExpectFloat;
numLinesDone++;
}
}
/* determine median offset in Y for Slit */
offSet = medianWirth(offsetArray->data, numLinesDone);
/* loop over slit to update model positions */
/* ALEX: this updating is done for good fibers only */
for (i = 0; i < numRows; i++) {
slit->ccdY->data[i] += offSet;
slit->crvPol[i]->offset += offSet;
}
offsetYArray->data[slit->slitNo - 1] = offSet;
} /* ALEX: end if is a good fiber */
/* ALEX: if is a dead fiber set offset to 0 */
else if ( (slit->IFUfibTrans) < 0.0)
{
offSet = 0.;
}
/* process next slit */
slit = slit->next;
}
offSet = medianWirth(offsetYArray->data, numSlits);
deleteFloatArray(offsetYArray);
/* get parameters of Optical Distortion Model from Extraction Table */
readOptDistModel(extractionTable->descs, &optModX, &optModY);
/* add offset */
optModY->coefs[0][0] += offSet;
writeIntDescriptor(&(extractionTable->descs), "ESO PRO SPECT LLEN LO",
nPixBelow + offSet, "");
writeIntDescriptor(&(extractionTable->descs), "ESO PRO SPECT LLEN HI",
nPixAbove - offSet, "");
/* now find offset in X */
/* create buffer to hold offset for all slits and all skylines */
deleteFloatArray(offsetArray);
offsetArray = newFloatArray(numSlits*2*numSkyLines);
/* reset counter */
numLinesDone = 0;
/* first slit in table */
slit = extractionTable->slits;
/* loop over all slits */
while (slit) {
/* spatial length of slit */
numRows = slit->numRows;
jMin = 0;
jMax = numRows-1;
while ((slit->invDisQuality->data[jMin] == 0) && jMin < (numRows-1))
jMin++;
while ((slit->invDisQuality->data[jMax] == 0) && jMax > 0)
jMax--;
/* create temp buffer */
tmpArray = newFloatArray(numRows + 2*fuzz);
/* ALEX: when IFU, do the following except for dead fibers */
if ( (slit->IFUfibTrans) >= 0.0)
{
/* loop over 'wavelength' */
for (j = 0; j < numSkyLines; j++) {
numPoints = 0;
/* extract a cut across the slit, with a bit of extra space */
for (i = -fuzz; i < numRows+fuzz; i++) {
if (i < 0)
{
k = 0;
yOut = slit->ccdY->data[k] + j;
xOutF = slit->ccdX->data[k] +
computeDistModel1D(slit->crvPol[k], yOut) + i;
}
else if (i >= numRows)
{
k = numRows - 1;
yOut = slit->ccdY->data[k] + j;
xOutF = slit->ccdX->data[k] +
computeDistModel1D(slit->crvPol[k], yOut) + i - (numRows-1);
}
else
{
k = i;
yOut = slit->ccdY->data[k] + j;
xOutF = slit->ccdX->data[k] +
computeDistModel1D(slit->crvPol[k], yOut);
}
/* use curvature polynomial of edge to tracte these data */
xOut = xOutF;
if(yOut < 0 || yOut >=imageYlen || xOut < 0 || xOut >= imageXlen) {
outOfImage = 1;
continue;
}
outOfImage = 0;
numPoints++;
/* quick interpolation of data */
frac = xOutF-xOut;
index = xOut+yOut*imageXlen;
datVal = ( (1.0-frac)*inputImage->data[index] +
frac*inputImage->data[index+1] );
/* and store in buffer */
tmpArray->data[i+fuzz] = datVal;
if (i == 0)
xStart = slit->ccdX->data[0] +
computeDistModel1D(slit->crvPol[0],yOut);
if (i == numRows-1)
xEnd = slit->ccdX->data[numRows-1] +
computeDistModel1D(slit->crvPol[numRows-1],yOut);
}
if (numPoints < numRows) {
continue;
}
else {
findSpectrumBorders(tmpArray, &upVal, &loVal, fuzz);
/* add position of sky line in buffer */
if (upVal > 0.0 && loVal > 0.0) {
offsetArray->data[numLinesDone] = loVal - fuzz;
numLinesDone++;
offsetArray->data[numLinesDone] = upVal - fuzz - numRows;
numLinesDone++;
}
}
}
deleteFloatArray(tmpArray);
} /* ALEX: end if on dead fibers */
slit = slit->next;
}
/* determine median offset in X for CCD */
offSet = medianWirth(offsetArray->data, numLinesDone);
/* add offset */
optModX->coefs[0][0] += offSet;
/* and write coefficients back to Table */
writeOptDistModel(&(extractionTable->descs), optModX, optModY);
/* loop over slits to update slit positions */
/* ALEX: this updating is done for good fibers only */
slit = extractionTable->slits;
while (slit) {
if ( (slit->IFUfibTrans) >= 0.0)
{
numRows = slit->numRows;
/* loop over all rows of a slit */
for (i = 0; i < numRows; i++) {
/* add offset to slit position */
slit->ccdX->data[i] += offSet;
}
}
slit = slit->next;
}
if (grismFlag) {
writeOptDistModel(&(grismTable->descs), optModX, optModY);
}
deleteFloatArray(spectrum);
/* deleteFloatArray(tmpSpectrum);*/
deleteFloatArray(offsetArray);
deleteFloatArray(skyLines);
deleteDistModel2D(optModX);
deleteDistModel2D(optModY);
return EXIT_SUCCESS;
}
/**
* @memo
* Build the list of wavelength intervals where the spectrum to be
* calibrated will be integrated.
*
* @return List of wavelength intervals.
*
* @param lineCat Line catalogue.
* @param width Slit width (in the same wavelength units used in
* line catalog).
*
* @doc
* The wavelength intervals where a spectrum will be integrated
* depend on the slit width and on the wavelength of the lines
* listed in the catalogue. When intervals centered on different
* lines overlap, they are merged into a single interval. The
* lines in catalog must be listed with increasing wavelength.
*
* @author C.Izzo
*/
VimosDpoint *getWavIntervals(VimosTable *lineCat, float width)
{
const char modName[] = "getWavIntervals";
VimosColumn *wLen = findColInTab(lineCat, "WLEN");
VimosDpoint *wavIntervals = NULL;
VimosDpoint *interval;
double *start;
double *end;
int numLines;
int numIntervals = 0;
int i = 0;
if (wLen) {
numLines = lineCat->cols->len;
start = (double *) cpl_malloc(numLines*sizeof(double));
end = (double *) cpl_malloc(numLines*sizeof(double));
/*
* First interval
*/
start[0] = wLen->colValue->fArray[i] - width/2;
end[0] = wLen->colValue->fArray[i] + width/2;
/*
* Note: current interval just get longer if next interval
* begins inside it.
*/
for (i=1; i<numLines; i++) {
if ((wLen->colValue->fArray[i] - wLen->colValue->fArray[i-1]) > width) {
numIntervals++;
start[numIntervals] = wLen->colValue->fArray[i] - width/2;
}
end[numIntervals] = wLen->colValue->fArray[i] + width/2;
}
numIntervals++;
cpl_msg_debug(modName, "%d integration intervals found:", numIntervals);
interval = wavIntervals = newDpoint(numIntervals);
for (i=0; i<numIntervals; i++) {
interval->x = start[i];
interval->y = end[i];
cpl_msg_debug(modName, "from %f to %f", interval->x, interval->y);
interval = interval->next;
}
cpl_free(start);
cpl_free(end);
}
return(wavIntervals);
}
/**
* @memo
* Delete a list of wavelength intervals.
*
* @return nothing
*
* @param wavIntervals List of wavelength intervals.
*
* @doc
* This is just a wrapper for deleteDpoint()
*
* @author C.Izzo
*/
void forgetWavIntervals(VimosDpoint *wavIntervals)
{
deleteDpoint(wavIntervals);
}
/**
* @memo
* Compute the Match Index between a spectrum and a list
* of wavelength intervals.
*
* @return Match Index.
*
* @param lambdaToCcd Wavelength to CCD pixel conversion to be used.
* @param wavIntervals Intervals of integration.
* @param spectrum Spectrum to be matched.
* @param offset Position of central wavelength in spectrum.
*
* @doc
* The list of lambda intervals is converted into a list of
* CCD pixel intervals according to the given lambdaToCcd
* transform. Next, the integral of the input spectrum is
* computed on the given intervals: the value of this integral
* is the Match Index. It is suggested to replace the spectrum
* with its own logarithm to avoid too strong a dependency of
* the Match Index on the brightest lines (this is not done
* within this function, for obvious reasons of efficiency).
*
* @author C.Izzo
*/
double computeMatchIndex(VimosDistModel1D *lambdaToCcd,
VimosDpoint *wavIntervals, VimosFloatArray *spectrum, int offset)
{
VimosDpoint *pixIntervals;
VimosDpoint *dWav;
VimosDpoint *dPix;
double matchIndex = -1.;
int spectrumLength = spectrum->len;
int numWav = 0;
int numPix = 0;
int i, j, low, high;
/*
* Conversion of wavelength intervals into CCD pixels intervals.
*/
for (dWav=wavIntervals; dWav; dWav=dWav->next)
numWav++;
dPix = pixIntervals = newDpoint(numWav);
for (dWav=wavIntervals; dWav; dWav=dWav->next) {
dPix->x = offset + computeDistModel1D(lambdaToCcd, dWav->x); /* Start */
dPix->y = offset + computeDistModel1D(lambdaToCcd, dWav->y); /* End */
if (dPix->x < 0.) { /* Interval start falls out of spectrum... */
if (dPix->y > 0.) { /* ... but interval end is in. */
dPix->x = 0.;
dPix = dPix->next;
numPix++;
}
}
else if (dPix->x < spectrumLength) { /* Interval start is in... */
if (dPix->y > spectrumLength) { /* ... but interval end not. */
dPix->y = spectrumLength;
}
dPix = dPix->next;
numPix++;
}
}
/*
* Compute match index
*/
matchIndex = 0.;
for (i=0, dPix=pixIntervals; i<numPix; i++, dPix=dPix->next) {
low = (int) (dPix->x + 0.5); /* Nearest integer */
high = (int) (dPix->y + 1.5); /* Nearest integer + 1 */
for (j=low; j<high; j++) matchIndex += spectrum->data[j];
}
deleteDpoint(pixIntervals);
return(matchIndex);
}
/**
* @memo
* Reduce intensity differences in a spectrum.
*
* @return New spectrum.
*
* @param spectrum Spectrum to process.
*
* @doc
* Currently the "equalization" of intensities is performed
* by simply make the logarithm of the spectrum itself. Negative
* numbers are avoided.
*
* @author C.Izzo
*/
VimosFloatArray *equalizeSpectrum(VimosFloatArray *spectrum)
{
VimosFloatArray *logSpectrum;
int spectrumLength = spectrum->len;
int i;
if ((logSpectrum = newFloatArray(spectrumLength))) {
/*
* Logarithm of spectrum (avoiding negative numbers)
*/
for (i=0; i<spectrumLength; i++)
logSpectrum->data[i] = log10(MAX(spectrum->data[i], 1.));
}
return(logSpectrum);
}
/**
* @memo
* Search the maximum of the Match Index in terms of the
* lambdaToCcd transform coefficients.
*
* @return Lambda to CCD transform corresponding to the max Match
* Index found.
*
* @param lambdaToCcd First guess for the wavelength calibration
* @param lineCat Line catalog.
* @param width Slit width (in the same wavelength units used
* in line catalog).
* @param spectrum Spectrum to be matched.
* @param offset Position of central wavelength in spectrum.
*
* @doc
* The Match Index is computed for a grid of values of the lambda
* to CCD transform coefficients. Each coefficient will be varied
* on a range inversely proportional to its corresponding power
* of a reference lambda in the polynomial transform (variation
* on the CCD is depending linearly on the variations of the
* coefficients, modulated by powers of lambda). The chosen value
* for lambda is its highest possible value. The max Match Index
* for all the values in the grid is found, and the corresponding
* wavelength to CCD pixel transform is returned. The (local) minimum
* is not searched (i.e., no fit is performed): the match should be
* just enough to ensure line identification, and proceed with the
* usual peak search algorithm.
*
* @author C.Izzo
*/
VimosDistModel1D *findMaxMatchIndex(VimosDistModel1D *lambdaToCcd,
VimosTable *lineCat, float width,
VimosFloatArray *spectrum, int offset)
{
VimosFloatArray *eqSpectrum;
VimosDpoint *wavIntervals;
VimosDistModel1D *grid;
VimosDistModel1D *start;
VimosDistModel1D *best = NULL;
int nCoeff;
int *count;
double *coeffRange;
double *coeffStep;
int nStep = 50;
int pixRange = 50;
double matchIndex = 0.;
double bestMatchIndex = 0.;
int i = 0;
int j = 0;
double lambda;
if (lambdaToCcd) {
nCoeff = lambdaToCcd->order + 1;
if ((eqSpectrum = equalizeSpectrum(spectrum))) {
if ((wavIntervals = getWavIntervals(lineCat, width))) {
/*
* Get a typical value of lambda in the polynomial,
* necessary to evaluate the variation range to assign
* to each coefficient. Since in the model lambda enters
* as an offset from the central wavelength, half of the
* spectral range might be a reasonable choice (currently
* hardcoded to a reasonable value for FORS data).
*/
lambda = 2000.;
/*
* Get max variation for each polynomial coefficient.
*/
if ((coeffRange = cpl_calloc(nCoeff, sizeof(double)))) {
coeffRange[0] = pixRange;
if ((coeffStep = cpl_calloc(nCoeff, sizeof(double)))) {
coeffStep[0] = ((float) pixRange)/nStep;
for (i = 1; i < nCoeff; i++) {
coeffRange[i] = coeffRange[i-1]/lambda;
coeffStep[i] = coeffRange[i]/nStep;
}
if ((grid = newDistModel1D(lambdaToCcd->order))) {
for (i = 0; i < nCoeff; i++) {
grid->coefs[i] = lambdaToCcd->coefs[i];
}
grid->offset = lambdaToCcd->offset;
if ((start = newDistModel1D(lambdaToCcd->order))) {
for (i = 0; i < nCoeff; i++) {
start->coefs[i] = grid->coefs[i] - coeffRange[i]/2.;
}
start->offset = grid->offset;
if ((count = cpl_calloc(nCoeff, sizeof(int)))) {
for (i = 1; i < nCoeff; i++) count[i] = 1;
/*
* Find best Match Index in a n-dimensional grid
* of coefficents values.
*/
if ((best = newDistModel1D(lambdaToCcd->order))) {
for (i = 0; i < nCoeff; i++) {
best->coefs[i] = lambdaToCcd->coefs[i];
}
best->offset = lambdaToCcd->offset;
grid->coefs[0] = start->coefs[0];
grid->coefs[1] = start->coefs[1];
/*
* The navel of the function!
*/
i = 0;
while (i < 2) {
if (count[i] < nStep) {
count[i]++;
grid->coefs[i] += coeffStep[i];
i = 0;
matchIndex =
computeMatchIndex(grid, wavIntervals,
eqSpectrum, offset);
if (matchIndex > bestMatchIndex) {
bestMatchIndex = matchIndex;
for (j = 0; j < nCoeff; j++) {
best->coefs[j] = grid->coefs[j];
}
}
}
else {
count[i] = 1;
grid->coefs[i] = start->coefs[i]; /* reset */
i++;
}
}
}
cpl_free(count);
}
deleteDistModel1D(start);
}
deleteDistModel1D(grid);
}
cpl_free(coeffStep);
}
cpl_free(coeffRange);
}
forgetWavIntervals(wavIntervals);
}
deleteFloatArray(eqSpectrum);
}
}
return(best);
}
/**
* @memo
* Find approximate position of the peak (if any) closest to the input
* histogram center.
*
* @return Approximate position of the closest-to-center peak. In case
* of failure, a negative number is returned.
*
* @param data Input histogram.
* @param size Number of bins in input histogram.
*
* @doc
* This routine was added to increase robustness in the correct
* identification of lines in an arc spectrum. The input is the
* arc spectrum portion where a given line is expected: in case
* more than one peak were included in the interval, the closest
* one to the expected position (i.e., the center) is chosen.
* Starting from the interval center, the spectrum is searched
* for the closest-to-center flux excess, and then the rough
* position of this excess is returned. This routine will allow
* to use a wider window around the expected arc line position,
* increasing the probability of including the searched line
* - and limiting the effect of the equally increased probability
* of including also other nearby lines. For this function to be
* useful, therefore, it should be called after the first-guess
* inverse dispersion relation was pre-tuned (using findMaxMatchIndex).
*
* @see findMaxMatchIndex()
*
* @author C.Izzo
*/
int findClosestPeak(float *data, int size)
{
float max, min, level;
float percent = 1./4.;
int pos, posRight, posLeft, distRight, distLeft;
int i;
if (data == NULL || size <= 10) return -1;
pos = posRight = posLeft = size/2;
distRight = distLeft = 0;
/*
* Find min and max
*/
min = max = data[0];
for (i=1; i<size; i++) {
if (data[i] > max) max = data[i];
if (data[i] < min) min = data[i];
}
/*
* If the max equals the min we have a flat input, therefore
* no peak is found. Conventionally, return the position of the
* interval centre.
*/
if (max-min < MIN_DIVISOR) return pos;
/*
* Discrimination level: when pixels with values above this
* level are found, we are (probably) within a peak.
*/
level = percent * max + (1 - percent) * min;
if (data[pos] < level) {
for (; (posRight < size) && (data[posRight] <= level); posRight++);
distRight = posRight - size/2;
for (; (posLeft >= 0 ) && (data[posLeft] <= level); posLeft--);
distLeft = size/2 - posLeft;
if (distRight < distLeft) {
posLeft = posRight;
for (; (posRight < size) && (data[posRight] > level); posRight++);
}
else {
posRight = posLeft;
for (; (posLeft >= 0 ) && (data[posLeft] > level); posLeft--);
}
}
else if (data[pos] > level) {
for (; (posRight < size) && (data[posRight] > level); posRight++);
for (; (posLeft >= 0 ) && (data[posLeft] > level); posLeft--);
}
pos = (posLeft + posRight) / 2;
return(pos);
}
double **identPeaks(double *peak, int npeaks, double *line, int nlines,
double min_disp, double max_disp, double tolerance,
int *identified)
{
int i, j, k, l;
int nlint, npint;
double lratio, pratio;
double lo_start, lo_end, hi_start, hi_end, denom;
double disp, variation, prev_variation;
int max, maxpos, minl, mink;
int ambiguous;
int npeaks_lo, npeaks_hi;
int *peak_lo = cpl_malloc(npeaks * sizeof(int));
int *peak_hi = cpl_malloc(npeaks * sizeof(int));
int **ident = cpl_malloc(npeaks * sizeof(int *));
int *nident = cpl_calloc(npeaks, sizeof(int));
int *lident = cpl_calloc(nlines, sizeof(int));
double **output = cpl_calloc(2, sizeof(double *));
double *xpos = cpl_calloc(npeaks, sizeof(double));
double *lambda = cpl_calloc(npeaks, sizeof(double));
int *ilambda = cpl_calloc(npeaks, sizeof(int));
double *tmp_xpos = cpl_calloc(npeaks, sizeof(double));
double *tmp_lambda = cpl_calloc(npeaks, sizeof(double));
double *tmp_ilambda = cpl_calloc(npeaks, sizeof(double));
int *flag = cpl_calloc(npeaks, sizeof(int));
int n = 0;
int nn;
int nseq = 0;
int gap;
int *seq_length = cpl_calloc(npeaks, sizeof(int));
int found;
*identified = 0;
output[0] = xpos;
output[1] = lambda;
for (i = 0; i < npeaks; i++)
ident[i] = cpl_malloc(3 * npeaks * sizeof(int));
/*
* This is just the number of intervals - one less than the number
* of points (catalog wavelengths, or detected peaks). I do this
* for performance reasons.
*/
nlint = nlines;
npint = npeaks;
--nlint;
--npint;
/*
* Here the big loops on catalog lines begins.
*/
for (i = 1; i < nlint; i++) {
/*
* For each catalog line I take the previous and the next one, and
* compute the ratio of their distances from the central wavelengths.
* This ratio will be compared to all the ratios obtained doing the
* same with all the detected peaks positions.
*/
lratio = (line[i+1] - line[i]) / (line[i] - line[i-1]);
/*
* Here the loop on detected peaks positions begins.
*/
for (j = 1; j < npint; j++) {
/*
* Not all peaks are used for computing ratios: just the ones
* that are compatible with the expected spectral dispersion
* are taken into consideration. Therefore, I define the pixel
* intervals before and after any peak that are compatible with
* the specified dispersion interval, and select just the peaks
* within such intervals. If either of the two intervals doesn't
* contain any peak, then I skip the current peak and continue
* with the next.
*/
lo_start = peak[j] - (line[i] - line[i-1]) / min_disp;
lo_end = peak[j] - (line[i] - line[i-1]) / max_disp;
hi_start = peak[j] + (line[i+1] - line[i]) / max_disp;
hi_end = peak[j] + (line[i+1] - line[i]) / min_disp;
for (npeaks_lo = 0, k = 0; k < npeaks; k++) {
if (peak[k] > lo_end)
break;
if (peak[k] > lo_start) {
peak_lo[npeaks_lo] = k;
++npeaks_lo;
}
}
if (npeaks_lo == 0)
continue;
for (npeaks_hi = 0, k = 0; k < npeaks; k++) {
if (peak[k] > hi_end)
break;
if (peak[k] > hi_start) {
peak_hi[npeaks_hi] = k;
++npeaks_hi;
}
}
if (npeaks_hi == 0)
continue;
/*
* Now I have all peaks that may help for a local identification.
* peak_lo[k] is the sequence number of the k-th peak of the lower
* interval; peak_hi[l] is the sequence number of the l-th peak of
* the higher interval. j is, of course, the sequence number of the
* current peak (second big loop).
*/
prev_variation = 1000;
minl = mink = 0;
for (k = 0; k < npeaks_lo; k++) {
denom = peak[j] - peak[peak_lo[k]];
for (l = 0; l < npeaks_hi; l++) {
/*
* For any pair of peaks - one from the lower and the other
* from the higher interval - I compute the same ratio that
* was computed with the current line catalog wavelength.
*/
pratio = (peak[peak_hi[l]] - peak[j]) / denom;
/*
* If the two ratios are compatible within the specified
* tolerance, we have a preliminary identification. This
* is marked in the matrix ident[][], where the first index
* correspond to a peak sequence number, and the second
* index is the counter of the identifications made during
* this whole process. The array of counters is nident[].
*/
variation = fabs(lratio-pratio) / pratio;
if (variation < tolerance) {
if (variation < prev_variation) {
prev_variation = variation;
minl = l;
mink = k;
}
}
}
}
if (prev_variation < tolerance) {
ident[j][nident[j]] = i;
ident[peak_hi[minl]][nident[peak_hi[minl]]] = i + 1;
ident[peak_lo[mink]][nident[peak_lo[mink]]] = i - 1;
++nident[j];
++nident[peak_hi[minl]];
++nident[peak_lo[mink]];
}
} /* End loop on positions */
} /* End loop on lines */
/*
* At this point I have filled the ident matrix with all my preliminary
* identifications. Ambiguous identifications must be eliminated.
*/
for (i = 0; i < npeaks; i++) {
/*
* I don't take into consideration peaks that were never identified.
* They are likely contaminations, or emission lines that were not
* listed in the input wavelength catalog.
*/
if (nident[i] > 0) {
/*
* Reset the histogram of wavelengths assigned to the i-th peak.
*/
for (j = 0; j < nlines; j++)
lident[j] = 0;
/*
* Collect all the nident[i] wavelengths assigned to the i-th peak.
*/
for (j = 0; j < nident[i]; j++)
++lident[ident[i][j]];
/*
* What wavelength was most frequently assigned to the i-th peak?
*/
max = 0;
for (j = 0; j < nlines; j++) {
if (max < lident[j]) {
max = lident[j];
maxpos = j;
}
}
/*
* Were there other wavelengths assigned with the same frequency?
* This would be the case of an ambiguous identification. It is
* safer to reject this peak...
*/
ambiguous = 0;
for (k = maxpos + 1; k < nlines; k++) {
if (lident[k] == max) {
ambiguous = 1;
break;
}
}
if (ambiguous)
continue;
/*
* Otherwise, I assign to the i-th peak the wavelength that was
* most often assigned to it.
*/
tmp_xpos[n] = peak[i];
tmp_lambda[n] = line[maxpos];
tmp_ilambda[n] = maxpos;
++n;
}
}
/*
* Check on identified peaks. Contaminations might be present and
* should be excluded. Contamination from multiplexed spectra
* consists of correctly identified lines that really belong to other
* spectra. Generic light contamination and line misidentification
* should have been almost all removed in the previous steps, but
* it may still be present. The identified peaks are sorted into
* separated self-consistent sequences. The longest of those sequences
* is the one that is returned.
*/
if (n > 1) {
nn = 0;
nseq = 0;
for (k = 0; k < n; k++) {
if (flag[k] == 0) {
flag[k] = 1;
xpos[nn] = tmp_xpos[k];
lambda[nn] = tmp_lambda[k];
ilambda[nn] = tmp_ilambda[k];
++seq_length[nseq];
++nn;
i = k;
while (i < n - 1) {
found = 0;
for (j = i + 1; j < n; j++) {
if (flag[j] == 0) {
disp = (tmp_lambda[j] - tmp_lambda[i])
/ (tmp_xpos[j] - tmp_xpos[i]);
if (disp >= min_disp && disp <= max_disp) {
flag[j] = 1;
xpos[nn] = tmp_xpos[j];
lambda[nn] = tmp_lambda[j];
ilambda[nn] = tmp_ilambda[j];
++seq_length[nseq];
++nn;
i = j;
found = 1;
break;
}
}
}
if (!found)
break;
}
++nseq;
k = 0;
}
}
max = 0;
for (i = 0; i < nseq; i++) {
if (seq_length[i] > max) {
max = seq_length[i];
maxpos = i;
}
}
nn = 0;
for (i = 0; i < maxpos; i++)
nn += seq_length[i];
n = max;
for (i = 0; i < n; i++, nn++) {
xpos[i] = xpos[nn];
lambda[i] = lambda[nn];
ilambda[i] = ilambda[nn];
}
/*
* Are some wavelengths missing?
*/
for (i = 1; i < n; i++) {
gap = ilambda[i] - ilambda[i-1];
if (gap > 1) {
j = 1;
disp = (lambda[i] - lambda[i-1]) / (xpos[i] - xpos[i-1]);
hi_start = xpos[i-1] + (line[ilambda[i-1] + j] - lambda[i-1]) / disp;
found = 0;
for (k = 0; k < npeaks; k++) {
if (fabs(peak[k] - hi_start) < 2) {
for (l = n; l > i; l--) {
xpos[l] = xpos[l-1];
lambda[l] = lambda[l-1];
ilambda[l] = ilambda[l-1];
}
xpos[i] = peak[k];
lambda[i] = line[ilambda[i-1] + j];
ilambda[i] = ilambda[i-1] + j;
++n;
found = 1;
break;
}
}
}
}
/*
* Try to extrapolate forward
*/
found = 1;
while (ilambda[n-1] < nlines - 1 && found) {
hi_start = xpos[n-1] + (line[ilambda[n-1]+1] - lambda[n-1]) / max_disp;
hi_end = xpos[n-1] + (line[ilambda[n-1]+1] - lambda[n-1]) / min_disp;
found = 0;
for (i = 0; i < npeaks; i++) {
if (peak[i] > hi_start && peak[i] < hi_end) {
xpos[n] = peak[i];
lambda[n] = line[ilambda[n-1]+1];
ilambda[n] = ilambda[n-1]+1;
++n;
found = 1;
break;
}
}
}
/*
* Try to extrapolate backward
*/
found = 1;
while (ilambda[0] > 0 && found) {
hi_start = xpos[0] + (line[ilambda[0]-1] - lambda[0]) / min_disp;
hi_end = xpos[0] + (line[ilambda[0]-1] - lambda[0]) / max_disp;
found = 0;
for (i = 0; i < npeaks; i++) {
if (peak[i] > hi_start && peak[i] < hi_end) {
for (j = n; j > 0; j--) {
xpos[j] = xpos[j-1];
lambda[j] = lambda[j-1];
ilambda[j] = ilambda[j-1];
}
xpos[0] = peak[i];
lambda[0] = line[ilambda[0]-1];
ilambda[0] = ilambda[0]-1;
++n;
found = 1;
break;
}
}
}
}
/*
* At this point all peaks are processed. Free memory, and return
* the result.
*/
/************************************************
for (i = 0; i < npeaks; i++) {
printf("Peak %d:\n ", i);
for (j = 0; j < nident[i]; j++)
printf("%.2f, ", line[ident[i][j]]);
printf("\n");
}
printf("\n");
for (i = 0; i < n; i++)
printf("%.2f, %.2f\n", xpos[i], lambda[i]);
**************************************************/
for (i = 0; i < npeaks; i++)
cpl_free(ident[i]);
cpl_free(ident);
cpl_free(nident);
cpl_free(lident);
cpl_free(ilambda);
cpl_free(tmp_xpos);
cpl_free(tmp_lambda);
cpl_free(tmp_ilambda);
cpl_free(peak_lo);
cpl_free(flag);
cpl_free(seq_length);
cpl_free(peak_hi);
*identified = n;
if (n == 0) {
cpl_free(output[0]);
cpl_free(output[1]);
cpl_free(output);
return NULL;
}
return output;
}
static double values_to_dx(double v1, double v2, double v3)
{
static double epsilon = 0.00000001;
double r = 2.0;
if (v1 > v2 || v3 > v2)
return r;
if (2 * v2 - v1 - v3 < epsilon)
return r;
r = 0.5 * (v3 - v1) / (2 * v2 - v3 - v1);
return r;
}
double *collectPeaks(float *row, int length,
float level, float exp_width, int *npeak)
{
int i, j;
int nint = length - 1;
int n = 0;
int width = 2 * ceil(exp_width / 2) + 1;
int start = width / 2;
int end = length - width / 2;
int step;
int minbox = 21;
float min;
float *smo;
float *flat;
double *peak = cpl_calloc(length/2, sizeof(double));
/*
* If lines have a flat top (as in the case of broad slit), smooth
* before determining the max.
*/
if (width > 3) {
smo = cpl_calloc(length, sizeof(float));
start = width / 2;
end = length - width / 2;
for (i = 0; i < start; i++)
smo[i] = row[i];
for (i = start; i < end; i++) {
for (j = i - start; j <= i + start; j++)
smo[i] += row[j];
smo[i] /= width;
}
for (i = end; i < length; i++)
smo[i] = row[i];
}
else {
smo = row;
}
/*
* Pass a min filter to subtract the continuum
*/
flat = cpl_calloc(length, sizeof(float));
start = minbox / 2;
end = length - minbox / 2;
for (i = start; i < end; i++) {
min = smo[i-start];
for (j = i - start + 1; j <= i + start; j++)
if (min > smo[j])
min = smo[j];
flat[i] = min;
}
if (width > 3) {
cpl_free(smo);
}
for (i = 0; i < start; i++)
flat[i] = row[i] - flat[start];
for (i = start; i < end; i++)
flat[i] = row[i] - flat[i];
for (i = end; i < length; i++)
flat[i] = row[i] - flat[end - 1];
if (width > 20)
step = width / 2;
else
step = 1;
/*
* Collect all relative maxima along row, that are higher than the
* specified level.
*/
for (i = step; i < nint - step + 1; i += step) {
if (flat[i] > level) {
if (flat[i] >= flat[i-step] && flat[i] > flat[i+step]) {
if (flat[i-step] != 0.0 && flat[i+step] != 0.0) {
peak[n] = i + step * values_to_dx(flat[i-step], flat[i], flat[i+step]);
++n;
}
}
}
}
*npeak = n;
cpl_free(flat);
if (n == 0) {
cpl_free(peak);
return NULL;
}
return peak;
}
double *collectPeaks_double(double *row, int length,
float level, float exp_width, int *npeak)
{
int i, j;
int nint = length - 1;
int n = 0;
int width = 2 * ceil(exp_width / 2) + 1;
int start = width / 2;
int end = length - width / 2;
int step;
int minbox = 21;
float min;
double *smo;
float *flat;
double *peak = cpl_calloc(length/2, sizeof(double));
/*
* If lines have a flat top (as in the case of broad slit), smooth
* before determining the max.
*/
if (width > 3) {
smo = cpl_calloc(length, sizeof(float));
start = width / 2;
end = length - width / 2;
for (i = 0; i < start; i++)
smo[i] = row[i];
for (i = start; i < end; i++) {
for (j = i - start; j <= i + start; j++)
smo[i] += row[j];
smo[i] /= width;
}
for (i = end; i < length; i++)
smo[i] = row[i];
}
else {
smo = row;
}
/*
* Pass a min filter to subtract the continuum
*/
flat = cpl_calloc(length, sizeof(float));
start = minbox / 2;
end = length - minbox / 2;
for (i = start; i < end; i++) {
min = smo[i-start];
for (j = i - start + 1; j <= i + start; j++)
if (min > smo[j])
min = smo[j];
flat[i] = min;
}
if (width > 3) {
cpl_free(smo);
}
for (i = 0; i < start; i++)
flat[i] = row[i] - flat[start];
for (i = start; i < end; i++)
flat[i] = row[i] - flat[i];
for (i = end; i < length; i++)
flat[i] = row[i] - flat[end - 1];
if (width > 20)
step = width / 2;
else
step = 1;
/*
* Collect all relative maxima along row, that are higher than the
* specified level.
*/
for (i = step; i < nint - step + 1; i += step) {
if (flat[i] > level) {
if (flat[i] >= flat[i-step] && flat[i] > flat[i+step]) {
if (flat[i-step] != 0.0 && flat[i+step] != 0.0) {
peak[n] = i + step * values_to_dx(flat[i-step], flat[i], flat[i+step]);
++n;
}
}
}
}
*npeak = n;
cpl_free(flat);
if (n == 0) {
cpl_free(peak);
return NULL;
}
return peak;
}
/**@}*/
|