Skip to content

PyNebCore

@module pynebcore Main PyNeb module Tools to manage atoms, emission lines and observational data.

@class Atom atom object @class EmissionLine emission line object @class Observation observation object

Atom

Bases: object

Define the atom object, fill it with data, explore the data, and compute quantities such as level populations and line emissivities.

Source code in pyneb/core/pynebcore.py
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
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
class Atom(object):
    """
    Define the atom object, fill it with data, explore the data, and 
    compute quantities such as level populations and line emissivities.

    """
    # This following Class variable will hold the (unique) references of every Atom instance created.
    # This allows to list all the references used in a project.


    @profile
    def __init__(self, elem=None, spec=None, atom=None, OmegaInterp='linear', noExtrapol = False, NLevels=None):
        """
        Atom constructor

        Parameters:
            elem:          symbol of the selected element
            spec:          ionization stage in spectroscopic notation (I = 1, II = 2, etc.)
            atom:          ion (e.g. 'O3').
            OmegaInterp:   option "kind" from scipy.interpolate.interp1d method: 
                            'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'previous', 'next', 
                            where 'zero', 'slinear', 'quadratic' and 'cubic' refer to a spline interpolation of 
                            zeroth, first, second or third order; 'previous' and 'next' simply return the 
                            previous or next value of the point. 
                            "Cheb" works only for fits files for historical reasons.
            noExtrapol:    if set to False (default), Omega will be extrapolated above and below
                            the highest and lowest temperatures where it is defined. If set to True
                            a NaN will be return.

        **Usage:**
            O3 = pn.Atom('O',3)

            N2 = pn.Atom(atom='N2')

            S2 = pn.Atom(atom='S2', OmegaInterp='linear')
        """        
        self.log_ = log_
        self.type = 'coll'
        self.is_valid = True
        if atom is not None:
            self.atom = str.capitalize(atom)
            self.elem = parseAtom(self.atom)[0]
            self.spec = int(parseAtom(self.atom)[1])
        else:
            if elem is None:
                self.log_.error('At least elem or atom needs to be given', calling='Atom')
            if elem[0].isalpha():
                self.elem = str.capitalize(elem)
            else:
                self.elem = elem
            self.spec = int(spec)
            self.atom = self.elem + str(self.spec)
        self.name = sym2name[self.elem]
        try:
            self.Z = Z[self.elem]
        except:
            self.Z = -1
        if self.elem in IP:
            if self.spec == 0:
                self.IP = -1
                self.IP_up = -1
            elif self.spec == 1:
                self.IP = 0
                try:
                    self.IP_up = IP[self.elem][self.spec-1]
                except:
                    self.IP = -1                    
            else:
                try:
                    self.IP = IP[self.elem][self.spec-2]
                except:
                    self.IP = -1
                try:
                    self.IP_up = IP[self.elem][self.spec-1]
                except:
                    self.IP = -1                    
        else:
            self.IP = -1
            self.IP_up = -1
        self.calling = 'Atom ' + self.atom
        self.log_.message('Making atom object for {0} {1}'.format(self.elem, self.spec), calling=self.calling)
        self.NLevels = NLevels
        dataFile = atomicData.getDataFile(self.atom, data_type='atom')
        if dataFile is None:
            self.atomFileType = None
        else:
            self.atomFileType = dataFile.split('.')[-1]
        if self.atomFileType == 'fits':
            self.AtomData = _AtomDataFits(elem=self.elem, spec=self.spec, atom=self.atom, NLevels=self.NLevels)
        elif self.atomFileType == 'dat':
            self.AtomData = _AtomDataAscii(elem=self.elem, spec=self.spec, atom=self.atom, NLevels=self.NLevels)
        elif self.atomFileType == 'chianti':
            self.AtomData = _AtomChianti(elem=self.elem, spec=self.spec, atom=self.atom, NLevels=self.NLevels)
        elif self.atomFileType == 'stout':
            self.AtomData = _AtomDataStout(elem=self.elem, spec=self.spec, atom=self.atom, NLevels=self.NLevels)
        elif self.atomFileType is None:
            self.AtomData = _AtomDataNone()
            self.is_valid = False
        else:
            self.log_.error('Atom file extensions must be fits, dat or chianti')

        self.atomFile = self.AtomData.atomFile
        self.atomPath = self.AtomData.atomPath
        self.atomFitsFile = self.atomFile # Obsolete
        self.atomFitsPath = self.atomPath # Obsolete
        self.wave_Ang = self.AtomData.wave_Ang
        self.getStatWeight = self.AtomData.getStatWeight
        self.getEnergy = self.AtomData.getEnergy
        self.atomNLevels = self.AtomData.NLevels


        dataFile = atomicData.getDataFile(self.atom, data_type='coll')
        if dataFile is None:
            self.collFileType = None
        else:
            self.collFileType = dataFile.split('.')[-1]
        if self.collFileType == 'fits':
            self.CollData = _CollDataFits(elem=self.elem, spec=self.spec, atom=self.atom, 
                                         OmegaInterp=OmegaInterp, noExtrapol = noExtrapol, NLevels=self.NLevels)
        elif self.collFileType == 'dat':
            self.CollData = _CollDataAscii(elem=self.elem, spec=self.spec, atom=self.atom, 
                                          OmegaInterp=OmegaInterp, noExtrapol = noExtrapol, NLevels=self.NLevels)
        elif self.collFileType == 'chianti':
            self.CollData = _CollChianti(elem=self.elem, spec=self.spec, atom=self.atom, NLevels=self.NLevels)
        elif self.collFileType == 'stout':
            self.CollData = _CollDataStout(elem=self.elem, spec=self.spec, atom=self.atom, NLevels=self.NLevels)            
        elif self.collFileType is None:
            self.CollData = _CollDataNone()
            self.is_valid = False
        try:
            self.CollHeader = self.CollData.CollHeader
        except:
            pass
        if "comments" not in self.CollData.__dict__.keys():
            self.CollData.comments = []
        self.getOmegaArray = self.CollData.getOmegaArray
        self.getTemArray = self.CollData.getTemArray
        self.collFile = self.CollData.collFile
        self.collPath = self.CollData.collPath
        self.collFitsFile = self.collFile # Obsolete
        self.collFitsPath = self.collPath # Obsolete
        self.collNLevels = self.CollData.NLevels
        self.tem_units = self.CollData.tem_units

        self.NLevels = np.min((self.atomNLevels, self.collNLevels))

        self.gs = gsFromAtom(self.atom)
        try:
            self.AtomHeader = self.AtomData.AtomHeader
        except:
            self.AtomHeader = None
        try:
            self.NIST = self.AtomData.NIST
        except:
            try:
                self.NIST = getLevelsNIST(self.atom, self.NLevels)
            except:
                self.NIST = None

        self.lineList = []
        for i in np.arange(self.NLevels):
            for j in np.arange(i):
                self.lineList.append(self.wave_Ang[i][j])
        self.lineList = np.array(self.lineList)

        self.energy_Ryd = quiet_divide(CST.RYD_ANG, self.wave_Ang)
        self.energy_eV = CST.RYD_EV * self.energy_Ryd

        self._A = self.getA() # index = quantum number - 1
        self._Energy = self.getEnergy() # Angstrom^-1
        self._StatWeight = self.getStatWeight()
        if self.NLevels > 0:
            self.EnergyNLevels = len(self._Energy)
        else:
            self.EnergyNLevels = None
        self.source = self.getSources()
        atomicData.add2usedFiles(self.atom, self.atomFile)
        atomicData.add2usedFiles(self.atom, self.collFile)

        self.ANN_n_temden=30
        self.ANN_inst_kwargs = {'RM_type' : 'SK_ANN', 
                                'verbose' : False, 
                                'scaling' : True,
                                'use_log' : True
                                }
        self.ANN_init_kwargs = {'solver' : 'lbfgs', 
                                'activation' : 'tanh', 
                                'hidden_layer_sizes' : (10, 10), 
                                'tol' : 1e-6,
                                'max_iter' : 20000
                                }
        self.ANN_Pop_inst_kwargs = {'RM_type' : 'SK_ANN', 
                                'verbose' : False, 
                                'scaling' : True,
                                'use_log' : True
                                }
        self.ANN_Pop_init_kwargs = {'solver' : 'lbfgs', 
                                'activation' : 'tanh', 
                                'hidden_layer_sizes' : (10, 10), 
                                'tol' : 1e-6,
                                'max_iter' : 20000
                                }


    def getOmega(self, tem, lev_i= -1, lev_j= -1, wave= -1):
        """
        Return interpolated value of the collision strength value at the given temperature 
            for the complete array or a specified transition.
        If kappa is not None (non-maxwellian distribution of e-velocities), the collision 
            strength is corrected as in Mendoza & Bautista, 2014 ApJ 785, 91.

        Parameters:
            tem:    electronic temperature in K. May be an array.
            lev_i:  upper level
            lev_j:  lower level

        **Usage:**

            O3.getOmega(15000.)

            O3.getOmega([8e3, 1e4, 1.2e4])

            O3.getOmega([8e3, 1e4, 1.2e4], 5, 4)
        """



        if wave != -1:
            lev_i, lev_j = self.getTransition(wave)
        kappa = config.kappa 
        if kappa is None:
            to_return = self.CollData.getOmega(tem, lev_i, lev_j)
        else:
            #ToDo The Kappa correction should come AFTER the transformation into CS unit
            if (lev_i == -1) and (lev_j == -1):
                tem = np.asarray(tem)
                res_shape = [self.collNLevels, self.collNLevels]
                for sh in tem.shape:
                    res_shape.append(sh)
                Omega = np.zeros(res_shape)

                for i in range(self.collNLevels - 1):
                    j = i + 1
                    while (j < self.collNLevels):
                        Omega[j][i] = self.getOmega(tem, j + 1, i + 1)
                        j += 1
            else:
                OmegaMB = self.CollData.getOmega(tem, lev_i, lev_j)
                delta_E = self.getEnergy(lev_i, unit='eV') - self.getEnergy(lev_j, unit='eV')
                correc = ((kappa - 3./2.)**(-0.5) / kappa * gamma(kappa+1) / gamma(kappa-0.5) * 
                          (1 + delta_E/((kappa-1.5)*CST.BOLTZMANN_eVK*tem))**(-kappa)) * np.exp(delta_E/CST.BOLTZMANN_eVK/tem)

                Omega = correc * OmegaMB
                self.log_.message('Correcting for Kappa={0} by {1}'.format(kappa, correc), self.calling)

            to_return = np.squeeze(Omega)
        if 'COEFF' in self.CollData.comments:
            to_return *= float(self.CollData.comments['COEFF'])
        if 'O_UNIT' in self.CollData.comments:
            if self.CollData.comments['O_UNIT'] == 'DEEX RATE COEFF':
                to_return /= CST.KCOLLRATE / tem ** 0.5 / self.getStatWeight(lev_i)
            elif self.CollData.comments['O_UNIT'] == 'RATE COEFF':
                deltaE = self.getEnergy(lev_i, unit='erg') - self.getEnergy(lev_j, unit='erg')
                to_return *= (self.getStatWeight(lev_j) / self.getStatWeight(lev_i) * np.exp(deltaE /(CST.BOLTZMANN * tem))) #q21
                to_return /= CST.KCOLLRATE / tem ** 0.5 / self.getStatWeight(lev_i)
            elif self.CollData.comments['O_UNIT'] == 'COOLING':
                deltaE = self.getEnergy(lev_i, unit='erg') - self.getEnergy(lev_j, unit='erg')
                to_return /= deltaE # Loss to q12                
                to_return *= (self.getStatWeight(lev_j) / self.getStatWeight(lev_i) * np.exp(deltaE /(CST.BOLTZMANN * tem))) #q21
                to_return /= (CST.KCOLLRATE / np.sqrt(tem) / self.getStatWeight(lev_i)) # Omega

        return to_return

    @profile
    def getCollRates(self, tem, NLevels=None):
        """
        Return (n_levels x n_levels) array of collision rates at given temperature. 

        Parameters:
            tem:     electronic temperature in K. May be an array.

        **Usage:**

            O3.getCollRates(tem=10000)

            O3.getCollRates([8e3, 1e4, 1.2e4])


        """
        tem = np.asarray(tem)
        if NLevels is None:
            NLevels = np.min((self.collNLevels, self.EnergyNLevels))
        res_shape = [NLevels, NLevels]
        for sh in tem.shape:
            res_shape.append(sh)
        resultArray = np.zeros(res_shape)
        Omegas = self.getOmega(tem)
        for i in range(NLevels - 1):
            lev_i = i + 1
            j = i + 1
            energy_i = self._Energy[i]
            stat_weight_i = self._StatWeight[i]
            while (j < NLevels):
                lev_j = j + 1 
                energy_j = self._Energy[j]
                stat_weight_j = self._StatWeight[j]
                resultArray[j][i] = CST.KCOLLRATE / tem ** 0.5 / stat_weight_j * Omegas[lev_j-1, lev_i-1]
                resultArray[i][j] = ((stat_weight_j) / (stat_weight_i) * 
                                      np.exp((energy_i - energy_j) / (CST.BOLTZMANN_ANGK * tem)) * 
                                      resultArray[j][i])
                j += 1

        return np.squeeze(resultArray)


    def _Transition(self, wave, maxErrorA = 5.e-3, maxErrorm = 5.e-2):
        """
        Return an array with computed upper level, computed lower level, computed wavelength, 
            input wavelength

        Parameters:
            wave:       wavelength either in Angstrom (a float or a label: e.g., 5007, '5007A') 
                            or in micron (a label: '51.5m')
            maxErrorA: tolerance if the input wavelength is in Angstrom
            maxErrorm: tolerance if the input wavelength is in micron                 
        """
        if str(wave)[-1] == 'A':
            inputWave = float(wave[:-1])
            label = '{0}_{1}'.format(self.atom, wave)
            maxError = maxErrorA
        elif str(wave)[-1] == 'm':
            inputWave = float(wave[:-1]) * 1e4
            label = '{0}_{1}'.format(self.atom, wave)
            maxError = maxErrorm
        else:
            inputWave = wave
            label = '{0}_{1}A'.format(self.atom, int(wave))
            maxError = maxErrorA

        #self.log_.debug('{}'.format(label2levelDict), calling='_Transition')
        if label in label2levelDict:
            result = [label2levelDict[label][0], label2levelDict[label][1], inputWave, inputWave]
            #self.log_.debug('label2levelDict[{}] = {}'.format(label, label2levelDict[label]),calling='_Transition')
            return(result)

        j, i = np.unravel_index(np.argmin(abs(self.wave_Ang - inputWave)), self.wave_Ang.shape)
        bestWave = self.wave_Ang[i, j]
        error = np.abs(bestWave - inputWave) / inputWave
        result = [i + 1, j + 1, bestWave, inputWave]
        if error > maxError:
            self.log_.warn('_Transition: wavelengths differ by more than {0:.2f}%: input = {1:.2f}, output = {2:.2f}'\
                           .format(100 * maxError, inputWave, bestWave), calling=self.calling)
        return(result)


    def getTransition(self, wave, maxErrorA = 5.e-3, maxErrorm = 5.e-2):
        """
        Return the indexes (upper level, lower level) of a transition for a given atom 
            from the wavelength.



        Parameters:
            wave:      wavelength in Angstrom (a float or a label: e.g., 5007, '5007A') 
                or in micron (a label: '51.5m')
            maxErrorA: tolerance if the input wavelength is in Angstrom
            maxErrorm: tolerance if the input wavelength is in micron

        **Usage:**

            O3.getTransition(4959)   
        """ 
        res = self._Transition(wave, maxErrorA = maxErrorA, maxErrorm = maxErrorm)
        return(res[0], res[1])


    def printTransition(self, wave):
        """
        Print info on transition associated to input wavelength.

        Parameters:
            wave:      wavelength in Angstrom (a float or a label: e.g., 5007, '5007A') 
                or in micron (a label: '51.5m')

        **Usage:**

            O3.printTransition(4959)        
        """
        closestTransition = self._Transition(wave)
        relativeError = closestTransition[3] / closestTransition[2] - 1
        print('Input wave: {0:.1F}'.format(closestTransition[3]))
        print('Closest wave found: {0:.1F}'.format(closestTransition[2]))
        print('Relative error: {0:.0E} '.format(relativeError))
        print('Transition: {0[0]} -> {0[1]}'.format(closestTransition))
        return

    def printSources(self):

        for source in self.getSources():
            print(source)    

    def getSources(self):
        sources = []
        if self.AtomData is not self.CollData:
            sources.extend(self.AtomData.getSources())
            sources.extend(self.CollData.getSources())
        else:
            sources.extend(self.AtomData.getSources())
        return sources

    def _test_lev(self, level):
        """
        Test whether selected level is legal

        Parameters:
            level:        selected atom level

        """       
        if level < -1 or level == 0 or level > self.NLevels:
            self.log_.error('Wrong value for level: {0}, maximum = {1}'.format(level, self.NLevels),
                            calling=self.calling)

    def getA(self, lev_i= -1, lev_j= -1, wave= -1):
        """
        Return the transition probability data. 
        If no arguments are given, the whole array of A is returned.
        A specific A value can be obtained by giving either the upper and lower levels or 
            the wavelength of the transition (keyword wave).

        Parameters:
            lev_i:  upper level of transition (default= -1, returns complete array)
            lev_j:  lower level of transition (default= -1, returns complete array)
            wave:   wavelength of transition. Takes precedence on lev_i and lev_j. Ignored if not set.

        **Usage:**

            A_O3 = O3.getA()          # The whole A array is stored in A_O3

            O3.getA(4, 2)      # A(4, 2) of the O3 atom is printed

            O3.getA(2, 4)      # Returns 0

            O3.getA(wave=4959)

        """
        if wave != -1:
            lev_i, lev_j = self.getTransition(wave)

        return self.AtomData.getA(lev_i= lev_i, lev_j= lev_j)

    @profile
    def _getPopulations_ANN(self, tem, den, product=True, NLevels=None):
        """
        Private method to obtain level population using Artificial Neuron Network.
        """
        if not config.INSTALLED['ai4neb']:
            self.log_.error('_getPopulations_ANN cannot be used in absence of ai4neb package',
                          calling=self.calling)
            return None

        N = 5000
        tem_min = 10**np.min(self.getTemArray())
        tem_max = 10**np.max(self.getTemArray())

        tem_train = tem_min + (tem_max - tem_min) * np.random.rand(N)
        den_train = 10**(1 + 5 * np.random.rand(N))

        pop_train = self.getPopulations(tem_train, den_train, product=False)
        if NLevels is None:
            n_levels = self.NLevels
        else:
            n_levels = NLevels
        pop_train = pop_train[0:n_levels,:]
        X = np.asarray((tem_train, den_train)).T
        y = np.log10(pop_train).T
        RM = manage_RM(X_train=X, y_train=y, **self.ANN_Pop_inst_kwargs)
        RM.init_RM(**self.ANN_Pop_init_kwargs)
        RM.train_RM()



    @profile
    def getPopulations(self, tem, den, product=True, NLevels=None):
        """
        Return array of populations at given temperature and density.
        The method returns a 1-, 2- or 3-D array containing the population of each level 
            for all temperatures and densities specified in the input vectors tem and den 
            (which can be n-element or 1-element vectors).
        If either quantity (tem or den) is a 1-element vector -that is, a single value-, 
            the resulting population array is collapsed along that dimension; 
            as a result, the result population array can be a 1-D, 2-D or 3-D array 
            (the three cases corresponding to situations in which both tem and den are single values; 
            one of them is a single value and the other an n-element vector; or both are multielement 
            vectors, respectively). In the general case, the level index is the first 
            [WARNING! It is not in physical unit, i.e. ground level = 0; to be normalized], 
            followed by the temperature index (if it exists) and the density index. 

        Parameters:
            tem:       electronic temperature in K
            den:       electronic density in cm^-3
            product:   operate on all possible combinations of temperature and density 
                      (product = True, default case) or on those resulting from combining 
                      the i-th value of tem with the i-th value of den (product = False).
                      If product = False, then tem and den must be the same size.

        **Usage:**

            O3.getPopulations(1e4, 1e2)

            tem=np.array([10000., 12000., 15000., 20000]) # An array of four temperatures

            den=np.array([600., 800., 1000])      # An array of three densities

            O3.getPopulations(tem, den)           # is a (6, 4, 3) array

            O3.getPopulations(tem, den)[0,2,1]    # Returns the population of level 1 for T = 15000 
                                                    and Ne = 800

            tem = 20000                           # tem is no longer an array

            O3.getPopulations(tem, den)[0,2,1]  # Crashes: one index too much

            O3.getPopulations(tem, den)[0,1]    # Returns the population of level 1 for T = 20000 
                                                    and Ne = 800 [see warning]

            tem=np.array([10000., 15000., 20000]) # An array of three temperatures

            O3.getPopulations(tem, den, product = False)# is a (6, 3) array, tem and den beeing 
                                                            taken 2 by 2.

        """
        tem = np.asarray(tem)
        den = np.asarray(den)
        if NLevels is None:
            n_level = self.NLevels
        else:
            n_level = NLevels
        if product:
            n_tem = tem.size
            n_den = den.size
            tem_ones = np.ones(n_tem)
            den_ones = np.ones(n_den)
            # q is vector-indexed (q(0, 1) = rate between levels 1 and 2)
            q = self.getCollRates(tem, n_level)
            Atem = np.outer(self._A[:n_level, :n_level], tem_ones).reshape(n_level, n_level, n_tem)
            pop_result = np.zeros((n_level, n_tem, n_den))
            sum_q_up = np.zeros((n_level, n_tem))
            sum_q_down = np.zeros((n_level, n_tem))
            sum_A = np.squeeze(Atem.sum(axis=1))
            self._critDensity = sum_A / q.sum(axis=1)
            for i in range(1, n_level):
                for j in range(i + 1, n_level):
                    sum_q_up[i] = sum_q_up[i] + q[i, j]
                for j in range(0, i):
                    sum_q_down[i] = sum_q_down[i] + q[i, j]
            coeff_matrix = ((np.outer(np.swapaxes(q, 0, 1), den) + 
                             np.outer(np.swapaxes(Atem, 0, 1), den_ones)).reshape(n_level, n_level, n_tem, n_den))
            coeff_matrix[0, :] = 1.
            for i in range(1, n_level):
                coeff_matrix[i, i] = (-(np.outer((sum_q_up[i] + sum_q_down[i]), den) + 
                                        np.outer(sum_A[i], den_ones)).reshape(1, 1, n_tem, n_den))
            vect = np.zeros(n_level)
            vect[0] = 1.

            for i_tem in range(n_tem):
                for i_den in range(n_den):
                    pop_result[:, i_tem, i_den] = solve(np.squeeze(coeff_matrix[:, :, i_tem, i_den]), vect)
                    try:
                        pop_result[:, i_tem, i_den] = solve(np.squeeze(coeff_matrix[:, :, i_tem, i_den]), vect)
                    #except np.linalg.LinAlgError:
                    #    pop_result[:, i_tem, i_den] = np.nan
                    except:
                        self.log_.error('Error solving population matrix', calling=self.calling)
            pop = np.squeeze(pop_result)
        else:
            if tem.shape != den.shape:
                self.log_.error('tem and den must have the same shape', calling=self.calling)
                return None
            res_shape1 = [n_level]
            res_shape_rav1 = [n_level, tem.size]
            res_shape_rav2 = [n_level, n_level, tem.size]
            for sh in tem.shape:
                res_shape1.append(sh)
            tem_rav = tem.ravel()
            den_rav = den.ravel()
            q = self.getCollRates(tem_rav, n_level)
            A = self._A[:n_level, :n_level]
            pop_result = np.zeros(res_shape_rav1)
            coeff_matrix = np.ones(res_shape_rav2)
            sum_q_up = np.zeros(res_shape_rav1)
            sum_q_down = np.zeros(res_shape_rav1)
            sum_A = A.sum(axis=1)
            n_tem = tem_rav.size
            # Following line changed 29/11/2012. It made the code crash when atom_nlevels diff coll_nlevels
            #Atem = np.outer(self._A, np.ones(n_tem)).reshape(n_level, n_level, n_tem)
            Atem = np.outer(self._A[:n_level, :n_level], np.ones(n_tem)).reshape(n_level, n_level, n_tem)
            self._critDensity = Atem.sum(axis=1) / q.sum(axis=1)

            for i in range(1, n_level):
                for j in range(i + 1, n_level):
                    sum_q_up[i] = sum_q_up[i] + q[i, j]
                for j in range(0, i):
                    sum_q_down[i] = sum_q_down[i] + q[i, j]
            for row in range(1, n_level):
                # upper right half            
                for col in range(row + 1, n_level):
                    coeff_matrix[row, col] = den_rav * q[col, row] + A[col, row]
                # lower left half
                for col in range(0, row):
                    coeff_matrix[row, col] = den_rav * q[col, row]
                # diagonal
                coeff_matrix[row, row] = -(den_rav * (sum_q_up[row] + sum_q_down[row]) + sum_A[row])

            vect = np.zeros(n_level)
            vect[0] = 1.

            for i in range(tem.size):
                try:
                    pop_result[:, i] = solve(np.squeeze(coeff_matrix[:, :, i]), vect)
                except np.linalg.LinAlgError:
                    pop_result[:, i] = np.nan
                except:
                    self.log_.error('Error solving population matrix', calling=self.calling)

            pop = np.squeeze(pop_result.reshape(res_shape1))

        return pop


    def getLowDensRatio(self, lev_i1=-1, lev_i2=-1, wave1=-1, wave2=-1, to_eval=None):

        """
        Return the value of a diagostic ratio at the low density limit

        Parameters:
            lev_i1 (int):
            lev_i2 (int):
            wave1 (int):
            wave2 (int):
            to_eval (str): 

        **Usage:**

            S2.getLowDensRatio(lev_i1 = 3, lev_i2 = 2)

            S2.getLowDensRatio(wave1 = 6716, wave2 = 6731)

            S2.getLowDensRatio(to_eval = 'L(6716)/L(6731)')
        """

        if wave1 != -1:
            lev_i1, lev_j1 = self.getTransition(wave1)
        if wave2 != -1:
            lev_i2, lev_j2 = self.getTransition(wave2)

        if to_eval is not None:
            L = lambda wave: self.getStatWeight(self.getTransition(wave)[0])
            return eval(to_eval)

        return self.getStatWeight(lev_i1) / self.getStatWeight(lev_i2)


    def getHighDensRatio(self, lev_i1=-1, lev_i2=-1, lev_j1=-1, lev_j2=-1, wave1=-1, wave2=-1, to_eval=None):

        """
        Return the value of a diagostic ratio at the high density limit

        Parameters:
            lev_i1 (int):
            lev_i2 (int):
            wave1 (int):
            wave2 (int):
            to_eval (str): 

        **Usage:**

            S2.getHighDensRatio(lev_i1 = 3, lev_i2 = 2)

            S2.getHighDensRatio(wave1 = 6716, wave2 = 6731)

            S2.getHighDensRatio(to_eval = 'L(6716)/L(6731)')
        """

        if wave1 != -1:
            lev_i1, lev_j1 = self.getTransition(wave1)
        if wave2 != -1:
            lev_i2, lev_j2 = self.getTransition(wave2)

        if to_eval is not None:
            L = lambda wave: (self.getStatWeight(self.getTransition(wave)[0]) * 
                              self.getA(self.getTransition(wave)[0], self.getTransition(wave)[1]))
            return eval(to_eval)

        return (self.getStatWeight(lev_i1) / self.getStatWeight(lev_i2) *
                self.getA(lev_i1, lev_j1) / self.getA(lev_i2, lev_j2))

    def getDensityRange(self, lev_i1=-1, lev_i2=-1, lev_j1=-1, lev_j2=-1, wave1=-1, wave2=-1, 
                        to_eval=None, tol=0.1, tem=1e4):
        """
        Return the range of density where a given line ratio is between 10% and 90% of the low and high density limits

        Parameters:
            lev_i1 (int):
            lev_i2 (int):
            wave1 (int):
            wave2 (int):
            to_eval (str):
            tol (float): 
            tem (float):
        """
        LowLim = self.getLowDensRatio(lev_i1, lev_i2, wave1, wave2, to_eval)
        HighLim = self.getHighDensRatio(lev_i1, lev_i2, lev_j1, lev_j2, wave1, wave2, to_eval)

        delta = abs(LowLim - HighLim)
        minRatio = min((LowLim, HighLim)) + tol * delta
        maxRatio = max((LowLim, HighLim)) - tol * delta
        dens1 = self.getTemDen(minRatio, tem=tem, lev_i1= lev_i1, lev_j1= lev_j1, lev_i2= lev_i2, lev_j2= lev_j2,
                  wave1= wave1, wave2= wave2, to_eval=to_eval)
        dens2 = self.getTemDen(maxRatio, tem=tem, lev_i1= lev_i1, lev_j1= lev_j1, lev_i2= lev_i2, lev_j2= lev_j2,
                  wave1= wave1, wave2= wave2, to_eval=to_eval)
        return(np.sort((dens1, dens2)))

    @profile
    def getCritDensity(self, tem, level= -1):
        """
        Return the critical density of selected level at given temperature. 
        If no transition is selected, return complete array.

        Parameters:
            tem:    electronic temperature in K. May be an array.
            level:  selected atomic level (default= -1)

        **Usage:**

            O3.getCritDensity(12000)

            O3.getCritDensity(12000, 4)

        """
        self._test_lev(level)
        self.getPopulations(tem, den=100.) # Any density would do
        if level != -1:
            return self._critDensity[level - 1]
        else:
            return self._critDensity        

    @profile
    def getEmissivity(self, tem, den, lev_i= -1, lev_j= -1, wave= -1, product=True, use_ANN=False):
        """
        Return the line emissivity (in erg.s-1.cm3) of selected transition or complete array of emissivities
        The transition is selected by the argument wave (if given); 
        if wave is not supplied, it is selected by the upper and lower levels (lev_i and lev_j); 
        if neither is given, the whole array is computed

        Parameters:
            tem:      electronic temperature in K. May be an array.
            den:      electronic density in cm^-3. May be an array.
            lev_i:    upper level (default= -1)
            lev_j:    lower level (default= -1)
            wave:     wavelength of transition. Takes precedence on lev_i and lev_j if set, 
                        ignored otherwise. It can also be a blend label.
            product:  Boolean. If True (default), all the combination of (tem, den) are used. 
                         If False, tem and den must have the same size and are joined.

        **Usage:**      

            O3.getEmissivity(12000, 100, 4, 2)         # (4, 2) transition

            O3.getEmissivity(10000, 10000, wave=5007)  # (4, 2) transition

            O3.getEmissivity(12000, 100)               # all transitions

            O3.getEmissivity([10000, 12000], [100, 500], 4, 2)

            O3.getEmissivity([10000, 12000], [100, 500])

        """
        if '{0}_{1}'.format(self.atom, wave) in BLEND_LIST:
            L = lambda wave: self.getEmissivity(tem, den, wave=wave, product=product)
            I = lambda lev_i, lev_j: self.getEmissivity(tem, den, lev_i=lev_i, lev_j=lev_j, product=product)
            try:
                res = eval(BLEND_LIST['{0}_{1}'.format(self.atom, wave)])
            except:
                self.log_.warn('{0} is not understood'.format(wave), calling=self.calling + 'getEmissivity')
                res = None
            return res
        self._test_lev(lev_i)
        self._test_lev(lev_j)
        tem = np.asarray(tem)
        den = np.asarray(den)
        if wave != -1:
            lev_i, lev_j = self.getTransition(wave)
        NLevels = self.NLevels
        if lev_i > NLevels or lev_j > NLevels:
            self.log_.error('The number of levels {} does not allow getting this emissivity ({}-{}). Consider changing the atomic data'.format(NLevels,lev_i, lev_j),
                          calling=self.calling) 
        if product:
            n_tem = tem.size
            n_den = den.size
            tem_ones = np.ones(n_tem)
            populations = self.getPopulations(tem, den, product=True)
            if ((lev_i == -1) and (lev_j == -1)):
                resultArray = np.zeros((NLevels, NLevels, n_tem, n_den))
                for i in range(NLevels):
                    lev_i = i + 1
                    j = i - 1 
                    while (j >= 0):
                        lev_j = j + 1
                        deltaE = (self._Energy[i] - self._Energy[j]) * CST.HPLANCK * CST.CLIGHT * 1.e8 
                        resultArray[i][j] = (deltaE * self._A[i, j] * populations[i].reshape(1, 1, n_tem, n_den) / 
                                             np.outer(tem_ones, den).reshape(1, 1, n_tem, n_den))
                        j -= 1
                return np.squeeze(resultArray)
            else:
                if (lev_i <= lev_j):
                    return 0.
                else:
                    i = lev_i - 1
                    j = lev_j - 1
                    deltaE = (self._Energy[i] - self._Energy[j]) * CST.HPLANCK * CST.CLIGHT * 1.e8 
                    return np.squeeze((populations[i] * deltaE * self._A[i, j]).reshape(1, 1, n_tem, n_den) / 
                                      np.outer(tem_ones, den).reshape(1, 1, n_tem, n_den))
        else:
            if tem.shape != den.shape:
                self.log_.error('tem and den must have the same shape', calling=self.calling)
                return None
            populations = self.getPopulations(tem, den, product=False)
            if (lev_i <= lev_j):
                return None
            else:
                i = lev_i - 1
                j = lev_j - 1
                deltaE = (self._Energy[i] - self._Energy[j]) * CST.HPLANCK * CST.CLIGHT * 1.e8 
                return populations[i] * deltaE * self._A[i, j] / den


    @profile
    def _getTemDen_1(self, int_ratio, tem= -1, den= -1, lev_i1= -1, lev_j1= -1, lev_i2= -1, lev_j2= -1,
                  wave1= -1, wave2= -1, maxError=1.e-3, method='nsect_recur', log=True, start_x= -1, end_x= -1,
                  to_eval=None, nCut=30, maxIter=20):

        ##
        # @todo manage blends
        self._test_lev(lev_i1)
        self._test_lev(lev_j1)
        self._test_lev(lev_i2)
        self._test_lev(lev_j2)
        tem = np.asarray(tem)
        den = np.asarray(den)
        if np.asarray(int_ratio).size != 1:
            shape = np.asarray(int_ratio).shape
            size = np.asarray(int_ratio).size
            result = np.zeros(size) 
            if np.asarray(tem).size != 1:
                if np.asarray(tem).shape != shape:
                    self.log_.error('getTemDen: int_ratio and tem/den must have the same size', calling=self.calling)
                    return None
                tem_ravel = np.asarray(tem).ravel()
                den_ravel = np.zeros(size) + den
            elif np.asarray(den).size != 1:
                if np.asarray(den).shape != shape:
                    self.log_.error('getTemDen: int_ratio and tem/den must have the same size', calling=self.calling)
                    return None
                den_ravel = np.asarray(den).ravel()
                tem_ravel = np.zeros(size) + tem
            else:
                den_ravel = np.zeros(size) + den
                tem_ravel = np.zeros(size) + tem
            int_ratio_ravel = np.asarray(int_ratio).ravel()
            for i in np.arange(size):
                result[i] = self._getTemDen_1(int_ratio_ravel[i], tem=tem_ravel[i], den=den_ravel[i],
                                           lev_i1=lev_i1, lev_j1=lev_j1, lev_i2=lev_i2, lev_j2=lev_j2,
                                           wave1=wave1, wave2=wave2, maxError=maxError, method=method,
                                           log=log, start_x=start_x, end_x=end_x,
                                           to_eval=to_eval)
            return result.reshape(shape)

        if wave1 != -1:
            lev_i1, lev_j1 = self.getTransition(wave1)
        if wave2 != -1:
            lev_i2, lev_j2 = self.getTransition(wave2)

        if to_eval is None:
            to_eval = 'I(' + str(lev_i1) + ',' + str(lev_j1) + ')/I(' + str(lev_i2) + ',' + str(lev_j2) + ')'


        if tem == -1:
            if start_x == -1:
                start_x = min(self.getTemArray(keep_unit=False))
                if log:
                    start_x = np.log10(start_x)
            if end_x == -1:
                end_x = max(self.getTemArray(keep_unit=False))
                if log:
                    end_x = np.log10(end_x)

            @profile
            def _func(x):
                """
                The function for which a root is looked for.
                It must return an array if x is an array, if an nsect-like method is used.
                The returned value is already normalized to the intensity ratio.

                """
                if log:
                    populations = self.getPopulations(10.**x, den)
                else:
                    populations = self.getPopulations(x, den)
                I = lambda lev_i, lev_j: (populations[lev_i - 1] * 
                                          (self._A[lev_i - 1, lev_j - 1] * 
                                           (self._Energy[lev_i - 1] - self._Energy[lev_j - 1])))
                L = lambda wave: (populations[self.getTransition(wave)[0] - 1] * 
                                  (self._A[self.getTransition(wave)[0] - 1, self.getTransition(wave)[1] - 1] * 
                                   (self._Energy[self.getTransition(wave)[0] - 1] - 
                                    self._Energy[self.getTransition(wave)[1] - 1])))
                result = eval(to_eval)
                return quiet_divide((result - int_ratio), int_ratio)

        elif den == -1:
            if start_x == -1:
                start_x = 1.e0
                if log: start_x = np.log10(start_x)
            if end_x == -1:
                end_x = 1e8
                if log: end_x = np.log10(end_x)

            @profile
            def _func(x):
                """
                The function for which a root is looked for.
                It must return an array if x is an array, if an nsect-like method is used.
                The returned value is already normalized to the intensity ratio.

                """
                if log:
                    populations = self.getPopulations(tem, pow(10., x))
                else:
                    populations = self.getPopulations(tem, x)
                I = lambda lev_i, lev_j: (populations[lev_i - 1] * 
                                          (self._A[lev_i - 1, lev_j - 1] * 
                                           (self._Energy[lev_i - 1] - self._Energy[lev_j - 1])))
                L = lambda wave: (populations[self.getTransition(wave)[0] - 1] * 
                                  (self._A[self.getTransition(wave)[0] - 1, self.getTransition(wave)[1] - 1] * 
                                   (self._Energy[self.getTransition(wave)[0] - 1] - 
                                    self._Energy[self.getTransition(wave)[1] - 1])))
                result = eval(to_eval)
                return quiet_divide((result - int_ratio), int_ratio)
        # improve exception handling (we must include cases where both tem, den = -1) 
        else:
            self.log_.error('ERROR in getTemDen: temperature and density cannot be simultaneously given',
                            calling=self.calling)

        if method == 'nsect_recur':
            """
            Recursive n-section method for finding a root
            It works by looking for the minumum of abs(f) using the fact that f(array) 
                returns an array

            """
            @profile
            def nsect_recur(f, x1, x2, nCut, maxIter, _iter=0):
                if _iter > maxIter:
                    return np.nan
                x = np.linspace(x1, x2, nCut)
                y = abs(f(x))
                x_min = np.argmin(y)
                if y[x_min] < maxError:
                    return x[x_min]
                else:
                    if x_min == 0:
                        x_min = 1
                    if x_min == nCut - 1:
                        x_min = nCut - 2
                    x1 = x[x_min - 1]
                    x2 = x[x_min + 1]
                    _iter = _iter + 1
                    #print(x1, x2)
                    return nsect_recur(f, x1, x2, nCut=nCut, maxIter=maxIter, _iter=_iter)

            result = nsect_recur(_func, start_x, end_x, nCut, maxIter)

        elif method == 'nsect_iter':
            """
            Iterative n-section method for finding a root (analogous to the bisection method)
            It works by looking for the minimum of abs(f) using the fact that f(array) returns an array

            """

            @profile
            def nsect_iter(f, x1, x2, nCut, maxIter):
                for i in range(maxIter):
                    x = np.linspace(x1, x2, nCut)
                    y = abs(f(x))
                    x_min = np.argmin(y)
                    if y[x_min] < maxError:
                        return x[x_min]
                    else:
                        if x_min == 0: x_min = 1
                        if x_min == nCut - 1: x_min = nCut - 2
                        x1 = x[x_min - 1]
                        x2 = x[x_min + 1]
                return np.nan

            result = nsect_iter(_func, start_x, end_x, nCut, maxIter)

        else:
            self.log_.error('ERROR in getTemDen: no valid method given', calling=self.calling)
            result = None

        if (log is True) and (result is not None):
            return pow(10., result)
        else:
            return result


    def _getTemDen_MP(self, int_ratio, tem= -1, den= -1, lev_i1= -1, lev_j1= -1, lev_i2= -1, lev_j2= -1,
                  wave1= -1, wave2= -1, maxError=1.e-3, method='nsect_recur', log=True, start_x= -1, end_x= -1,
                  to_eval=None, nCut=30, maxIter=20):

        if not config.INSTALLED['mp']:
            self.log_.error('_getTemDen_MP cannot be used in absence of multiprocessing package',
                          calling=self.calling)
            return None
        self._test_lev(lev_i1)
        self._test_lev(lev_j1)
        self._test_lev(lev_i2)
        self._test_lev(lev_j2)
        tem = np.asarray(tem)
        den = np.asarray(den)
        if np.asarray(int_ratio).size != 1:
            shape = np.asarray(int_ratio).shape
            size = np.asarray(int_ratio).size
            result = np.zeros(size) 
            if np.asarray(tem).size != 1:
                if np.asarray(tem).shape != shape:
                    self.log_.error('getTemDen: int_ratio and tem/den must have the same size', calling=self.calling)
                    return None
                tem_ravel = np.asarray(tem).ravel()
                den_ravel = np.zeros(size) + den
            elif np.asarray(den).size != 1:
                if np.asarray(den).shape != shape:
                    self.log_.error('getTemDen: int_ratio and tem/den must have the same size', calling=self.calling)
                    return None
                den_ravel = np.asarray(den).ravel()
                tem_ravel = np.zeros(size) + tem
            else:
                den_ravel = np.zeros(size) + den
                tem_ravel = np.zeros(size) + tem
            int_ratio_ravel = np.asarray(int_ratio).ravel()
        else:
            return self._getTemDen_1(int_ratio=int_ratio, tem=tem, den=den, lev_i1=lev_i1, lev_j1=lev_j1, lev_i2=lev_i2, lev_j2=lev_j2,
                  wave1=wave1, wave2=wave2, maxError=maxError, method=method, log=log, start_x=start_x,
                  end_x=end_x, to_eval=to_eval, nCut=nCut, maxIter=maxIter)

        Nprocs = config.Nprocs
        self.log_.message('number of CPUs = {0}'.format(Nprocs), calling=self.calling + '.getTemDenMP')
        gTDWorkerQ = Queue()
        gTDDoneQ = Queue()
        self.log_.message('Queues initialized', calling=self.calling + '.getTemDenMP')
        jobid = 0
        for int_rat1, tem1, den1 in zip(int_ratio_ravel, tem_ravel, den_ravel):
            gTDWorkerQ.put((jobid, int_rat1, tem1, den1))
            jobid += 1
        self.log_.message('put done', calling=self.calling + '.getTemDenMP')
        #gTDWorkerQSize = gTDWorkerQ.qsize() # this crash on OSX
        gTDWorkerQSize = size
        self.log_.message('Queue size {0}'.format(gTDWorkerQSize), calling=self.calling + '.getTemDenMP')


        gTDProcesses = []
        for i in range(Nprocs):
            p = Process(target=getTemDen_helper, args=(gTDWorkerQ, gTDDoneQ, self.atom, lev_i1, lev_j1, lev_i2, lev_j2,
                  wave1, wave2, maxError, method, log, start_x, end_x, to_eval, nCut, maxIter, self.NLevels))
            p.start()
            gTDProcesses.append(p)
        self.log_.message('processes started', calling=self.calling + '.getTemDenMP')

        #
        result = []
        for i in range(gTDWorkerQSize):
            result.append(gTDDoneQ.get())
        self.log_.message('Result obtained', calling=self.calling + '.getTemDenMP')

        for p in gTDProcesses:
            p.join(timeout=0.1)
        self.log_.message('Joined', calling=self.calling + '.getTemDenMP')

        for i in range(Nprocs):
            gTDWorkerQ.put('STOP')
        result.sort()
        to_return = np.array(result)[:, 1]
        return to_return.reshape(int_ratio.shape)


    @profile
    def _getTemDen_ANN(self, int_ratio, tem= -1, den= -1, lev_i1= -1, lev_j1= -1, lev_i2= -1, lev_j2= -1,
                  wave1= -1, wave2= -1, start_x= -1, end_x= -1, to_eval=None):

        if not config.INSTALLED['ai4neb']:
            self.log_.error('_getTemDen_ANN cannot be used in absence of ai4neb package',
                          calling=self.calling)
            return None

        self._test_lev(lev_i1)
        self._test_lev(lev_j1)
        self._test_lev(lev_i2)
        self._test_lev(lev_j2)
        if wave1 != -1:
            lev_i1, lev_j1 = self.getTransition(wave1)
        if wave2 != -1:
            lev_i2, lev_j2 = self.getTransition(wave2)

        if to_eval is None:
            to_eval = 'I(' + str(lev_i1) + ',' + str(lev_j1) + ')/I(' + str(lev_i2) + ',' + str(lev_j2) + ')'

        tem = np.asarray(tem)
        den = np.asarray(den)


        X1_test = np.asarray(int_ratio).ravel()
        if (tem == -1).any(): # Looking for Tem
            if np.asarray(den).size == 1: # Single density
                N_train = self.ANN_n_temden
                X2_test = np.zeros_like(X1_test) + den
                X2_train = np.zeros(N_train) + den
            else: # Multiple densities
                if np.asarray(den).shape != np.asarray(int_ratio).shape:
                    self.log_.error('getTemDen: int_ratio and tem/den must have the same size', calling=self.calling)
                    return None
                N_train = self.ANN_n_temden**2
                X2_test = np.asarray(den).ravel()
                X2_train = np.min(den) + np.random.rand(N_train) * (np.max(den) - np.min(den)) 

            if start_x == -1:
                start_x = min(self.getTemArray(keep_unit=False))
            if end_x == -1:
                end_x = max(self.getTemArray(keep_unit=False))
            y_train = np.logspace(np.log10(start_x), np.log10(end_x), N_train)

            def I(lev_i, lev_j):
                return self.getEmissivity(tem=y_train, den=X2_train, lev_i= lev_i, lev_j= lev_j, product=False) 
            def L(wave):
                return self.getEmissivity(tem=y_train, den=X2_train, wave=wave, product=False) 

        elif (den == -1).any(): # Looking for density
            if np.asarray(tem).size == 1:
                N_train = self.ANN_n_temden
                X2_test = np.zeros_like(X1_test) + tem
                X2_train = np.zeros(N_train) + tem
            else:
                if np.asarray(tem).shape != np.asarray(int_ratio).shape:
                    self.log_.error('getTemDen: int_ratio and tem/den must have the same size', calling=self.calling)
                    return None
                N_train = self.ANN_n_temden**2
                X2_test = np.asarray(tem).ravel()
                X2_train = np.min(tem) + np.random.rand(N_train) * (np.max(tem) - np.min(tem)) 

            if start_x == -1:
                start_x = 1.e0
            if end_x == -1:
                end_x = 1e8
            y_train = np.logspace(np.log10(start_x), np.log10(end_x), N_train)
            def I(lev_i, lev_j):
                return self.getEmissivity(tem=X2_train, den=y_train, lev_i= lev_i, lev_j= lev_j, product=False) 
            def L(wave):
                return self.getEmissivity(tem=X2_train, den=y_train, wave=wave, product=False) 
        else:
            self.log_.error('getTemDen: one of tem or den must be unset', calling=self.calling)

        X1_train = eval(to_eval)
        X = np.array((X1_train, X2_train)).T
        y = np.log10(y_train)
        self.ANN = manage_RM(X_train=X, y_train=y, **self.ANN_inst_kwargs)
        self.ANN.init_RM(**self.ANN_init_kwargs)
        self.ANN.train_RM()
        # set the test values to the one we are looking for
        X_test = np.array((X1_test, X2_test)).T
        self.ANN.set_test(X_test)
        # predict the result and denormalize them
        self.ANN.predict()
        to_return = np.ones_like(int_ratio) * np.nan
        to_return.ravel()[self.ANN.isfin] = self.ANN.pred
        to_return = 10**to_return
        return to_return


    @profile
    def getTemDen(self, int_ratio, tem= -1, den= -1, lev_i1= -1, lev_j1= -1, lev_i2= -1, lev_j2= -1,
                  wave1= -1, wave2= -1, maxError=1.e-3, method='nsect_recur', log=True, start_x= -1, end_x= -1,
                  to_eval=None, nCut=30, maxIter=20):
        """
        Return either the temperature or the density given the other variable for a selected line ratio 
            of known intensity.
        The line ratio can involve two or more than two lines. 
        In the first case (only two lines), it can be specified giving either two transitions 
            (four atomic levels, i.e. two for each transition), or two wavelengths.
        In the general case (any number of lines), it can be specified as an algebraic expression 
            to be evaluated, involving either atomic levels or wavelengths.
        An array of values, rather than a single value, can also be given, in which case the result 
            will also be an array.

        Parameters:
           int_ratio:    intensity ratio of the selected transition
           tem:          electronic temperature
           den:          electronic density
           lev_i1:       upper level of 1st transition
           lev_j1:       lower level of 1st transition
           lev_i2:       upper level of 2nd transition
           lev_j2:       lower level of 2nd transition
           wave1:        wavelength of 1st transition
           wave2:        wavelength of 2nd transition
           maxError:     tolerance on difference between input and computed ratio 
           method:       numerical method for finding the root (nsect_recur, nsect_iter)
           log:          switch of log (default = True). start_x and end_x are using this parameter.
           start_x:      lower end of the interval to explore. (default: lower end of collision 
                            strength temperature array for temperature, 1 if density)
           end_x:        higher end of the interval to explore. (default: higher end of collision 
                            strength temperature array for temperature, 1e8 if density)
           to_eval:      expression to be evaluated, using either I (for transitions identified 
                            through atomic levels) or L (for transitions identified through wavelengths)
           nCut:        number of sections in which each step is cut. 2 would be dichotomy.
           maxIter:     maximum number of iterations

        **Usage:** 

            O3.getTemDen(150., den=100., wave1=5007, wave2=4363, maxError=1.e-2)

            O3.getTemDen(150., den=100., to_eval = '(I(4,3) + I(4,2) + I(4,1)) / I(5,4)')

            N2.getTemDen(150., den=100., to_eval = '(L(6584) + L(6548)) / L(5755)')

            O3.getTemDen([0.02, 0.04], den=[1.e4, 1.1e4], to_eval="I(5, 4) / (I(4, 3) + I(4, 2))")
        """
        if method == 'ANN':
            return self._getTemDen_ANN(int_ratio=int_ratio, tem=tem, den=den, lev_i1=lev_i1, lev_j1=lev_j1, lev_i2=lev_i2, lev_j2=lev_j2,
                  wave1=wave1, wave2=wave2, start_x=start_x, end_x=end_x, to_eval=to_eval)            
        elif config._use_mp:
            return self._getTemDen_MP(int_ratio=int_ratio, tem=tem, den=den, lev_i1=lev_i1, lev_j1=lev_j1, lev_i2=lev_i2, lev_j2=lev_j2,
                  wave1=wave1, wave2=wave2, maxError=maxError, method=method, log=log, start_x=start_x,
                  end_x=end_x, to_eval=to_eval, nCut=nCut, maxIter=maxIter)
        else:
            return self._getTemDen_1(int_ratio=int_ratio, tem=tem, den=den, lev_i1=lev_i1, lev_j1=lev_j1, lev_i2=lev_i2, lev_j2=lev_j2,
                  wave1=wave1, wave2=wave2, maxError=maxError, method=method, log=log, start_x=start_x,
                  end_x=end_x, to_eval=to_eval, nCut=nCut, maxIter=maxIter)

    def getIonAbundance(self, int_ratio, tem, den, lev_i= -1, lev_j= -1, wave= -1, to_eval=None, 
                        Hbeta=100., tem_HI=None, den_HI=None, extrapHbeta=False, use_ANN=False):
        """
        Compute the ionic abundance relative to H+ given the intensity of a line or sum of lines, 
        the temperature, and the density. 
        The line can be specified as a transition (i.e., giving the two atomic level involved), 
        as a wavelength, or as an algebraic expression. In the last case, a sum of lines 
        can also be supplied.

        Parameters:
            int_ratio:    relative line intensity (default normalization: Hbeta = 100). 
                            May be an array.
            tem:          electronic temperature in K. May be an array.
            den:          electronic density in cm^-3. May be an array.
            lev_i:        upper level of transition
            lev_j:        lower level of transition
            wave:         wavelength of transition. Takes precedence on lev_i and lev_j if set, 
                            ignored otherwise 
            to_eval:      expression to be evaluated. Takes precedence on wave if set, 
                            ignored otherwise.
            Hbeta:        line intensity normalization at Hbeta (default Hbeta = 100)

            tem_HI:       HI temperature. If not set, tem is used.
            extrapHbeta: [False] if set to True, Hbeta is extrapolated at low Te using Aller 82 function
            use_ANN: [False] if set to True, use Machine Learning to compute line emissivities

        **Usage:**

            O3.getIonAbundance(100, 1.5e4, 100., wave=5007)

            O3.getIonAbundance(130, 1.5e4, 100., to_eval='I(4,3) + I(4,2)')

        """
        if tem_HI is None:
            tem_HI = tem
        if den_HI is None:
            den_HI = den
        self._test_lev(lev_i)
        self._test_lev(lev_j)
        if np.ndim(tem) != np.ndim(den):
            self.log_.error('ten and den must have the same shape', calling=self.calling)
            return None
        if ((np.squeeze(np.asarray(int_ratio)).shape != np.squeeze(np.asarray(tem)).shape) | 
            (np.squeeze(np.asarray(den)).shape != np.squeeze(np.asarray(tem)).shape)):
            self.log_.warn('int_ratio, tem and den must does not have the same shape', calling=self.calling)
        if (lev_i == -1) & (lev_j == -1) & (wave == -1) & (to_eval is None):
            self.log_.error('At least one of lev_i, lev_j, wave or to_eval must be supplied', calling=self.calling)
            return None
        if to_eval == None:
            if wave != -1:
                lev_i, lev_j = self.getTransition(wave)     
            to_eval = 'I(' + str(lev_i) + ',' + str(lev_j) + ')' 
        I = lambda lev_i, lev_j: self.getEmissivity(tem, den, lev_i, lev_j, product=False, use_ANN=use_ANN)
        L = lambda wave: self.getEmissivity(tem, den, wave=wave, product=False, use_ANN=use_ANN)
        try:
            emis = eval(to_eval)
        except:
            self.log_.error('Unable to eval {0}'.format(to_eval), calling=self.calling)
            return None
        #int_ratio is in units of Hb = Hbeta keyword
        if extrapHbeta:
            HbEmis = getHbEmissivity(tem= tem_HI, den=den_HI)
        else:
            HbEmis = getRecEmissivity(tem_HI, den_HI, 4, 2, atom='H1', product=False)
        ionAbundance = ((int_ratio / Hbeta) * (HbEmis / emis))
        return ionAbundance


    def printIonic(self, tem=None, den=None, printA=False, printPop=True, printCrit=True):
        """ 
        Print miscellaneous information (wavelengths, level populations, emissivities, 
            critical densities) for given physical conditions.
        If an electron temperature is given, level critical densities can be printed 
            (using printCrit=True)
        If an electron density is also given, line emissivities (also for Hbeta) are printed and level 
            populations can be printed (using printPop=True)

        Parameters:
            tem:          temperature
            den:          density
            printA:       also print transition probabilities (default=False)
            printPop:     also print level populations (needs tem and den)
            printCrit:    also print critical densities (needs tem)

        **Usage:**

            O3.printIonic()

            O3.printIonic(printA=True)

            O3.printIonic(tem=10000., printCrit=True)

            O3.printIonic(tem=10000., den=1e3, printA=True, printPop=True, printCrit=True)

        """
        print('elem = %s' % self.elem)
        print('spec = %i' % self.spec)
        if tem is not None:
            print('temperature = %6.1f K' % tem)
        if den is not None:
            print('density = %6.1f cm-3' % den)
        print("")
        if printPop and ((tem is None) or (den is None)):
            self.log_.warn('Cannot print populations as tem or den is missing', calling=self.calling)
            printPop = False
        if printCrit and (tem is None):
            self.log_.warn('Cannot print critical densities as tem is missing', calling=self.calling)
            printCrit = False
        to_print = ''
        if printPop:
            to_print += 'Level   Populations  '
        if printCrit:
            to_print += 'Critical densities'
        if to_print != '':
            print(to_print)
        if printCrit:
            critdens = self.getCritDensity(tem)
        if printPop:
            pop = self.getPopulations(tem, den)
        for i in range(0, self.NLevels):
            lev_i = i + 1
            to_print = 'Level %1i:  ' % (lev_i)
            if printPop:
                to_print += "%.3E  " % (pop[i])
            if printCrit:
                to_print += "%.3E" % critdens[i]
            if printPop or printCrit:
                print(to_print)
        if printPop or printCrit:
            print('')

        if (tem is not None) and (den is not None):
            emis = self.getEmissivity(tem, den)
        for i in range(1, self.NLevels):
            if printA:
                for j in range(i):
                    to_print = "{0:.3E}   ".format(np.float64(self.getA(i + 1, j + 1)))
                    print(to_print, end="")
                print("")
            for j in range(i):
                if self.wave_Ang[i, j] > 10000.:
                    to_print = "%10.2fm " % (self.wave_Ang[i, j] / 1e4)
                else:
                    to_print = "%10.2fA " % self.wave_Ang[i, j]
                print(to_print, end="")
            print("")
            for j in range(i):
                print("    (%1i-->%1i) " % (i + 1, j + 1), end="")
            print("")
            if (tem is not None) and (den is not None):
                for j in range(i):
                    print("  %.3E " % emis[i,j], end="")
            print("\n")
        if (tem is not None) and (den is not None):
            try:
                H1 = RecAtom('H', 1)
                print("# H-beta volume emissivity:")
                print("%.3E N(H+) * N(e-)  (erg/s)" % H1.getEmissivity(tem, den, 4, 2))
            except:
                pass

    def printTemDen(self, int_ratio, tem= -1, den= -1, lev_i1= -1, lev_j1= -1, lev_i2= -1, lev_j2= -1, wave1= -1, wave2= -1,
                    maxError=1.e-3, method='nsect_recur', log=True, start_x= -1, end_x= -1, to_eval=None,
                    nCut=30, maxIter=20):
        """ 
        Print result of getTemDen function. See getTemDen for more details.



        Parameters:
            int_ratio:    intensity ratio of the selected transition
            tem:          electronic temperature
            den:          electronic density
            lev_i1:       upper level of 1st transition
            lev_j1:       lower level of 1st transition
            lev_i2:       upper level of 2nd transition
            lev_j2:       lower level of 2nd transition
            wave1:        wavelength of 1st transition
            wave2:        wavelength of 2nd transition
            maxError:     tolerance on difference between input and computed ratio 
            method:       numerical method for finding the root (nsect_recur, nsect_iter)
            log:          log switch (default = True)
            start_x:      lower end of the interval to explore (default: lower end of collision 
                            strength temperature array)
            end_x:        higher end of the interval to explore (default: higher end of collision 
                            strength temperature array)
            to_eval:      expression to be evaluated, using either I (for transitions identified through 
                            atomic levels) or L (for transitions identified through wavelengths)
            nCut:        number of sections in which each step is cut. 2 would be dichotomy.
            maxIter:     maximum number of iterations

        **Usage:**

            O3.printTemDen(100, tem=10000, wave1=5007, wave2=4363)

        """
        if tem == -1:
            option = 'temperature'
            assume = den
            assume_str = 'density'
            assume_unit = 'cm-3'
            unit = 'K'
        if den == -1:
            option = 'density'
            assume = tem
            assume_str = 'temperature'
            assume_unit = 'K'
            unit = 'cm-3'

        result = self.getTemDen(int_ratio, tem=tem, den=den, lev_i1=lev_i1, lev_j1=lev_j1, lev_i2=lev_i2, lev_j2=lev_j2,
                                wave1=wave1, wave2=wave2, maxError=maxError, method=method, log=log, start_x=start_x,
                                end_x=end_x, to_eval=to_eval, nCut=nCut, maxIter=maxIter)
        print('Ion = %s' % self.elem + " " + int_to_roman(self.spec))
        print('Option = %s' % option)
        print('Assumed %s = %.0f %s' % (assume_str, assume, assume_unit))
        if to_eval is None:
            print('Assumed I(%i)/I(%i) ratio = %.0f' % (wave1, wave2, int_ratio))
        else:
            print('Assumed %s = %.0f' % (to_eval, int_ratio))
#        print 'method = %s' % method
#        print 'maxError on ratio %f' % maxError
        print('Calculated %s = %.0f %s' % (option, result, unit))


    def plotEmiss(self, tem_min=1000, tem_max=30000, ionic_abund=1.0, den=1e3, style='-',
                  legend_loc=4, temLog=False, plot_total=False, plot_only_total=False, legend=True,
                  total_color='black', total_label='TOTAL', ax=None):
        """ 
        Plot the emissivity as a function of temperature of all the lines of the selected atom.  

        Parameters:
            tem_min:         minimum value of the temperature range to span (default=1000)
            tem_max:         maximum value of the temperature range to span (default=30000)
            ionic_abund:     relative ionic abundance (default = 1.0)
            den:             electron density
            style:           line style of the plot (default: '-' [solid line])
            legend_loc:      localization of the legend (default: 4 = lower right; see plt.legend 
                                for more details)
            temLog:          linear (False) or logarithmic temperature axis (default = False)
            plot_total:      flag to also plot total emissivity (default = False)
            plot_only_total: flag to only plot total emissivity (default = False)
            legend:          flag to place legend (default = True)
            total_color:     color of the total emissivity (default = 'black')
            total_label:     label of the total emissivity (default = 'TOTAL')
            ax:              axis where to send the plot. If None, a new axis is done

        **Usage:**

            O3.plotEmiss(tem_min=10000, tem_max=20000)

        """
        if ax is None:
            f, ax = plt.subplots()
        if not config.INSTALLED['plt']: 
            self.log_.error('Matplotlib not available, no plot', calling=self.calling + '.plot')
            return None
        tem = np.logspace(np.log10(tem_min), np.log10(tem_max), 1000)
        total_emis = np.zeros_like(tem)
        for wave in self.lineList:
            lev_i, lev_j = self.getTransition(wave)
            if (lev_i <= self.NLevels) and (lev_j <= self.NLevels):
                color = ((np.log10(wave) - np.log10(np.min(self.lineList))) / 
                         (np.log10(np.max(self.lineList)) - np.log10(np.min(self.lineList)))) ** 0.4
                c = cm.jet(color, 1)
                if temLog:
                    x_to_plot = np.log10(tem)
                else:
                    x_to_plot = tem
                y_to_plot = ionic_abund * self.getEmissivity(tem, den, wave=wave)
                if not plot_only_total:
                    if (y_to_plot[0] > 0.):
                        ax.plot(x_to_plot, np.log10(y_to_plot),
                             label='{0:.0f}'.format(wave), color=c, linestyle=style)
                total_emis += y_to_plot
        if plot_total:
            ax.plot(x_to_plot, np.log10(total_emis),
                     label=total_label, color=total_color, linewidth=3, linestyle=style)
        if legend:
            ax.legend(loc=legend_loc)
        if temLog:
            ax.set_xlabel('log(T[K])')
        else:
            ax.set_xlabel('T[K]')
        ax.set_ylabel('log [erg.cm3/s]')
        ax.set_title('Line emissivities')

    def plotGrotrian(self, tem=1e4, den=1e2, thresh_int=1e-3, unit='eV', detailed=False, ax=None):
        """
        Draw a Grotrian plot of the selected atom, labelling only lines above a
        pecified intensity threshold (relative to the most intense line). 
        For ground state levels, the Russell-Saunders term symbol is also given.

        Parameters:
            tem:          temperature at which the intensity threshold is to be computed 
            den:          density at which the intensity threshold is to be computed 
            thresh_int:   intensity threshold (relative to the most intense line, default: 1.e-3)
            unit:         one of 'eV' (default), '1/Ang' or 'Ryd'
            ax:           axis where to plot the result

        Usage:

            **O3.plotGrotrian()**

        """
        if ax is None:
            f, ax = plt.subplots()
        if unit not in ['eV', 'Ryd', '1/Ang']:
            self.log_.error('Unit {0} not available'.format(unit))
            return None
        if not config.INSTALLED['plt']: 
            self.log_.error('Matplotlib not available, no plot', calling=self.calling + '.plot')
            return None
        color_list = ['b', 'r', 'y', 'c', 'm', 'g']
        energies = self.getEnergy(unit=unit)

        # VL 16 Jul 2013 - Detect level inversion, just for warning        
        level_multiplet = [0]
        multiplets = []
        if self.NIST is not None:
            term = []; j = []; en = []
            for item in self.NIST:
                term.append(item[1])
                j.append(item[2])
                en.append(item[3])
            sorted_indx = np.argsort(en) 
            term = np.array(term)[sorted_indx]
            j = np.array(j)[sorted_indx]
            en = np.array(en)[sorted_indx]
            for i in np.arange(1, len(en)):
                if (term[i] == term[i-1]):
                    level_multiplet.append(i)
                else:
                    multiplets.append(level_multiplet) 
                    level_multiplet = [i]
            multiplets.append(level_multiplet) # append last multiplet
# Mistakenly rounds off fractional J values. Corrected 26/12/2014            
#            levelLabels = ['$^{{{0}}}${1}$_{{{2:.0f}}}$'.format(l['term'][0],l['term'][1],l['J']) for l in self.NIST]
            levelLabels = []
            for l in self.NIST:
                if Fraction(l['J']).denominator == 1:
                    levelLabels.append('$^{{{0}}}${1}$_{{{2}}}$'.format(l['term'][0], l['term'][1], Fraction(l['J']).numerator))
                else:
                    levelLabels.append('$^{{{0}}}${1}$_{{{2}/{3}}}$'.format(l['term'][0], l['term'][1], Fraction(l['J']).numerator, Fraction(l['J']).denominator))
        else:
            delta_e_max = 1.e-5  # Arbitrary limit to define hyperfine structure and identify multiplets 
            for i in np.arange(1, len(energies)):
                if (self.getEnergy()[i] - self.getEnergy()[i - 1] < delta_e_max):
                    # if levels close, append level to multiplet
                    level_multiplet.append(i) 
                else:
                    # if levels separated, add current multiplet to array and start a new multiplet
                    multiplets.append(level_multiplet) 
                    level_multiplet = [i]
            multiplets.append(level_multiplet) # append last multiplet
            warn_label = []
            levelLabels = gsLevelDict[self.gs]
            for i_multi in np.arange(len(multiplets)):
                stat_weights = []
                # check each multiplet for inversion separately
                for i_level in multiplets[i_multi]:
                    latex_sw = levelLabels[i_level]
                    sw = eval(latex_sw.split('$')[-2].replace('_', '').replace('{', '').replace('}', '.') + '*2.+1.')
                    stat_weights.append(sw)
                if (stat_weights != [self.getStatWeight()[k] for k in multiplets[i_multi]]):
                    warn_label.append(i_multi)
                    to_print = '\nLevel inversion in multiplet {0} of {1}'\
                             '\nThe labels of levels {2} are displayed in the wrong order' + \
                             '\nAssumed statistical weights: {3}' + \
                             '\nStatistical weights of data: {4}\n'
                    self.log_.warn(to_print.format(i_multi + 1, self.atom, multiplets[i_multi], 
                                                 stat_weights, [self.getStatWeight()[k] for k in multiplets[i_multi]]), 
                                 calling=self.calling + '.plot')

        # where level starts in the plot

        x_span = 0.75
        x_0 = (1 - x_span) / 4.    
        dx = 0.005
        max_en = np.max(energies)
        blow = 0.02 * max_en # blowup scale for multiplets
        ax.set_xlim((0, 1.))
        ax.set_ylim((np.max(energies) * -0.05, max_en * 1.05))
        ax.set_title('[{0} {1}]'.format(self.elem, int_to_roman(self.spec)))

        # Blow up of multiplets in the plot
        i_tot = 0
        for i_multi in np.arange(len(multiplets)):
            shift = (1-len(multiplets[i_multi])) / 2.
            for i in np.arange(len(multiplets[i_multi])):
                y = energies[multiplets[i_multi][i]] + shift * blow
                ax.plot([x_0, 1.5 * x_0, 1.6 * x_0, x_0 + x_span], 
                         [y, y, energies[multiplets[i_multi][i]], 
                          energies[multiplets[i_multi][i]]], lw = 1.2, 
                         color = color_list[np.mod(multiplets[i_multi][i], len(color_list))])
                ax.text(x_span + x_0 + dx, y, '{0:7.4f}'.format(energies[multiplets[i_multi][i]]), size='small', 
                         horizontalalignment='left', verticalalignment='center')
                try:
                    if (detailed is False):
                        ax.text(dx, y, levelLabels[i_tot], size='medium', verticalalignment='center')
                    else:
                        ax.text(dx, y, str(i_tot+1) + ": " + levelLabels[i_tot] , size='medium', verticalalignment='center', 
                                color = color_list[np.mod(multiplets[i_multi][i], len(color_list))])
                    i_tot += 1
                except:
                    pass
                shift += 1
        ax.text(1 - dx / 2., max(energies) * 0.5, 'E [{0:s}] '.format(unit), horizontalalignment='right', color='blue')
        ax.set_xlabel('Ground-state configuration: {0}'.format(self.gs), color="#004400")

        ax.xaxis.set_ticks_position("none")
        ax.yaxis.set_ticks_position("none")
        ax.xaxis.set_ticklabels([])
        ax.yaxis.set_ticklabels([])

        all_emis = self.getEmissivity(tem, den)
        emis_max = np.max(all_emis)
        N_lines = (self.getEmissivity(1e4, 1e3) > (emis_max * thresh_int)).sum() # number of lines plotted
        x_pad = 0.1 * (x_span - 0.6 * x_0)     
        if N_lines > 1:
            delta_x = (x_span - 2 * x_pad) / (N_lines - 1)
            x = 1.6 * x_0 + 0.5 * x_pad
        else:
            delta_x = 0
            x = (1.6 * x_0 + x_span) / 2.
        cc = colors.ColorConverter()
        for j in np.arange(self.NLevels - 1) + 2:
            for i in np.arange(j - 1) + 1:
                emis = all_emis[j-1, i-1]
                if emis > (emis_max * thresh_int):
                    N_seg = 1000 #number of segments to draw emission line, to make it look smooth
                    xx = np.ones(N_seg+1) * x  # x coord of segmente making up one line
                    yy = np.linspace(self.getEnergy(i, unit=unit), self.getEnergy(j, unit=unit), N_seg+1)
                    scale = np.linspace(0, 1, N_seg+1)
                    alpha =  np.tanh((2*scale-1)+1)  # to make alpha vary as a smooth step function
                    points = np.array([xx, yy]).T.reshape(-1, 1, 2) 
                    segments = np.concatenate([points[:-1], points[1:]], axis=1) 
                    cmap1 = []
                    cmap2 = []
                    for seg in segments:
                            yy0 = seg.mean(0)[1] 
                            alpha0 = np.interp(yy0, yy, alpha)
                            rgb1 = cc.to_rgb(color_list[np.mod(j-1, len(color_list))]) 
                            rgb2 = cc.to_rgb(color_list[np.mod(i-1, len(color_list))]) 
                            cmap1.append([rgb1[0], rgb1[1], rgb1[2], alpha0]) 
                            cmap2.append([rgb2[0], rgb2[1], rgb2[2], 1-alpha0])
                    lc1 = LineCollection(segments, linewidths=3.5)
                    lc1.set_color(cmap1) 
                    lc2 = LineCollection(segments, linewidths=3.5)
                    lc2.set_color(cmap2) 
                    ax.add_collection(lc1) 
                    ax.add_collection(lc2) 
                    if self.wave_Ang[j - 1, i - 1] > 1e4:
                        to_print = '{0:.1f}m'.format(self.wave_Ang[j - 1, i - 1] / 1e4) + ' '
                    else:
                        to_print = '{0:.1f}A'.format(self.wave_Ang[j - 1, i - 1]) + ' '
                    ax.text(x + 0.05 * delta_x, self.getEnergy(j, unit=unit)-blow/2., to_print, size='small', rotation=90, verticalalignment='top')
                    x = x + delta_x

        # issue warning on plot if level inversion 
        try:
            for i in warn_label:
                ax.text(0, self.getEnergy(multiplets[i][0]+1, unit=unit), 'Warning ', ha='right', color='red')
        except:
            pass


    def __repr__(self):
        return 'Atom {0}{1} from {2} and {3}'.format(self.elem, self.spec, self.atomFile, self.collFile)

__init__(elem=None, spec=None, atom=None, OmegaInterp='linear', noExtrapol=False, NLevels=None)

Atom constructor

Parameters:

Name Type Description Default
elem

symbol of the selected element

None
spec

ionization stage in spectroscopic notation (I = 1, II = 2, etc.)

None
atom

ion (e.g. 'O3').

None
OmegaInterp

option "kind" from scipy.interpolate.interp1d method: 'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'previous', 'next', where 'zero', 'slinear', 'quadratic' and 'cubic' refer to a spline interpolation of zeroth, first, second or third order; 'previous' and 'next' simply return the previous or next value of the point. "Cheb" works only for fits files for historical reasons.

'linear'
noExtrapol

if set to False (default), Omega will be extrapolated above and below the highest and lowest temperatures where it is defined. If set to True a NaN will be return.

False

Usage: O3 = pn.Atom('O',3)

N2 = pn.Atom(atom='N2')

S2 = pn.Atom(atom='S2', OmegaInterp='linear')
Source code in pyneb/core/pynebcore.py
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
@profile
def __init__(self, elem=None, spec=None, atom=None, OmegaInterp='linear', noExtrapol = False, NLevels=None):
    """
    Atom constructor

    Parameters:
        elem:          symbol of the selected element
        spec:          ionization stage in spectroscopic notation (I = 1, II = 2, etc.)
        atom:          ion (e.g. 'O3').
        OmegaInterp:   option "kind" from scipy.interpolate.interp1d method: 
                        'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'previous', 'next', 
                        where 'zero', 'slinear', 'quadratic' and 'cubic' refer to a spline interpolation of 
                        zeroth, first, second or third order; 'previous' and 'next' simply return the 
                        previous or next value of the point. 
                        "Cheb" works only for fits files for historical reasons.
        noExtrapol:    if set to False (default), Omega will be extrapolated above and below
                        the highest and lowest temperatures where it is defined. If set to True
                        a NaN will be return.

    **Usage:**
        O3 = pn.Atom('O',3)

        N2 = pn.Atom(atom='N2')

        S2 = pn.Atom(atom='S2', OmegaInterp='linear')
    """        
    self.log_ = log_
    self.type = 'coll'
    self.is_valid = True
    if atom is not None:
        self.atom = str.capitalize(atom)
        self.elem = parseAtom(self.atom)[0]
        self.spec = int(parseAtom(self.atom)[1])
    else:
        if elem is None:
            self.log_.error('At least elem or atom needs to be given', calling='Atom')
        if elem[0].isalpha():
            self.elem = str.capitalize(elem)
        else:
            self.elem = elem
        self.spec = int(spec)
        self.atom = self.elem + str(self.spec)
    self.name = sym2name[self.elem]
    try:
        self.Z = Z[self.elem]
    except:
        self.Z = -1
    if self.elem in IP:
        if self.spec == 0:
            self.IP = -1
            self.IP_up = -1
        elif self.spec == 1:
            self.IP = 0
            try:
                self.IP_up = IP[self.elem][self.spec-1]
            except:
                self.IP = -1                    
        else:
            try:
                self.IP = IP[self.elem][self.spec-2]
            except:
                self.IP = -1
            try:
                self.IP_up = IP[self.elem][self.spec-1]
            except:
                self.IP = -1                    
    else:
        self.IP = -1
        self.IP_up = -1
    self.calling = 'Atom ' + self.atom
    self.log_.message('Making atom object for {0} {1}'.format(self.elem, self.spec), calling=self.calling)
    self.NLevels = NLevels
    dataFile = atomicData.getDataFile(self.atom, data_type='atom')
    if dataFile is None:
        self.atomFileType = None
    else:
        self.atomFileType = dataFile.split('.')[-1]
    if self.atomFileType == 'fits':
        self.AtomData = _AtomDataFits(elem=self.elem, spec=self.spec, atom=self.atom, NLevels=self.NLevels)
    elif self.atomFileType == 'dat':
        self.AtomData = _AtomDataAscii(elem=self.elem, spec=self.spec, atom=self.atom, NLevels=self.NLevels)
    elif self.atomFileType == 'chianti':
        self.AtomData = _AtomChianti(elem=self.elem, spec=self.spec, atom=self.atom, NLevels=self.NLevels)
    elif self.atomFileType == 'stout':
        self.AtomData = _AtomDataStout(elem=self.elem, spec=self.spec, atom=self.atom, NLevels=self.NLevels)
    elif self.atomFileType is None:
        self.AtomData = _AtomDataNone()
        self.is_valid = False
    else:
        self.log_.error('Atom file extensions must be fits, dat or chianti')

    self.atomFile = self.AtomData.atomFile
    self.atomPath = self.AtomData.atomPath
    self.atomFitsFile = self.atomFile # Obsolete
    self.atomFitsPath = self.atomPath # Obsolete
    self.wave_Ang = self.AtomData.wave_Ang
    self.getStatWeight = self.AtomData.getStatWeight
    self.getEnergy = self.AtomData.getEnergy
    self.atomNLevels = self.AtomData.NLevels


    dataFile = atomicData.getDataFile(self.atom, data_type='coll')
    if dataFile is None:
        self.collFileType = None
    else:
        self.collFileType = dataFile.split('.')[-1]
    if self.collFileType == 'fits':
        self.CollData = _CollDataFits(elem=self.elem, spec=self.spec, atom=self.atom, 
                                     OmegaInterp=OmegaInterp, noExtrapol = noExtrapol, NLevels=self.NLevels)
    elif self.collFileType == 'dat':
        self.CollData = _CollDataAscii(elem=self.elem, spec=self.spec, atom=self.atom, 
                                      OmegaInterp=OmegaInterp, noExtrapol = noExtrapol, NLevels=self.NLevels)
    elif self.collFileType == 'chianti':
        self.CollData = _CollChianti(elem=self.elem, spec=self.spec, atom=self.atom, NLevels=self.NLevels)
    elif self.collFileType == 'stout':
        self.CollData = _CollDataStout(elem=self.elem, spec=self.spec, atom=self.atom, NLevels=self.NLevels)            
    elif self.collFileType is None:
        self.CollData = _CollDataNone()
        self.is_valid = False
    try:
        self.CollHeader = self.CollData.CollHeader
    except:
        pass
    if "comments" not in self.CollData.__dict__.keys():
        self.CollData.comments = []
    self.getOmegaArray = self.CollData.getOmegaArray
    self.getTemArray = self.CollData.getTemArray
    self.collFile = self.CollData.collFile
    self.collPath = self.CollData.collPath
    self.collFitsFile = self.collFile # Obsolete
    self.collFitsPath = self.collPath # Obsolete
    self.collNLevels = self.CollData.NLevels
    self.tem_units = self.CollData.tem_units

    self.NLevels = np.min((self.atomNLevels, self.collNLevels))

    self.gs = gsFromAtom(self.atom)
    try:
        self.AtomHeader = self.AtomData.AtomHeader
    except:
        self.AtomHeader = None
    try:
        self.NIST = self.AtomData.NIST
    except:
        try:
            self.NIST = getLevelsNIST(self.atom, self.NLevels)
        except:
            self.NIST = None

    self.lineList = []
    for i in np.arange(self.NLevels):
        for j in np.arange(i):
            self.lineList.append(self.wave_Ang[i][j])
    self.lineList = np.array(self.lineList)

    self.energy_Ryd = quiet_divide(CST.RYD_ANG, self.wave_Ang)
    self.energy_eV = CST.RYD_EV * self.energy_Ryd

    self._A = self.getA() # index = quantum number - 1
    self._Energy = self.getEnergy() # Angstrom^-1
    self._StatWeight = self.getStatWeight()
    if self.NLevels > 0:
        self.EnergyNLevels = len(self._Energy)
    else:
        self.EnergyNLevels = None
    self.source = self.getSources()
    atomicData.add2usedFiles(self.atom, self.atomFile)
    atomicData.add2usedFiles(self.atom, self.collFile)

    self.ANN_n_temden=30
    self.ANN_inst_kwargs = {'RM_type' : 'SK_ANN', 
                            'verbose' : False, 
                            'scaling' : True,
                            'use_log' : True
                            }
    self.ANN_init_kwargs = {'solver' : 'lbfgs', 
                            'activation' : 'tanh', 
                            'hidden_layer_sizes' : (10, 10), 
                            'tol' : 1e-6,
                            'max_iter' : 20000
                            }
    self.ANN_Pop_inst_kwargs = {'RM_type' : 'SK_ANN', 
                            'verbose' : False, 
                            'scaling' : True,
                            'use_log' : True
                            }
    self.ANN_Pop_init_kwargs = {'solver' : 'lbfgs', 
                            'activation' : 'tanh', 
                            'hidden_layer_sizes' : (10, 10), 
                            'tol' : 1e-6,
                            'max_iter' : 20000
                            }

getA(lev_i=-1, lev_j=-1, wave=-1)

Return the transition probability data. If no arguments are given, the whole array of A is returned. A specific A value can be obtained by giving either the upper and lower levels or the wavelength of the transition (keyword wave).

Parameters:

Name Type Description Default
lev_i

upper level of transition (default= -1, returns complete array)

-1
lev_j

lower level of transition (default= -1, returns complete array)

-1
wave

wavelength of transition. Takes precedence on lev_i and lev_j. Ignored if not set.

-1

Usage:

A_O3 = O3.getA()          # The whole A array is stored in A_O3

O3.getA(4, 2)      # A(4, 2) of the O3 atom is printed

O3.getA(2, 4)      # Returns 0

O3.getA(wave=4959)
Source code in pyneb/core/pynebcore.py
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
def getA(self, lev_i= -1, lev_j= -1, wave= -1):
    """
    Return the transition probability data. 
    If no arguments are given, the whole array of A is returned.
    A specific A value can be obtained by giving either the upper and lower levels or 
        the wavelength of the transition (keyword wave).

    Parameters:
        lev_i:  upper level of transition (default= -1, returns complete array)
        lev_j:  lower level of transition (default= -1, returns complete array)
        wave:   wavelength of transition. Takes precedence on lev_i and lev_j. Ignored if not set.

    **Usage:**

        A_O3 = O3.getA()          # The whole A array is stored in A_O3

        O3.getA(4, 2)      # A(4, 2) of the O3 atom is printed

        O3.getA(2, 4)      # Returns 0

        O3.getA(wave=4959)

    """
    if wave != -1:
        lev_i, lev_j = self.getTransition(wave)

    return self.AtomData.getA(lev_i= lev_i, lev_j= lev_j)

getCollRates(tem, NLevels=None)

Return (n_levels x n_levels) array of collision rates at given temperature.

Parameters:

Name Type Description Default
tem

electronic temperature in K. May be an array.

required

Usage:

O3.getCollRates(tem=10000)

O3.getCollRates([8e3, 1e4, 1.2e4])
Source code in pyneb/core/pynebcore.py
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
@profile
def getCollRates(self, tem, NLevels=None):
    """
    Return (n_levels x n_levels) array of collision rates at given temperature. 

    Parameters:
        tem:     electronic temperature in K. May be an array.

    **Usage:**

        O3.getCollRates(tem=10000)

        O3.getCollRates([8e3, 1e4, 1.2e4])


    """
    tem = np.asarray(tem)
    if NLevels is None:
        NLevels = np.min((self.collNLevels, self.EnergyNLevels))
    res_shape = [NLevels, NLevels]
    for sh in tem.shape:
        res_shape.append(sh)
    resultArray = np.zeros(res_shape)
    Omegas = self.getOmega(tem)
    for i in range(NLevels - 1):
        lev_i = i + 1
        j = i + 1
        energy_i = self._Energy[i]
        stat_weight_i = self._StatWeight[i]
        while (j < NLevels):
            lev_j = j + 1 
            energy_j = self._Energy[j]
            stat_weight_j = self._StatWeight[j]
            resultArray[j][i] = CST.KCOLLRATE / tem ** 0.5 / stat_weight_j * Omegas[lev_j-1, lev_i-1]
            resultArray[i][j] = ((stat_weight_j) / (stat_weight_i) * 
                                  np.exp((energy_i - energy_j) / (CST.BOLTZMANN_ANGK * tem)) * 
                                  resultArray[j][i])
            j += 1

    return np.squeeze(resultArray)

getCritDensity(tem, level=-1)

Return the critical density of selected level at given temperature. If no transition is selected, return complete array.

Parameters:

Name Type Description Default
tem

electronic temperature in K. May be an array.

required
level

selected atomic level (default= -1)

-1

Usage:

O3.getCritDensity(12000)

O3.getCritDensity(12000, 4)
Source code in pyneb/core/pynebcore.py
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
@profile
def getCritDensity(self, tem, level= -1):
    """
    Return the critical density of selected level at given temperature. 
    If no transition is selected, return complete array.

    Parameters:
        tem:    electronic temperature in K. May be an array.
        level:  selected atomic level (default= -1)

    **Usage:**

        O3.getCritDensity(12000)

        O3.getCritDensity(12000, 4)

    """
    self._test_lev(level)
    self.getPopulations(tem, den=100.) # Any density would do
    if level != -1:
        return self._critDensity[level - 1]
    else:
        return self._critDensity        

getDensityRange(lev_i1=-1, lev_i2=-1, lev_j1=-1, lev_j2=-1, wave1=-1, wave2=-1, to_eval=None, tol=0.1, tem=10000.0)

Return the range of density where a given line ratio is between 10% and 90% of the low and high density limits

Parameters:

Name Type Description Default
lev_i1 int
-1
lev_i2 int
-1
wave1 int
-1
wave2 int
-1
to_eval str
None
tol float
0.1
tem float
10000.0
Source code in pyneb/core/pynebcore.py
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
def getDensityRange(self, lev_i1=-1, lev_i2=-1, lev_j1=-1, lev_j2=-1, wave1=-1, wave2=-1, 
                    to_eval=None, tol=0.1, tem=1e4):
    """
    Return the range of density where a given line ratio is between 10% and 90% of the low and high density limits

    Parameters:
        lev_i1 (int):
        lev_i2 (int):
        wave1 (int):
        wave2 (int):
        to_eval (str):
        tol (float): 
        tem (float):
    """
    LowLim = self.getLowDensRatio(lev_i1, lev_i2, wave1, wave2, to_eval)
    HighLim = self.getHighDensRatio(lev_i1, lev_i2, lev_j1, lev_j2, wave1, wave2, to_eval)

    delta = abs(LowLim - HighLim)
    minRatio = min((LowLim, HighLim)) + tol * delta
    maxRatio = max((LowLim, HighLim)) - tol * delta
    dens1 = self.getTemDen(minRatio, tem=tem, lev_i1= lev_i1, lev_j1= lev_j1, lev_i2= lev_i2, lev_j2= lev_j2,
              wave1= wave1, wave2= wave2, to_eval=to_eval)
    dens2 = self.getTemDen(maxRatio, tem=tem, lev_i1= lev_i1, lev_j1= lev_j1, lev_i2= lev_i2, lev_j2= lev_j2,
              wave1= wave1, wave2= wave2, to_eval=to_eval)
    return(np.sort((dens1, dens2)))

getEmissivity(tem, den, lev_i=-1, lev_j=-1, wave=-1, product=True, use_ANN=False)

Return the line emissivity (in erg.s-1.cm3) of selected transition or complete array of emissivities The transition is selected by the argument wave (if given); if wave is not supplied, it is selected by the upper and lower levels (lev_i and lev_j); if neither is given, the whole array is computed

Parameters:

Name Type Description Default
tem

electronic temperature in K. May be an array.

required
den

electronic density in cm^-3. May be an array.

required
lev_i

upper level (default= -1)

-1
lev_j

lower level (default= -1)

-1
wave

wavelength of transition. Takes precedence on lev_i and lev_j if set, ignored otherwise. It can also be a blend label.

-1
product

Boolean. If True (default), all the combination of (tem, den) are used. If False, tem and den must have the same size and are joined.

True

Usage:

O3.getEmissivity(12000, 100, 4, 2)         # (4, 2) transition

O3.getEmissivity(10000, 10000, wave=5007)  # (4, 2) transition

O3.getEmissivity(12000, 100)               # all transitions

O3.getEmissivity([10000, 12000], [100, 500], 4, 2)

O3.getEmissivity([10000, 12000], [100, 500])
Source code in pyneb/core/pynebcore.py
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
@profile
def getEmissivity(self, tem, den, lev_i= -1, lev_j= -1, wave= -1, product=True, use_ANN=False):
    """
    Return the line emissivity (in erg.s-1.cm3) of selected transition or complete array of emissivities
    The transition is selected by the argument wave (if given); 
    if wave is not supplied, it is selected by the upper and lower levels (lev_i and lev_j); 
    if neither is given, the whole array is computed

    Parameters:
        tem:      electronic temperature in K. May be an array.
        den:      electronic density in cm^-3. May be an array.
        lev_i:    upper level (default= -1)
        lev_j:    lower level (default= -1)
        wave:     wavelength of transition. Takes precedence on lev_i and lev_j if set, 
                    ignored otherwise. It can also be a blend label.
        product:  Boolean. If True (default), all the combination of (tem, den) are used. 
                     If False, tem and den must have the same size and are joined.

    **Usage:**      

        O3.getEmissivity(12000, 100, 4, 2)         # (4, 2) transition

        O3.getEmissivity(10000, 10000, wave=5007)  # (4, 2) transition

        O3.getEmissivity(12000, 100)               # all transitions

        O3.getEmissivity([10000, 12000], [100, 500], 4, 2)

        O3.getEmissivity([10000, 12000], [100, 500])

    """
    if '{0}_{1}'.format(self.atom, wave) in BLEND_LIST:
        L = lambda wave: self.getEmissivity(tem, den, wave=wave, product=product)
        I = lambda lev_i, lev_j: self.getEmissivity(tem, den, lev_i=lev_i, lev_j=lev_j, product=product)
        try:
            res = eval(BLEND_LIST['{0}_{1}'.format(self.atom, wave)])
        except:
            self.log_.warn('{0} is not understood'.format(wave), calling=self.calling + 'getEmissivity')
            res = None
        return res
    self._test_lev(lev_i)
    self._test_lev(lev_j)
    tem = np.asarray(tem)
    den = np.asarray(den)
    if wave != -1:
        lev_i, lev_j = self.getTransition(wave)
    NLevels = self.NLevels
    if lev_i > NLevels or lev_j > NLevels:
        self.log_.error('The number of levels {} does not allow getting this emissivity ({}-{}). Consider changing the atomic data'.format(NLevels,lev_i, lev_j),
                      calling=self.calling) 
    if product:
        n_tem = tem.size
        n_den = den.size
        tem_ones = np.ones(n_tem)
        populations = self.getPopulations(tem, den, product=True)
        if ((lev_i == -1) and (lev_j == -1)):
            resultArray = np.zeros((NLevels, NLevels, n_tem, n_den))
            for i in range(NLevels):
                lev_i = i + 1
                j = i - 1 
                while (j >= 0):
                    lev_j = j + 1
                    deltaE = (self._Energy[i] - self._Energy[j]) * CST.HPLANCK * CST.CLIGHT * 1.e8 
                    resultArray[i][j] = (deltaE * self._A[i, j] * populations[i].reshape(1, 1, n_tem, n_den) / 
                                         np.outer(tem_ones, den).reshape(1, 1, n_tem, n_den))
                    j -= 1
            return np.squeeze(resultArray)
        else:
            if (lev_i <= lev_j):
                return 0.
            else:
                i = lev_i - 1
                j = lev_j - 1
                deltaE = (self._Energy[i] - self._Energy[j]) * CST.HPLANCK * CST.CLIGHT * 1.e8 
                return np.squeeze((populations[i] * deltaE * self._A[i, j]).reshape(1, 1, n_tem, n_den) / 
                                  np.outer(tem_ones, den).reshape(1, 1, n_tem, n_den))
    else:
        if tem.shape != den.shape:
            self.log_.error('tem and den must have the same shape', calling=self.calling)
            return None
        populations = self.getPopulations(tem, den, product=False)
        if (lev_i <= lev_j):
            return None
        else:
            i = lev_i - 1
            j = lev_j - 1
            deltaE = (self._Energy[i] - self._Energy[j]) * CST.HPLANCK * CST.CLIGHT * 1.e8 
            return populations[i] * deltaE * self._A[i, j] / den

getHighDensRatio(lev_i1=-1, lev_i2=-1, lev_j1=-1, lev_j2=-1, wave1=-1, wave2=-1, to_eval=None)

Return the value of a diagostic ratio at the high density limit

Parameters:

Name Type Description Default
lev_i1 int
-1
lev_i2 int
-1
wave1 int
-1
wave2 int
-1
to_eval str
None

Usage:

S2.getHighDensRatio(lev_i1 = 3, lev_i2 = 2)

S2.getHighDensRatio(wave1 = 6716, wave2 = 6731)

S2.getHighDensRatio(to_eval = 'L(6716)/L(6731)')
Source code in pyneb/core/pynebcore.py
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
def getHighDensRatio(self, lev_i1=-1, lev_i2=-1, lev_j1=-1, lev_j2=-1, wave1=-1, wave2=-1, to_eval=None):

    """
    Return the value of a diagostic ratio at the high density limit

    Parameters:
        lev_i1 (int):
        lev_i2 (int):
        wave1 (int):
        wave2 (int):
        to_eval (str): 

    **Usage:**

        S2.getHighDensRatio(lev_i1 = 3, lev_i2 = 2)

        S2.getHighDensRatio(wave1 = 6716, wave2 = 6731)

        S2.getHighDensRatio(to_eval = 'L(6716)/L(6731)')
    """

    if wave1 != -1:
        lev_i1, lev_j1 = self.getTransition(wave1)
    if wave2 != -1:
        lev_i2, lev_j2 = self.getTransition(wave2)

    if to_eval is not None:
        L = lambda wave: (self.getStatWeight(self.getTransition(wave)[0]) * 
                          self.getA(self.getTransition(wave)[0], self.getTransition(wave)[1]))
        return eval(to_eval)

    return (self.getStatWeight(lev_i1) / self.getStatWeight(lev_i2) *
            self.getA(lev_i1, lev_j1) / self.getA(lev_i2, lev_j2))

getIonAbundance(int_ratio, tem, den, lev_i=-1, lev_j=-1, wave=-1, to_eval=None, Hbeta=100.0, tem_HI=None, den_HI=None, extrapHbeta=False, use_ANN=False)

Compute the ionic abundance relative to H+ given the intensity of a line or sum of lines, the temperature, and the density. The line can be specified as a transition (i.e., giving the two atomic level involved), as a wavelength, or as an algebraic expression. In the last case, a sum of lines can also be supplied.

Parameters:

Name Type Description Default
int_ratio

relative line intensity (default normalization: Hbeta = 100). May be an array.

required
tem

electronic temperature in K. May be an array.

required
den

electronic density in cm^-3. May be an array.

required
lev_i

upper level of transition

-1
lev_j

lower level of transition

-1
wave

wavelength of transition. Takes precedence on lev_i and lev_j if set, ignored otherwise

-1
to_eval

expression to be evaluated. Takes precedence on wave if set, ignored otherwise.

None
Hbeta

line intensity normalization at Hbeta (default Hbeta = 100)

100.0
tem_HI

HI temperature. If not set, tem is used.

None
extrapHbeta

[False] if set to True, Hbeta is extrapolated at low Te using Aller 82 function

False
use_ANN

[False] if set to True, use Machine Learning to compute line emissivities

False

Usage:

O3.getIonAbundance(100, 1.5e4, 100., wave=5007)

O3.getIonAbundance(130, 1.5e4, 100., to_eval='I(4,3) + I(4,2)')
Source code in pyneb/core/pynebcore.py
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
def getIonAbundance(self, int_ratio, tem, den, lev_i= -1, lev_j= -1, wave= -1, to_eval=None, 
                    Hbeta=100., tem_HI=None, den_HI=None, extrapHbeta=False, use_ANN=False):
    """
    Compute the ionic abundance relative to H+ given the intensity of a line or sum of lines, 
    the temperature, and the density. 
    The line can be specified as a transition (i.e., giving the two atomic level involved), 
    as a wavelength, or as an algebraic expression. In the last case, a sum of lines 
    can also be supplied.

    Parameters:
        int_ratio:    relative line intensity (default normalization: Hbeta = 100). 
                        May be an array.
        tem:          electronic temperature in K. May be an array.
        den:          electronic density in cm^-3. May be an array.
        lev_i:        upper level of transition
        lev_j:        lower level of transition
        wave:         wavelength of transition. Takes precedence on lev_i and lev_j if set, 
                        ignored otherwise 
        to_eval:      expression to be evaluated. Takes precedence on wave if set, 
                        ignored otherwise.
        Hbeta:        line intensity normalization at Hbeta (default Hbeta = 100)

        tem_HI:       HI temperature. If not set, tem is used.
        extrapHbeta: [False] if set to True, Hbeta is extrapolated at low Te using Aller 82 function
        use_ANN: [False] if set to True, use Machine Learning to compute line emissivities

    **Usage:**

        O3.getIonAbundance(100, 1.5e4, 100., wave=5007)

        O3.getIonAbundance(130, 1.5e4, 100., to_eval='I(4,3) + I(4,2)')

    """
    if tem_HI is None:
        tem_HI = tem
    if den_HI is None:
        den_HI = den
    self._test_lev(lev_i)
    self._test_lev(lev_j)
    if np.ndim(tem) != np.ndim(den):
        self.log_.error('ten and den must have the same shape', calling=self.calling)
        return None
    if ((np.squeeze(np.asarray(int_ratio)).shape != np.squeeze(np.asarray(tem)).shape) | 
        (np.squeeze(np.asarray(den)).shape != np.squeeze(np.asarray(tem)).shape)):
        self.log_.warn('int_ratio, tem and den must does not have the same shape', calling=self.calling)
    if (lev_i == -1) & (lev_j == -1) & (wave == -1) & (to_eval is None):
        self.log_.error('At least one of lev_i, lev_j, wave or to_eval must be supplied', calling=self.calling)
        return None
    if to_eval == None:
        if wave != -1:
            lev_i, lev_j = self.getTransition(wave)     
        to_eval = 'I(' + str(lev_i) + ',' + str(lev_j) + ')' 
    I = lambda lev_i, lev_j: self.getEmissivity(tem, den, lev_i, lev_j, product=False, use_ANN=use_ANN)
    L = lambda wave: self.getEmissivity(tem, den, wave=wave, product=False, use_ANN=use_ANN)
    try:
        emis = eval(to_eval)
    except:
        self.log_.error('Unable to eval {0}'.format(to_eval), calling=self.calling)
        return None
    #int_ratio is in units of Hb = Hbeta keyword
    if extrapHbeta:
        HbEmis = getHbEmissivity(tem= tem_HI, den=den_HI)
    else:
        HbEmis = getRecEmissivity(tem_HI, den_HI, 4, 2, atom='H1', product=False)
    ionAbundance = ((int_ratio / Hbeta) * (HbEmis / emis))
    return ionAbundance

getLowDensRatio(lev_i1=-1, lev_i2=-1, wave1=-1, wave2=-1, to_eval=None)

Return the value of a diagostic ratio at the low density limit

Parameters:

Name Type Description Default
lev_i1 int
-1
lev_i2 int
-1
wave1 int
-1
wave2 int
-1
to_eval str
None

Usage:

S2.getLowDensRatio(lev_i1 = 3, lev_i2 = 2)

S2.getLowDensRatio(wave1 = 6716, wave2 = 6731)

S2.getLowDensRatio(to_eval = 'L(6716)/L(6731)')
Source code in pyneb/core/pynebcore.py
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
def getLowDensRatio(self, lev_i1=-1, lev_i2=-1, wave1=-1, wave2=-1, to_eval=None):

    """
    Return the value of a diagostic ratio at the low density limit

    Parameters:
        lev_i1 (int):
        lev_i2 (int):
        wave1 (int):
        wave2 (int):
        to_eval (str): 

    **Usage:**

        S2.getLowDensRatio(lev_i1 = 3, lev_i2 = 2)

        S2.getLowDensRatio(wave1 = 6716, wave2 = 6731)

        S2.getLowDensRatio(to_eval = 'L(6716)/L(6731)')
    """

    if wave1 != -1:
        lev_i1, lev_j1 = self.getTransition(wave1)
    if wave2 != -1:
        lev_i2, lev_j2 = self.getTransition(wave2)

    if to_eval is not None:
        L = lambda wave: self.getStatWeight(self.getTransition(wave)[0])
        return eval(to_eval)

    return self.getStatWeight(lev_i1) / self.getStatWeight(lev_i2)

getOmega(tem, lev_i=-1, lev_j=-1, wave=-1)

Return interpolated value of the collision strength value at the given temperature for the complete array or a specified transition. If kappa is not None (non-maxwellian distribution of e-velocities), the collision strength is corrected as in Mendoza & Bautista, 2014 ApJ 785, 91.

Parameters:

Name Type Description Default
tem

electronic temperature in K. May be an array.

required
lev_i

upper level

-1
lev_j

lower level

-1

Usage:

O3.getOmega(15000.)

O3.getOmega([8e3, 1e4, 1.2e4])

O3.getOmega([8e3, 1e4, 1.2e4], 5, 4)
Source code in pyneb/core/pynebcore.py
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
def getOmega(self, tem, lev_i= -1, lev_j= -1, wave= -1):
    """
    Return interpolated value of the collision strength value at the given temperature 
        for the complete array or a specified transition.
    If kappa is not None (non-maxwellian distribution of e-velocities), the collision 
        strength is corrected as in Mendoza & Bautista, 2014 ApJ 785, 91.

    Parameters:
        tem:    electronic temperature in K. May be an array.
        lev_i:  upper level
        lev_j:  lower level

    **Usage:**

        O3.getOmega(15000.)

        O3.getOmega([8e3, 1e4, 1.2e4])

        O3.getOmega([8e3, 1e4, 1.2e4], 5, 4)
    """



    if wave != -1:
        lev_i, lev_j = self.getTransition(wave)
    kappa = config.kappa 
    if kappa is None:
        to_return = self.CollData.getOmega(tem, lev_i, lev_j)
    else:
        #ToDo The Kappa correction should come AFTER the transformation into CS unit
        if (lev_i == -1) and (lev_j == -1):
            tem = np.asarray(tem)
            res_shape = [self.collNLevels, self.collNLevels]
            for sh in tem.shape:
                res_shape.append(sh)
            Omega = np.zeros(res_shape)

            for i in range(self.collNLevels - 1):
                j = i + 1
                while (j < self.collNLevels):
                    Omega[j][i] = self.getOmega(tem, j + 1, i + 1)
                    j += 1
        else:
            OmegaMB = self.CollData.getOmega(tem, lev_i, lev_j)
            delta_E = self.getEnergy(lev_i, unit='eV') - self.getEnergy(lev_j, unit='eV')
            correc = ((kappa - 3./2.)**(-0.5) / kappa * gamma(kappa+1) / gamma(kappa-0.5) * 
                      (1 + delta_E/((kappa-1.5)*CST.BOLTZMANN_eVK*tem))**(-kappa)) * np.exp(delta_E/CST.BOLTZMANN_eVK/tem)

            Omega = correc * OmegaMB
            self.log_.message('Correcting for Kappa={0} by {1}'.format(kappa, correc), self.calling)

        to_return = np.squeeze(Omega)
    if 'COEFF' in self.CollData.comments:
        to_return *= float(self.CollData.comments['COEFF'])
    if 'O_UNIT' in self.CollData.comments:
        if self.CollData.comments['O_UNIT'] == 'DEEX RATE COEFF':
            to_return /= CST.KCOLLRATE / tem ** 0.5 / self.getStatWeight(lev_i)
        elif self.CollData.comments['O_UNIT'] == 'RATE COEFF':
            deltaE = self.getEnergy(lev_i, unit='erg') - self.getEnergy(lev_j, unit='erg')
            to_return *= (self.getStatWeight(lev_j) / self.getStatWeight(lev_i) * np.exp(deltaE /(CST.BOLTZMANN * tem))) #q21
            to_return /= CST.KCOLLRATE / tem ** 0.5 / self.getStatWeight(lev_i)
        elif self.CollData.comments['O_UNIT'] == 'COOLING':
            deltaE = self.getEnergy(lev_i, unit='erg') - self.getEnergy(lev_j, unit='erg')
            to_return /= deltaE # Loss to q12                
            to_return *= (self.getStatWeight(lev_j) / self.getStatWeight(lev_i) * np.exp(deltaE /(CST.BOLTZMANN * tem))) #q21
            to_return /= (CST.KCOLLRATE / np.sqrt(tem) / self.getStatWeight(lev_i)) # Omega

    return to_return

getPopulations(tem, den, product=True, NLevels=None)

Return array of populations at given temperature and density. The method returns a 1-, 2- or 3-D array containing the population of each level for all temperatures and densities specified in the input vectors tem and den (which can be n-element or 1-element vectors). If either quantity (tem or den) is a 1-element vector -that is, a single value-, the resulting population array is collapsed along that dimension; as a result, the result population array can be a 1-D, 2-D or 3-D array (the three cases corresponding to situations in which both tem and den are single values; one of them is a single value and the other an n-element vector; or both are multielement vectors, respectively). In the general case, the level index is the first [WARNING! It is not in physical unit, i.e. ground level = 0; to be normalized], followed by the temperature index (if it exists) and the density index.

Parameters:

Name Type Description Default
tem

electronic temperature in K

required
den

electronic density in cm^-3

required
product

operate on all possible combinations of temperature and density (product = True, default case) or on those resulting from combining the i-th value of tem with the i-th value of den (product = False). If product = False, then tem and den must be the same size.

True

Usage:

O3.getPopulations(1e4, 1e2)

tem=np.array([10000., 12000., 15000., 20000]) # An array of four temperatures

den=np.array([600., 800., 1000])      # An array of three densities

O3.getPopulations(tem, den)           # is a (6, 4, 3) array

O3.getPopulations(tem, den)[0,2,1]    # Returns the population of level 1 for T = 15000 
                                        and Ne = 800

tem = 20000                           # tem is no longer an array

O3.getPopulations(tem, den)[0,2,1]  # Crashes: one index too much

O3.getPopulations(tem, den)[0,1]    # Returns the population of level 1 for T = 20000 
                                        and Ne = 800 [see warning]

tem=np.array([10000., 15000., 20000]) # An array of three temperatures

O3.getPopulations(tem, den, product = False)# is a (6, 3) array, tem and den beeing 
                                                taken 2 by 2.
Source code in pyneb/core/pynebcore.py
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
@profile
def getPopulations(self, tem, den, product=True, NLevels=None):
    """
    Return array of populations at given temperature and density.
    The method returns a 1-, 2- or 3-D array containing the population of each level 
        for all temperatures and densities specified in the input vectors tem and den 
        (which can be n-element or 1-element vectors).
    If either quantity (tem or den) is a 1-element vector -that is, a single value-, 
        the resulting population array is collapsed along that dimension; 
        as a result, the result population array can be a 1-D, 2-D or 3-D array 
        (the three cases corresponding to situations in which both tem and den are single values; 
        one of them is a single value and the other an n-element vector; or both are multielement 
        vectors, respectively). In the general case, the level index is the first 
        [WARNING! It is not in physical unit, i.e. ground level = 0; to be normalized], 
        followed by the temperature index (if it exists) and the density index. 

    Parameters:
        tem:       electronic temperature in K
        den:       electronic density in cm^-3
        product:   operate on all possible combinations of temperature and density 
                  (product = True, default case) or on those resulting from combining 
                  the i-th value of tem with the i-th value of den (product = False).
                  If product = False, then tem and den must be the same size.

    **Usage:**

        O3.getPopulations(1e4, 1e2)

        tem=np.array([10000., 12000., 15000., 20000]) # An array of four temperatures

        den=np.array([600., 800., 1000])      # An array of three densities

        O3.getPopulations(tem, den)           # is a (6, 4, 3) array

        O3.getPopulations(tem, den)[0,2,1]    # Returns the population of level 1 for T = 15000 
                                                and Ne = 800

        tem = 20000                           # tem is no longer an array

        O3.getPopulations(tem, den)[0,2,1]  # Crashes: one index too much

        O3.getPopulations(tem, den)[0,1]    # Returns the population of level 1 for T = 20000 
                                                and Ne = 800 [see warning]

        tem=np.array([10000., 15000., 20000]) # An array of three temperatures

        O3.getPopulations(tem, den, product = False)# is a (6, 3) array, tem and den beeing 
                                                        taken 2 by 2.

    """
    tem = np.asarray(tem)
    den = np.asarray(den)
    if NLevels is None:
        n_level = self.NLevels
    else:
        n_level = NLevels
    if product:
        n_tem = tem.size
        n_den = den.size
        tem_ones = np.ones(n_tem)
        den_ones = np.ones(n_den)
        # q is vector-indexed (q(0, 1) = rate between levels 1 and 2)
        q = self.getCollRates(tem, n_level)
        Atem = np.outer(self._A[:n_level, :n_level], tem_ones).reshape(n_level, n_level, n_tem)
        pop_result = np.zeros((n_level, n_tem, n_den))
        sum_q_up = np.zeros((n_level, n_tem))
        sum_q_down = np.zeros((n_level, n_tem))
        sum_A = np.squeeze(Atem.sum(axis=1))
        self._critDensity = sum_A / q.sum(axis=1)
        for i in range(1, n_level):
            for j in range(i + 1, n_level):
                sum_q_up[i] = sum_q_up[i] + q[i, j]
            for j in range(0, i):
                sum_q_down[i] = sum_q_down[i] + q[i, j]
        coeff_matrix = ((np.outer(np.swapaxes(q, 0, 1), den) + 
                         np.outer(np.swapaxes(Atem, 0, 1), den_ones)).reshape(n_level, n_level, n_tem, n_den))
        coeff_matrix[0, :] = 1.
        for i in range(1, n_level):
            coeff_matrix[i, i] = (-(np.outer((sum_q_up[i] + sum_q_down[i]), den) + 
                                    np.outer(sum_A[i], den_ones)).reshape(1, 1, n_tem, n_den))
        vect = np.zeros(n_level)
        vect[0] = 1.

        for i_tem in range(n_tem):
            for i_den in range(n_den):
                pop_result[:, i_tem, i_den] = solve(np.squeeze(coeff_matrix[:, :, i_tem, i_den]), vect)
                try:
                    pop_result[:, i_tem, i_den] = solve(np.squeeze(coeff_matrix[:, :, i_tem, i_den]), vect)
                #except np.linalg.LinAlgError:
                #    pop_result[:, i_tem, i_den] = np.nan
                except:
                    self.log_.error('Error solving population matrix', calling=self.calling)
        pop = np.squeeze(pop_result)
    else:
        if tem.shape != den.shape:
            self.log_.error('tem and den must have the same shape', calling=self.calling)
            return None
        res_shape1 = [n_level]
        res_shape_rav1 = [n_level, tem.size]
        res_shape_rav2 = [n_level, n_level, tem.size]
        for sh in tem.shape:
            res_shape1.append(sh)
        tem_rav = tem.ravel()
        den_rav = den.ravel()
        q = self.getCollRates(tem_rav, n_level)
        A = self._A[:n_level, :n_level]
        pop_result = np.zeros(res_shape_rav1)
        coeff_matrix = np.ones(res_shape_rav2)
        sum_q_up = np.zeros(res_shape_rav1)
        sum_q_down = np.zeros(res_shape_rav1)
        sum_A = A.sum(axis=1)
        n_tem = tem_rav.size
        # Following line changed 29/11/2012. It made the code crash when atom_nlevels diff coll_nlevels
        #Atem = np.outer(self._A, np.ones(n_tem)).reshape(n_level, n_level, n_tem)
        Atem = np.outer(self._A[:n_level, :n_level], np.ones(n_tem)).reshape(n_level, n_level, n_tem)
        self._critDensity = Atem.sum(axis=1) / q.sum(axis=1)

        for i in range(1, n_level):
            for j in range(i + 1, n_level):
                sum_q_up[i] = sum_q_up[i] + q[i, j]
            for j in range(0, i):
                sum_q_down[i] = sum_q_down[i] + q[i, j]
        for row in range(1, n_level):
            # upper right half            
            for col in range(row + 1, n_level):
                coeff_matrix[row, col] = den_rav * q[col, row] + A[col, row]
            # lower left half
            for col in range(0, row):
                coeff_matrix[row, col] = den_rav * q[col, row]
            # diagonal
            coeff_matrix[row, row] = -(den_rav * (sum_q_up[row] + sum_q_down[row]) + sum_A[row])

        vect = np.zeros(n_level)
        vect[0] = 1.

        for i in range(tem.size):
            try:
                pop_result[:, i] = solve(np.squeeze(coeff_matrix[:, :, i]), vect)
            except np.linalg.LinAlgError:
                pop_result[:, i] = np.nan
            except:
                self.log_.error('Error solving population matrix', calling=self.calling)

        pop = np.squeeze(pop_result.reshape(res_shape1))

    return pop

getTemDen(int_ratio, tem=-1, den=-1, lev_i1=-1, lev_j1=-1, lev_i2=-1, lev_j2=-1, wave1=-1, wave2=-1, maxError=0.001, method='nsect_recur', log=True, start_x=-1, end_x=-1, to_eval=None, nCut=30, maxIter=20)

Return either the temperature or the density given the other variable for a selected line ratio of known intensity. The line ratio can involve two or more than two lines. In the first case (only two lines), it can be specified giving either two transitions (four atomic levels, i.e. two for each transition), or two wavelengths. In the general case (any number of lines), it can be specified as an algebraic expression to be evaluated, involving either atomic levels or wavelengths. An array of values, rather than a single value, can also be given, in which case the result will also be an array.

Parameters:

Name Type Description Default
int_ratio

intensity ratio of the selected transition

required
tem

electronic temperature

-1
den

electronic density

-1
lev_i1

upper level of 1st transition

-1
lev_j1

lower level of 1st transition

-1
lev_i2

upper level of 2nd transition

-1
lev_j2

lower level of 2nd transition

-1
wave1

wavelength of 1st transition

-1
wave2

wavelength of 2nd transition

-1
maxError

tolerance on difference between input and computed ratio

0.001
method

numerical method for finding the root (nsect_recur, nsect_iter)

'nsect_recur'
log

switch of log (default = True). start_x and end_x are using this parameter.

True
start_x

lower end of the interval to explore. (default: lower end of collision strength temperature array for temperature, 1 if density)

-1
end_x

higher end of the interval to explore. (default: higher end of collision strength temperature array for temperature, 1e8 if density)

-1
to_eval

expression to be evaluated, using either I (for transitions identified through atomic levels) or L (for transitions identified through wavelengths)

None
nCut

number of sections in which each step is cut. 2 would be dichotomy.

30
maxIter

maximum number of iterations

20

Usage:

O3.getTemDen(150., den=100., wave1=5007, wave2=4363, maxError=1.e-2)

O3.getTemDen(150., den=100., to_eval = '(I(4,3) + I(4,2) + I(4,1)) / I(5,4)')

N2.getTemDen(150., den=100., to_eval = '(L(6584) + L(6548)) / L(5755)')

O3.getTemDen([0.02, 0.04], den=[1.e4, 1.1e4], to_eval="I(5, 4) / (I(4, 3) + I(4, 2))")
Source code in pyneb/core/pynebcore.py
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
@profile
def getTemDen(self, int_ratio, tem= -1, den= -1, lev_i1= -1, lev_j1= -1, lev_i2= -1, lev_j2= -1,
              wave1= -1, wave2= -1, maxError=1.e-3, method='nsect_recur', log=True, start_x= -1, end_x= -1,
              to_eval=None, nCut=30, maxIter=20):
    """
    Return either the temperature or the density given the other variable for a selected line ratio 
        of known intensity.
    The line ratio can involve two or more than two lines. 
    In the first case (only two lines), it can be specified giving either two transitions 
        (four atomic levels, i.e. two for each transition), or two wavelengths.
    In the general case (any number of lines), it can be specified as an algebraic expression 
        to be evaluated, involving either atomic levels or wavelengths.
    An array of values, rather than a single value, can also be given, in which case the result 
        will also be an array.

    Parameters:
       int_ratio:    intensity ratio of the selected transition
       tem:          electronic temperature
       den:          electronic density
       lev_i1:       upper level of 1st transition
       lev_j1:       lower level of 1st transition
       lev_i2:       upper level of 2nd transition
       lev_j2:       lower level of 2nd transition
       wave1:        wavelength of 1st transition
       wave2:        wavelength of 2nd transition
       maxError:     tolerance on difference between input and computed ratio 
       method:       numerical method for finding the root (nsect_recur, nsect_iter)
       log:          switch of log (default = True). start_x and end_x are using this parameter.
       start_x:      lower end of the interval to explore. (default: lower end of collision 
                        strength temperature array for temperature, 1 if density)
       end_x:        higher end of the interval to explore. (default: higher end of collision 
                        strength temperature array for temperature, 1e8 if density)
       to_eval:      expression to be evaluated, using either I (for transitions identified 
                        through atomic levels) or L (for transitions identified through wavelengths)
       nCut:        number of sections in which each step is cut. 2 would be dichotomy.
       maxIter:     maximum number of iterations

    **Usage:** 

        O3.getTemDen(150., den=100., wave1=5007, wave2=4363, maxError=1.e-2)

        O3.getTemDen(150., den=100., to_eval = '(I(4,3) + I(4,2) + I(4,1)) / I(5,4)')

        N2.getTemDen(150., den=100., to_eval = '(L(6584) + L(6548)) / L(5755)')

        O3.getTemDen([0.02, 0.04], den=[1.e4, 1.1e4], to_eval="I(5, 4) / (I(4, 3) + I(4, 2))")
    """
    if method == 'ANN':
        return self._getTemDen_ANN(int_ratio=int_ratio, tem=tem, den=den, lev_i1=lev_i1, lev_j1=lev_j1, lev_i2=lev_i2, lev_j2=lev_j2,
              wave1=wave1, wave2=wave2, start_x=start_x, end_x=end_x, to_eval=to_eval)            
    elif config._use_mp:
        return self._getTemDen_MP(int_ratio=int_ratio, tem=tem, den=den, lev_i1=lev_i1, lev_j1=lev_j1, lev_i2=lev_i2, lev_j2=lev_j2,
              wave1=wave1, wave2=wave2, maxError=maxError, method=method, log=log, start_x=start_x,
              end_x=end_x, to_eval=to_eval, nCut=nCut, maxIter=maxIter)
    else:
        return self._getTemDen_1(int_ratio=int_ratio, tem=tem, den=den, lev_i1=lev_i1, lev_j1=lev_j1, lev_i2=lev_i2, lev_j2=lev_j2,
              wave1=wave1, wave2=wave2, maxError=maxError, method=method, log=log, start_x=start_x,
              end_x=end_x, to_eval=to_eval, nCut=nCut, maxIter=maxIter)

getTransition(wave, maxErrorA=0.005, maxErrorm=0.05)

Return the indexes (upper level, lower level) of a transition for a given atom from the wavelength.

Parameters:

Name Type Description Default
wave

wavelength in Angstrom (a float or a label: e.g., 5007, '5007A') or in micron (a label: '51.5m')

required
maxErrorA

tolerance if the input wavelength is in Angstrom

0.005
maxErrorm

tolerance if the input wavelength is in micron

0.05

Usage:

O3.getTransition(4959)
Source code in pyneb/core/pynebcore.py
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
def getTransition(self, wave, maxErrorA = 5.e-3, maxErrorm = 5.e-2):
    """
    Return the indexes (upper level, lower level) of a transition for a given atom 
        from the wavelength.



    Parameters:
        wave:      wavelength in Angstrom (a float or a label: e.g., 5007, '5007A') 
            or in micron (a label: '51.5m')
        maxErrorA: tolerance if the input wavelength is in Angstrom
        maxErrorm: tolerance if the input wavelength is in micron

    **Usage:**

        O3.getTransition(4959)   
    """ 
    res = self._Transition(wave, maxErrorA = maxErrorA, maxErrorm = maxErrorm)
    return(res[0], res[1])

plotEmiss(tem_min=1000, tem_max=30000, ionic_abund=1.0, den=1000.0, style='-', legend_loc=4, temLog=False, plot_total=False, plot_only_total=False, legend=True, total_color='black', total_label='TOTAL', ax=None)

Plot the emissivity as a function of temperature of all the lines of the selected atom.

Parameters:

Name Type Description Default
tem_min

minimum value of the temperature range to span (default=1000)

1000
tem_max

maximum value of the temperature range to span (default=30000)

30000
ionic_abund

relative ionic abundance (default = 1.0)

1.0
den

electron density

1000.0
style

line style of the plot (default: '-' [solid line])

'-'
legend_loc

localization of the legend (default: 4 = lower right; see plt.legend for more details)

4
temLog

linear (False) or logarithmic temperature axis (default = False)

False
plot_total

flag to also plot total emissivity (default = False)

False
plot_only_total

flag to only plot total emissivity (default = False)

False
legend

flag to place legend (default = True)

True
total_color

color of the total emissivity (default = 'black')

'black'
total_label

label of the total emissivity (default = 'TOTAL')

'TOTAL'
ax

axis where to send the plot. If None, a new axis is done

None

Usage:

O3.plotEmiss(tem_min=10000, tem_max=20000)
Source code in pyneb/core/pynebcore.py
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
def plotEmiss(self, tem_min=1000, tem_max=30000, ionic_abund=1.0, den=1e3, style='-',
              legend_loc=4, temLog=False, plot_total=False, plot_only_total=False, legend=True,
              total_color='black', total_label='TOTAL', ax=None):
    """ 
    Plot the emissivity as a function of temperature of all the lines of the selected atom.  

    Parameters:
        tem_min:         minimum value of the temperature range to span (default=1000)
        tem_max:         maximum value of the temperature range to span (default=30000)
        ionic_abund:     relative ionic abundance (default = 1.0)
        den:             electron density
        style:           line style of the plot (default: '-' [solid line])
        legend_loc:      localization of the legend (default: 4 = lower right; see plt.legend 
                            for more details)
        temLog:          linear (False) or logarithmic temperature axis (default = False)
        plot_total:      flag to also plot total emissivity (default = False)
        plot_only_total: flag to only plot total emissivity (default = False)
        legend:          flag to place legend (default = True)
        total_color:     color of the total emissivity (default = 'black')
        total_label:     label of the total emissivity (default = 'TOTAL')
        ax:              axis where to send the plot. If None, a new axis is done

    **Usage:**

        O3.plotEmiss(tem_min=10000, tem_max=20000)

    """
    if ax is None:
        f, ax = plt.subplots()
    if not config.INSTALLED['plt']: 
        self.log_.error('Matplotlib not available, no plot', calling=self.calling + '.plot')
        return None
    tem = np.logspace(np.log10(tem_min), np.log10(tem_max), 1000)
    total_emis = np.zeros_like(tem)
    for wave in self.lineList:
        lev_i, lev_j = self.getTransition(wave)
        if (lev_i <= self.NLevels) and (lev_j <= self.NLevels):
            color = ((np.log10(wave) - np.log10(np.min(self.lineList))) / 
                     (np.log10(np.max(self.lineList)) - np.log10(np.min(self.lineList)))) ** 0.4
            c = cm.jet(color, 1)
            if temLog:
                x_to_plot = np.log10(tem)
            else:
                x_to_plot = tem
            y_to_plot = ionic_abund * self.getEmissivity(tem, den, wave=wave)
            if not plot_only_total:
                if (y_to_plot[0] > 0.):
                    ax.plot(x_to_plot, np.log10(y_to_plot),
                         label='{0:.0f}'.format(wave), color=c, linestyle=style)
            total_emis += y_to_plot
    if plot_total:
        ax.plot(x_to_plot, np.log10(total_emis),
                 label=total_label, color=total_color, linewidth=3, linestyle=style)
    if legend:
        ax.legend(loc=legend_loc)
    if temLog:
        ax.set_xlabel('log(T[K])')
    else:
        ax.set_xlabel('T[K]')
    ax.set_ylabel('log [erg.cm3/s]')
    ax.set_title('Line emissivities')

plotGrotrian(tem=10000.0, den=100.0, thresh_int=0.001, unit='eV', detailed=False, ax=None)

Draw a Grotrian plot of the selected atom, labelling only lines above a pecified intensity threshold (relative to the most intense line). For ground state levels, the Russell-Saunders term symbol is also given.

Parameters:

Name Type Description Default
tem

temperature at which the intensity threshold is to be computed

10000.0
den

density at which the intensity threshold is to be computed

100.0
thresh_int

intensity threshold (relative to the most intense line, default: 1.e-3)

0.001
unit

one of 'eV' (default), '1/Ang' or 'Ryd'

'eV'
ax

axis where to plot the result

None
Usage

O3.plotGrotrian()

Source code in pyneb/core/pynebcore.py
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
    def plotGrotrian(self, tem=1e4, den=1e2, thresh_int=1e-3, unit='eV', detailed=False, ax=None):
        """
        Draw a Grotrian plot of the selected atom, labelling only lines above a
        pecified intensity threshold (relative to the most intense line). 
        For ground state levels, the Russell-Saunders term symbol is also given.

        Parameters:
            tem:          temperature at which the intensity threshold is to be computed 
            den:          density at which the intensity threshold is to be computed 
            thresh_int:   intensity threshold (relative to the most intense line, default: 1.e-3)
            unit:         one of 'eV' (default), '1/Ang' or 'Ryd'
            ax:           axis where to plot the result

        Usage:

            **O3.plotGrotrian()**

        """
        if ax is None:
            f, ax = plt.subplots()
        if unit not in ['eV', 'Ryd', '1/Ang']:
            self.log_.error('Unit {0} not available'.format(unit))
            return None
        if not config.INSTALLED['plt']: 
            self.log_.error('Matplotlib not available, no plot', calling=self.calling + '.plot')
            return None
        color_list = ['b', 'r', 'y', 'c', 'm', 'g']
        energies = self.getEnergy(unit=unit)

        # VL 16 Jul 2013 - Detect level inversion, just for warning        
        level_multiplet = [0]
        multiplets = []
        if self.NIST is not None:
            term = []; j = []; en = []
            for item in self.NIST:
                term.append(item[1])
                j.append(item[2])
                en.append(item[3])
            sorted_indx = np.argsort(en) 
            term = np.array(term)[sorted_indx]
            j = np.array(j)[sorted_indx]
            en = np.array(en)[sorted_indx]
            for i in np.arange(1, len(en)):
                if (term[i] == term[i-1]):
                    level_multiplet.append(i)
                else:
                    multiplets.append(level_multiplet) 
                    level_multiplet = [i]
            multiplets.append(level_multiplet) # append last multiplet
# Mistakenly rounds off fractional J values. Corrected 26/12/2014            
#            levelLabels = ['$^{{{0}}}${1}$_{{{2:.0f}}}$'.format(l['term'][0],l['term'][1],l['J']) for l in self.NIST]
            levelLabels = []
            for l in self.NIST:
                if Fraction(l['J']).denominator == 1:
                    levelLabels.append('$^{{{0}}}${1}$_{{{2}}}$'.format(l['term'][0], l['term'][1], Fraction(l['J']).numerator))
                else:
                    levelLabels.append('$^{{{0}}}${1}$_{{{2}/{3}}}$'.format(l['term'][0], l['term'][1], Fraction(l['J']).numerator, Fraction(l['J']).denominator))
        else:
            delta_e_max = 1.e-5  # Arbitrary limit to define hyperfine structure and identify multiplets 
            for i in np.arange(1, len(energies)):
                if (self.getEnergy()[i] - self.getEnergy()[i - 1] < delta_e_max):
                    # if levels close, append level to multiplet
                    level_multiplet.append(i) 
                else:
                    # if levels separated, add current multiplet to array and start a new multiplet
                    multiplets.append(level_multiplet) 
                    level_multiplet = [i]
            multiplets.append(level_multiplet) # append last multiplet
            warn_label = []
            levelLabels = gsLevelDict[self.gs]
            for i_multi in np.arange(len(multiplets)):
                stat_weights = []
                # check each multiplet for inversion separately
                for i_level in multiplets[i_multi]:
                    latex_sw = levelLabels[i_level]
                    sw = eval(latex_sw.split('$')[-2].replace('_', '').replace('{', '').replace('}', '.') + '*2.+1.')
                    stat_weights.append(sw)
                if (stat_weights != [self.getStatWeight()[k] for k in multiplets[i_multi]]):
                    warn_label.append(i_multi)
                    to_print = '\nLevel inversion in multiplet {0} of {1}'\
                             '\nThe labels of levels {2} are displayed in the wrong order' + \
                             '\nAssumed statistical weights: {3}' + \
                             '\nStatistical weights of data: {4}\n'
                    self.log_.warn(to_print.format(i_multi + 1, self.atom, multiplets[i_multi], 
                                                 stat_weights, [self.getStatWeight()[k] for k in multiplets[i_multi]]), 
                                 calling=self.calling + '.plot')

        # where level starts in the plot

        x_span = 0.75
        x_0 = (1 - x_span) / 4.    
        dx = 0.005
        max_en = np.max(energies)
        blow = 0.02 * max_en # blowup scale for multiplets
        ax.set_xlim((0, 1.))
        ax.set_ylim((np.max(energies) * -0.05, max_en * 1.05))
        ax.set_title('[{0} {1}]'.format(self.elem, int_to_roman(self.spec)))

        # Blow up of multiplets in the plot
        i_tot = 0
        for i_multi in np.arange(len(multiplets)):
            shift = (1-len(multiplets[i_multi])) / 2.
            for i in np.arange(len(multiplets[i_multi])):
                y = energies[multiplets[i_multi][i]] + shift * blow
                ax.plot([x_0, 1.5 * x_0, 1.6 * x_0, x_0 + x_span], 
                         [y, y, energies[multiplets[i_multi][i]], 
                          energies[multiplets[i_multi][i]]], lw = 1.2, 
                         color = color_list[np.mod(multiplets[i_multi][i], len(color_list))])
                ax.text(x_span + x_0 + dx, y, '{0:7.4f}'.format(energies[multiplets[i_multi][i]]), size='small', 
                         horizontalalignment='left', verticalalignment='center')
                try:
                    if (detailed is False):
                        ax.text(dx, y, levelLabels[i_tot], size='medium', verticalalignment='center')
                    else:
                        ax.text(dx, y, str(i_tot+1) + ": " + levelLabels[i_tot] , size='medium', verticalalignment='center', 
                                color = color_list[np.mod(multiplets[i_multi][i], len(color_list))])
                    i_tot += 1
                except:
                    pass
                shift += 1
        ax.text(1 - dx / 2., max(energies) * 0.5, 'E [{0:s}] '.format(unit), horizontalalignment='right', color='blue')
        ax.set_xlabel('Ground-state configuration: {0}'.format(self.gs), color="#004400")

        ax.xaxis.set_ticks_position("none")
        ax.yaxis.set_ticks_position("none")
        ax.xaxis.set_ticklabels([])
        ax.yaxis.set_ticklabels([])

        all_emis = self.getEmissivity(tem, den)
        emis_max = np.max(all_emis)
        N_lines = (self.getEmissivity(1e4, 1e3) > (emis_max * thresh_int)).sum() # number of lines plotted
        x_pad = 0.1 * (x_span - 0.6 * x_0)     
        if N_lines > 1:
            delta_x = (x_span - 2 * x_pad) / (N_lines - 1)
            x = 1.6 * x_0 + 0.5 * x_pad
        else:
            delta_x = 0
            x = (1.6 * x_0 + x_span) / 2.
        cc = colors.ColorConverter()
        for j in np.arange(self.NLevels - 1) + 2:
            for i in np.arange(j - 1) + 1:
                emis = all_emis[j-1, i-1]
                if emis > (emis_max * thresh_int):
                    N_seg = 1000 #number of segments to draw emission line, to make it look smooth
                    xx = np.ones(N_seg+1) * x  # x coord of segmente making up one line
                    yy = np.linspace(self.getEnergy(i, unit=unit), self.getEnergy(j, unit=unit), N_seg+1)
                    scale = np.linspace(0, 1, N_seg+1)
                    alpha =  np.tanh((2*scale-1)+1)  # to make alpha vary as a smooth step function
                    points = np.array([xx, yy]).T.reshape(-1, 1, 2) 
                    segments = np.concatenate([points[:-1], points[1:]], axis=1) 
                    cmap1 = []
                    cmap2 = []
                    for seg in segments:
                            yy0 = seg.mean(0)[1] 
                            alpha0 = np.interp(yy0, yy, alpha)
                            rgb1 = cc.to_rgb(color_list[np.mod(j-1, len(color_list))]) 
                            rgb2 = cc.to_rgb(color_list[np.mod(i-1, len(color_list))]) 
                            cmap1.append([rgb1[0], rgb1[1], rgb1[2], alpha0]) 
                            cmap2.append([rgb2[0], rgb2[1], rgb2[2], 1-alpha0])
                    lc1 = LineCollection(segments, linewidths=3.5)
                    lc1.set_color(cmap1) 
                    lc2 = LineCollection(segments, linewidths=3.5)
                    lc2.set_color(cmap2) 
                    ax.add_collection(lc1) 
                    ax.add_collection(lc2) 
                    if self.wave_Ang[j - 1, i - 1] > 1e4:
                        to_print = '{0:.1f}m'.format(self.wave_Ang[j - 1, i - 1] / 1e4) + ' '
                    else:
                        to_print = '{0:.1f}A'.format(self.wave_Ang[j - 1, i - 1]) + ' '
                    ax.text(x + 0.05 * delta_x, self.getEnergy(j, unit=unit)-blow/2., to_print, size='small', rotation=90, verticalalignment='top')
                    x = x + delta_x

        # issue warning on plot if level inversion 
        try:
            for i in warn_label:
                ax.text(0, self.getEnergy(multiplets[i][0]+1, unit=unit), 'Warning ', ha='right', color='red')
        except:
            pass

printIonic(tem=None, den=None, printA=False, printPop=True, printCrit=True)

Print miscellaneous information (wavelengths, level populations, emissivities, critical densities) for given physical conditions. If an electron temperature is given, level critical densities can be printed (using printCrit=True) If an electron density is also given, line emissivities (also for Hbeta) are printed and level populations can be printed (using printPop=True)

Parameters:

Name Type Description Default
tem

temperature

None
den

density

None
printA

also print transition probabilities (default=False)

False
printPop

also print level populations (needs tem and den)

True
printCrit

also print critical densities (needs tem)

True

Usage:

O3.printIonic()

O3.printIonic(printA=True)

O3.printIonic(tem=10000., printCrit=True)

O3.printIonic(tem=10000., den=1e3, printA=True, printPop=True, printCrit=True)
Source code in pyneb/core/pynebcore.py
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
def printIonic(self, tem=None, den=None, printA=False, printPop=True, printCrit=True):
    """ 
    Print miscellaneous information (wavelengths, level populations, emissivities, 
        critical densities) for given physical conditions.
    If an electron temperature is given, level critical densities can be printed 
        (using printCrit=True)
    If an electron density is also given, line emissivities (also for Hbeta) are printed and level 
        populations can be printed (using printPop=True)

    Parameters:
        tem:          temperature
        den:          density
        printA:       also print transition probabilities (default=False)
        printPop:     also print level populations (needs tem and den)
        printCrit:    also print critical densities (needs tem)

    **Usage:**

        O3.printIonic()

        O3.printIonic(printA=True)

        O3.printIonic(tem=10000., printCrit=True)

        O3.printIonic(tem=10000., den=1e3, printA=True, printPop=True, printCrit=True)

    """
    print('elem = %s' % self.elem)
    print('spec = %i' % self.spec)
    if tem is not None:
        print('temperature = %6.1f K' % tem)
    if den is not None:
        print('density = %6.1f cm-3' % den)
    print("")
    if printPop and ((tem is None) or (den is None)):
        self.log_.warn('Cannot print populations as tem or den is missing', calling=self.calling)
        printPop = False
    if printCrit and (tem is None):
        self.log_.warn('Cannot print critical densities as tem is missing', calling=self.calling)
        printCrit = False
    to_print = ''
    if printPop:
        to_print += 'Level   Populations  '
    if printCrit:
        to_print += 'Critical densities'
    if to_print != '':
        print(to_print)
    if printCrit:
        critdens = self.getCritDensity(tem)
    if printPop:
        pop = self.getPopulations(tem, den)
    for i in range(0, self.NLevels):
        lev_i = i + 1
        to_print = 'Level %1i:  ' % (lev_i)
        if printPop:
            to_print += "%.3E  " % (pop[i])
        if printCrit:
            to_print += "%.3E" % critdens[i]
        if printPop or printCrit:
            print(to_print)
    if printPop or printCrit:
        print('')

    if (tem is not None) and (den is not None):
        emis = self.getEmissivity(tem, den)
    for i in range(1, self.NLevels):
        if printA:
            for j in range(i):
                to_print = "{0:.3E}   ".format(np.float64(self.getA(i + 1, j + 1)))
                print(to_print, end="")
            print("")
        for j in range(i):
            if self.wave_Ang[i, j] > 10000.:
                to_print = "%10.2fm " % (self.wave_Ang[i, j] / 1e4)
            else:
                to_print = "%10.2fA " % self.wave_Ang[i, j]
            print(to_print, end="")
        print("")
        for j in range(i):
            print("    (%1i-->%1i) " % (i + 1, j + 1), end="")
        print("")
        if (tem is not None) and (den is not None):
            for j in range(i):
                print("  %.3E " % emis[i,j], end="")
        print("\n")
    if (tem is not None) and (den is not None):
        try:
            H1 = RecAtom('H', 1)
            print("# H-beta volume emissivity:")
            print("%.3E N(H+) * N(e-)  (erg/s)" % H1.getEmissivity(tem, den, 4, 2))
        except:
            pass

printTemDen(int_ratio, tem=-1, den=-1, lev_i1=-1, lev_j1=-1, lev_i2=-1, lev_j2=-1, wave1=-1, wave2=-1, maxError=0.001, method='nsect_recur', log=True, start_x=-1, end_x=-1, to_eval=None, nCut=30, maxIter=20)

Print result of getTemDen function. See getTemDen for more details.

Parameters:

Name Type Description Default
int_ratio

intensity ratio of the selected transition

required
tem

electronic temperature

-1
den

electronic density

-1
lev_i1

upper level of 1st transition

-1
lev_j1

lower level of 1st transition

-1
lev_i2

upper level of 2nd transition

-1
lev_j2

lower level of 2nd transition

-1
wave1

wavelength of 1st transition

-1
wave2

wavelength of 2nd transition

-1
maxError

tolerance on difference between input and computed ratio

0.001
method

numerical method for finding the root (nsect_recur, nsect_iter)

'nsect_recur'
log

log switch (default = True)

True
start_x

lower end of the interval to explore (default: lower end of collision strength temperature array)

-1
end_x

higher end of the interval to explore (default: higher end of collision strength temperature array)

-1
to_eval

expression to be evaluated, using either I (for transitions identified through atomic levels) or L (for transitions identified through wavelengths)

None
nCut

number of sections in which each step is cut. 2 would be dichotomy.

30
maxIter

maximum number of iterations

20

Usage:

O3.printTemDen(100, tem=10000, wave1=5007, wave2=4363)
Source code in pyneb/core/pynebcore.py
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
    def printTemDen(self, int_ratio, tem= -1, den= -1, lev_i1= -1, lev_j1= -1, lev_i2= -1, lev_j2= -1, wave1= -1, wave2= -1,
                    maxError=1.e-3, method='nsect_recur', log=True, start_x= -1, end_x= -1, to_eval=None,
                    nCut=30, maxIter=20):
        """ 
        Print result of getTemDen function. See getTemDen for more details.



        Parameters:
            int_ratio:    intensity ratio of the selected transition
            tem:          electronic temperature
            den:          electronic density
            lev_i1:       upper level of 1st transition
            lev_j1:       lower level of 1st transition
            lev_i2:       upper level of 2nd transition
            lev_j2:       lower level of 2nd transition
            wave1:        wavelength of 1st transition
            wave2:        wavelength of 2nd transition
            maxError:     tolerance on difference between input and computed ratio 
            method:       numerical method for finding the root (nsect_recur, nsect_iter)
            log:          log switch (default = True)
            start_x:      lower end of the interval to explore (default: lower end of collision 
                            strength temperature array)
            end_x:        higher end of the interval to explore (default: higher end of collision 
                            strength temperature array)
            to_eval:      expression to be evaluated, using either I (for transitions identified through 
                            atomic levels) or L (for transitions identified through wavelengths)
            nCut:        number of sections in which each step is cut. 2 would be dichotomy.
            maxIter:     maximum number of iterations

        **Usage:**

            O3.printTemDen(100, tem=10000, wave1=5007, wave2=4363)

        """
        if tem == -1:
            option = 'temperature'
            assume = den
            assume_str = 'density'
            assume_unit = 'cm-3'
            unit = 'K'
        if den == -1:
            option = 'density'
            assume = tem
            assume_str = 'temperature'
            assume_unit = 'K'
            unit = 'cm-3'

        result = self.getTemDen(int_ratio, tem=tem, den=den, lev_i1=lev_i1, lev_j1=lev_j1, lev_i2=lev_i2, lev_j2=lev_j2,
                                wave1=wave1, wave2=wave2, maxError=maxError, method=method, log=log, start_x=start_x,
                                end_x=end_x, to_eval=to_eval, nCut=nCut, maxIter=maxIter)
        print('Ion = %s' % self.elem + " " + int_to_roman(self.spec))
        print('Option = %s' % option)
        print('Assumed %s = %.0f %s' % (assume_str, assume, assume_unit))
        if to_eval is None:
            print('Assumed I(%i)/I(%i) ratio = %.0f' % (wave1, wave2, int_ratio))
        else:
            print('Assumed %s = %.0f' % (to_eval, int_ratio))
#        print 'method = %s' % method
#        print 'maxError on ratio %f' % maxError
        print('Calculated %s = %.0f %s' % (option, result, unit))

printTransition(wave)

Print info on transition associated to input wavelength.

Parameters:

Name Type Description Default
wave

wavelength in Angstrom (a float or a label: e.g., 5007, '5007A') or in micron (a label: '51.5m')

required

Usage:

O3.printTransition(4959)
Source code in pyneb/core/pynebcore.py
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
def printTransition(self, wave):
    """
    Print info on transition associated to input wavelength.

    Parameters:
        wave:      wavelength in Angstrom (a float or a label: e.g., 5007, '5007A') 
            or in micron (a label: '51.5m')

    **Usage:**

        O3.printTransition(4959)        
    """
    closestTransition = self._Transition(wave)
    relativeError = closestTransition[3] / closestTransition[2] - 1
    print('Input wave: {0:.1F}'.format(closestTransition[3]))
    print('Closest wave found: {0:.1F}'.format(closestTransition[2]))
    print('Relative error: {0:.0E} '.format(relativeError))
    print('Transition: {0[0]} -> {0[1]}'.format(closestTransition))
    return

EmissionLine

Bases: object

Define the emission line object, which is defined by the line parameters and the intensity parameters. The line parameters define the emitting ion, the wavelength or the transition, the label in PyNeb format, and a flag defining whether the line is a blend or a single transition. The intensity parameters describe the observed intensity, the observed uncertainty and the corrected uncertainty

Parameters:

Name Type Description Default
elem

symbol of the selected element

None
spec

ionization stage in spectroscopic notation (I = 1, II = 2, etc.)

None
wave

wavelength of the line

None
blend

blend flag (boolean)

False
to_eval

algebraic expression describing the emission line in terms of single transitions

None
label

line label in the standard PyNeb format

None
obsIntens

observed intensity

None
obsError

uncertainty on the observed intensity

None
errIsRelative

Boolean. True if the errors are relative to the intensities, False if they are in the same unit as the intensity (default: True)

True

Usage:

line = pn.EmissionLine('O', 3, 5007, obsIntens=[1.4, 1.3])

line = pn.EmissionLine(label = 'O3_5007A', obsIntens=320, corrected = True)
Source code in pyneb/core/pynebcore.py
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
class EmissionLine(object):
    """
    Define the emission line object, which is defined by the line parameters and the intensity 
        parameters.
    The line parameters define the emitting ion, the wavelength or the transition, the label 
        in PyNeb format, and a flag defining whether the line is a blend or a single transition. 
    The intensity parameters describe the observed intensity, the observed uncertainty and 
        the corrected uncertainty

    Parameters:
        elem:        symbol of the selected element
        spec:        ionization stage in spectroscopic notation (I = 1, II = 2, etc.)
        wave:        wavelength of the line
        blend:       blend flag (boolean)
        to_eval:     algebraic expression describing the emission line in terms of single transitions
        label:       line label in the standard PyNeb format
        obsIntens:   observed intensity
        obsError:    uncertainty on the observed intensity
        errIsRelative: Boolean. True if the errors are relative to the intensities, False if they
                      are in the same unit as the intensity (default: True)

    **Usage:**

        line = pn.EmissionLine('O', 3, 5007, obsIntens=[1.4, 1.3])

        line = pn.EmissionLine(label = 'O3_5007A', obsIntens=320, corrected = True)


    """ 
    def __init__(self, elem=None, spec=None, wave=None, blend=False, to_eval=None, label=None,
                 obsIntens=None, obsError=None, corrected=False, _unit=None, errIsRelative=True):

        self.log_ = log_ 
        self.calling = 'EmissionLine'
        self.corrected = corrected

        if label is None:
            self.elem = elem
            self.spec = int(spec)
            self.atom = self.elem + str(self.spec)
            self.wave = wave
            self.blend = blend
            self.atom, self.waveLabel, self.label = getLineLabel(elem, spec, wave, blend)
        else:
            self.label = label
            self.elem, self.spec, self.atom, self.wave, self.waveLabel, self.blend = parseLineLabel(label)
            if wave is not None:
                self.wave = wave

        if self.atom in LINE_LABEL_LIST:
            if (self.waveLabel in LINE_LABEL_LIST[self.atom]) or (self.label in BLEND_LIST):
                self.is_valid = True
                if to_eval is None:
                    if self.blend:
                        if self.waveLabel in LINE_LABEL_LIST[self.atom]:
                            self.to_eval = 'S("'+ str(self.waveLabel) + '")'
                        else:
                            self.to_eval = BLEND_LIST[self.label]
                    else: 
                        self.to_eval = 'L(' + str(self.wave) + ')'
                else:
                    self.to_eval = to_eval
            else:
                self.is_valid = False
                self.to_eval = None
                self.log_.warn('line {0} for atom {1} not valid'.format(self.waveLabel, self.atom), calling=self.calling)
                print(self.waveLabel, LINE_LABEL_LIST[self.atom])
        else:
                self.is_valid = False
                self.to_eval = None
                self.log_.warn('Atom {0} not valid'.format(self.atom), calling=self.calling)


        self.obsIntens = np.asarray(obsIntens, dtype=float)
        if self.corrected:
            self.corrIntens = np.asarray(obsIntens, dtype=float)
        else:
            self.corrIntens = np.zeros_like(obsIntens)

        # the following is not public, as we still have to think about it. 
        # Don't une it...
        self._obsIntens_n = np.zeros_like(obsIntens)
        self._corrIntens_n = np.zeros_like(obsIntens)
        self._unit = _unit

        if obsError is None:
            self.obsError = np.zeros_like(self.obsIntens)
        else:
            if errIsRelative:
                self.obsError = np.asarray(obsError, dtype=float)
            else:
                self.obsError = np.asarray(obsError, dtype=float) / self.obsIntens
        if self.corrected:
            if errIsRelative:
                self.corrError = np.asarray(self.obsError, dtype=float)
            else:
                self.corrError = np.asarray(self.obsError, dtype=float) / self.corrIntens
        else:
            self.corrError = np.zeros_like(self.obsError)
    ##            
    # @var elem
    # Symbol of the element


    def correctIntens(self, RC, normWave=None):
        """
        Correct from extinction. The corrIntens and corrError values of the line 
        are updated according to the RedCorr object


        Parameters:
            RC:        an instantiation of the pn.RedCorr class 
            normWave:  a wavelength for the normalisation of the correction, e.g. 4861.  

        """
        if not isinstance(RC, RedCorr):
            self.log_.error('Trying to correct with something that is not a RedCor object',
                          calling=self.calling)
            return None
        if self.wave > 0.0:
            with np.errstate(invalid='ignore'):
                self.corrIntens = self.obsIntens * RC.getCorr(self.wave, normWave)
                self.log_.debug('Correcting {} with wave = {}'.format(self.label, self.wave),
                                calling='EmissionLine.correctIntens')
        else:
            self.corrIntens = self.obsIntens
        self.corrError = self.obsError # error is supposed to be relative.


    def addObs(self, newObsIntens, newObsError=None):
        """
        Add observed values to an existing line. 

        Parameters:
            newObsIntens:    observed intensity of the line
            newObsError:     error on the observed intensity (optional)

        """
        self.obsIntens = np.append(self.obsIntens, newObsIntens)
        if newObsError is None:
            self.obsError = np.append(self.obsError, np.zeros_like(newObsIntens))
        else:
            self.obsError = np.append(self.obsError, newObsError)
        if self.corrected:
            self.corrIntens = np.append(self.corrIntens, newObsIntens)
            if newObsError is None:
                self.corrError = np.append(self.corrError, np.zeros_like(newObsIntens))
            else:
                self.corrError = np.append(self.corrError, newObsError) 
        else:
            self.corrIntens = np.append(self.corrIntens, np.zeros_like(newObsIntens))
            self.corrError = np.append(self.corrError, np.zeros_like(newObsIntens))


    def printLine(self):
        """
        Provide information on the line: atom, label, to_eval, as well as the intensities and errors

        **Usage:**

            line.printLine()

        """
        print("""Line {0.atom} {0.label} evaluated as {0.to_eval}
Observed intensity: {0.obsIntens}
Observed error: {0.obsError}
Corrected intensity: {0.corrIntens}
Corrected error: {0.corrError}""".format(self))


    def __repr__(self):
        return 'Line {0.atom} {0.label}'.format(self)

addObs(newObsIntens, newObsError=None)

Add observed values to an existing line.

Parameters:

Name Type Description Default
newObsIntens

observed intensity of the line

required
newObsError

error on the observed intensity (optional)

None
Source code in pyneb/core/pynebcore.py
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
def addObs(self, newObsIntens, newObsError=None):
    """
    Add observed values to an existing line. 

    Parameters:
        newObsIntens:    observed intensity of the line
        newObsError:     error on the observed intensity (optional)

    """
    self.obsIntens = np.append(self.obsIntens, newObsIntens)
    if newObsError is None:
        self.obsError = np.append(self.obsError, np.zeros_like(newObsIntens))
    else:
        self.obsError = np.append(self.obsError, newObsError)
    if self.corrected:
        self.corrIntens = np.append(self.corrIntens, newObsIntens)
        if newObsError is None:
            self.corrError = np.append(self.corrError, np.zeros_like(newObsIntens))
        else:
            self.corrError = np.append(self.corrError, newObsError) 
    else:
        self.corrIntens = np.append(self.corrIntens, np.zeros_like(newObsIntens))
        self.corrError = np.append(self.corrError, np.zeros_like(newObsIntens))

correctIntens(RC, normWave=None)

Correct from extinction. The corrIntens and corrError values of the line are updated according to the RedCorr object

Parameters:

Name Type Description Default
RC

an instantiation of the pn.RedCorr class

required
normWave

a wavelength for the normalisation of the correction, e.g. 4861.

None
Source code in pyneb/core/pynebcore.py
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
def correctIntens(self, RC, normWave=None):
    """
    Correct from extinction. The corrIntens and corrError values of the line 
    are updated according to the RedCorr object


    Parameters:
        RC:        an instantiation of the pn.RedCorr class 
        normWave:  a wavelength for the normalisation of the correction, e.g. 4861.  

    """
    if not isinstance(RC, RedCorr):
        self.log_.error('Trying to correct with something that is not a RedCor object',
                      calling=self.calling)
        return None
    if self.wave > 0.0:
        with np.errstate(invalid='ignore'):
            self.corrIntens = self.obsIntens * RC.getCorr(self.wave, normWave)
            self.log_.debug('Correcting {} with wave = {}'.format(self.label, self.wave),
                            calling='EmissionLine.correctIntens')
    else:
        self.corrIntens = self.obsIntens
    self.corrError = self.obsError # error is supposed to be relative.

printLine()

Provide information on the line: atom, label, to_eval, as well as the intensities and errors

Usage:

line.printLine()
Source code in pyneb/core/pynebcore.py
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
    def printLine(self):
        """
        Provide information on the line: atom, label, to_eval, as well as the intensities and errors

        **Usage:**

            line.printLine()

        """
        print("""Line {0.atom} {0.label} evaluated as {0.to_eval}
Observed intensity: {0.obsIntens}
Observed error: {0.obsError}
Corrected intensity: {0.corrIntens}
Corrected error: {0.corrError}""".format(self))

Observation

Bases: object

Source code in pyneb/core/pynebcore.py
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
class Observation(object):
    def __init__(self, obsFile=None, fileFormat='lines_in_cols', delimiter=None, err_default=0.10,
                 corrected=False, errIsRelative=True, correcLaw='F99', errStr='err',
                 addErrDefault = False, Cutout2D_position=None, Cutout2D_size=None):
        """
        Define the observation object, which is a collection of observated intensities of one or more
        emission lines for one or more objects, with the corresponding errors.
        The observed intensities are read from a file or filled in by the addLine method.
        Includes an extinction correction object (pyneb.RedCorr) as Observation.extinction.

        Parameters:
            obsFile:       name of the file containing the observations. May be a file object or a file name 
                             If the fileFormat is 'fits_IFU', the obsFile keyword is of the form e.g.:
                             'dir/ngc6778_MUSE_*.fits' where * is of the form O3_5007A.
                             The associated error file must be named the same way, using errStr keyword value 
                             e.g. dir/ngc6778_MUSE_O3_5007A_err.fits
            fileFormat:    format of the data file, depending on how the wavelengths are ordered.
                            Available formats are :
                            - 'lines_in_cols' : Each object is on a different row. Each column corresponds to a given emission line. 
                               Line labels with tailing "e" are for errors on line intensities.
                            - 'lines_in_cols2' : Each object is on a different row. Same as 'lines_in_cols' but using genfromtxt to read the file.
                               Allows undefined values.
                            - 'lines_in_rows' : Each object is on a different column. Each row corresponds to a given emission line.
                            - 'lines_in_rows_err_cols' : Each object is on a different column. Each row corresponds to a given emission line. 
                               For each object (eg. "IC418"), an additional column (named eg "errIC418") contains the errors on the line intensities.
                            - 'fits_IFU': each emission line is stored into a fits file
            delimiter:     character separating entries 
            err_default:   [0.10] default uncertainty assumed on intensities. Will overwrite the error from the file.
            corrected:     Boolean. True if the observed intensities are already corrected from extinction
                                (default: False)
            errIsRelative: Boolean. True if the errors are relative to the intensities, False if they
                                are in the same unit as the intensity (default: True)
            correcLaw:   ['F99'] extinction law used to correct the observed lines.
            errStr (str):        String used to identify error file when fileFormat is fits_IFU
            addErrDefault: if True, the default error is always quadratically added to the read error.
            Cutout2D_position:
            Cutout2D_size: In case of reading fits images, crop the image to those pixel limits

        **Example:**

        Read a file containing corrected intensities:

            obs = pn.Observation('obs.dat', corrected = True)

        To obtain a dictionary with the observed  corrected intensities:

            i_cor = {label: obs.getLine(label = label).corrIntens for label in obs.lineLabels}

        """        
        self.log_ = log_ 
        self.calling = 'Observation'
        self.lines = []
        self.names = []
        self.extinction = RedCorr(law=correcLaw)
        self.corrected = corrected
        self.addErrDefault = addErrDefault
        self.MC_added = False
        self.N_MC = 0
        self.fits_shape = None
        self.data_shape = None
        if self.corrected:
            self.extinction.law = 'No correction'
        if obsFile is not None:
            self.readData(obsFile=obsFile, fileFormat=fileFormat, delimiter=delimiter,
                          err_default=err_default, corrected=corrected, errIsRelative=errIsRelative,
                          errStr=errStr, 
                          Cutout2D_position=Cutout2D_position, Cutout2D_size=Cutout2D_size)
    ##            
    # @var log_
    # myloggin object
    # @var extinction
    # RedCor object


    def addLine(self, line):
        """
        Add a line to an existing observation

        Parameters:
            line:    the selected emission line (an instance of EmissionLine)

        """
        if not isinstance(line, EmissionLine):            
            self.log_.error('Trying to add an inappropriate record to observations', calling=self.calling)
            return None
        if self.corrected and not line.corrected:
            line.corrected = True
            self.correctData(line)
        self.lines.append(line)

    def removeLine(self, lineLabel):
        """

        """

        for l in self.lines:
            if l.label == lineLabel:
                self.lines.remove(l)

    def fillObs(self, lineLabel, default=np.nan):
        """
        Create a fake observation of a given line, filled with a given value.
        Parameters:
            lineLabel: the label of the new line. If the label corresponds to an already 
                defined observation, nothing is done and a warning is issued.
            default: the value of the fake observations. Default is np.nan
        """

        if lineLabel not in self.lineLabels:
            newLine = EmissionLine(label=lineLabel, obsIntens=default*np.ones(self.n_obs))
            self.addLine(newLine)
        else:
            log_.warn('Line {0} already in obs'.format(lineLabel), calling = self.calling)

    def addObs(self, name, newObsIntens, newObsError=None):
        """
        Add an observation (i.e. a list of intensities corresponding to a new object) to the existing set.

        Parameters:
            name:            name of the new observation/object
            newObsIntens:    value(s) of the line intensities. Length must match Observation.n_lines

        """
        if np.ndim(newObsIntens) == 0:
            newObsIntens = [newObsIntens]
        if len(newObsIntens) != self.n_lines:
            self.log_.error('Length of observations to be added does not match n_lines = {0}'.format(self.n_lines),
                            calling=self.calling)
            return
        if name in self.names:
            self.log_.error('Name {0} already exists'.format(name))
            return
        for i, line in enumerate(self.lines):
            if newObsError is None:
                line.addObs(newObsIntens[i])
            else:
                line.addObs(newObsIntens[i], newObsError[i])
        self.names.append(name)

    def addSum(self, labelsToAdd, newLabel, to_eval=None):
        """
        Add a new observation. The intensity is the sum of the intensities of 
        the lines defined by the tupple labelsToAdd. The error is the quadratic sum of the absolute errors.


        **Example:**

            addSum(('O1r_7771A', 'O1r_7773A', 'O1r_7775A'), 'O1r_7773A+', to_eval = 'S("7773+")')
        """

        intenses = self.getIntens(returnObs=True)
        errors = self.getError(returnObs=True)
        I = intenses[labelsToAdd[0]]
        E = errors[labelsToAdd[0]] * I


        atom = labelsToAdd[0].split('_')[0]

        for label in labelsToAdd[1:]:
            if label.split('_')[0] != atom:
                self.log_.error('Can not add lines from different atoms {} and {}.'.format(
                    label.split('_')[0],atom))
            I += intenses[label]
            E = np.sqrt(E**2 + (errors[label]*I)**2)
        if to_eval is None:
            to_eval = 'S("{}")'.format(newLabel.split('_')[1])
        E = E / I
        newLine = EmissionLine(label=newLabel, obsIntens=I, obsError=E, 
                                  corrected=False, errIsRelative=True, 
                                  to_eval=to_eval)
        self.addLine(newLine)


    @property
    def lineLabels(self):
        """
        Property
        Array of labels of the lines 

        """
        return np.asarray([line.label for line in self.lines])   

    @property
    def n_lines(self):
        """
        Property
        Number of lines

        """
        return len(self.lines)

    @property
    def n_valid_lines(self):
        """
        Property
        Number of valid lines (i.e., lines with labels recognized by PyNeb)

        """
        return len([line for line in self.lines if line.is_valid])

    @property
    def n_obs(self):
        """
        Property
        Number of observations. If the number of observations varies from one line to the other,
            returns the number of observations for each line as an array.

        """
        n_obs = np.asarray([l.obsIntens.size for l in self.lines])
        for n in n_obs:
            if n != n_obs[0]:
                return n_obs

        return n_obs[0]


    @property
    def n_obs_origin(self):
        """
        Property
        Number of observations which are not from MonteCarlo (i.e. without -MC- in the name)
        """
        return len([n for n in self.names if '-MC-' not in n])

    def getLine(self, elem=None, spec=None, wave=None, label=None, blend=False, i=None, j=None):
        """
        Return the lines corresponding to elem-spec-wave or to the label.

        """
        if label is None:
            label = getLineLabel(elem, spec, wave, blend)[2]
        lines = [line for line in self.lines if line.label == label.strip()]
        n_lines = len(lines)
        if n_lines == 0:
            self.log_.warn('No line for {0} from {1}{2} at wavelength {3} (blend={4})'.format(label, elem, spec, wave, blend),
                           calling=self.calling)
            return None
        elif n_lines == 1:
            return lines[0]
        else:
            return np.asarray(lines)


    def getSortedLines(self, crit='atom'):
        """
        Return a list of lines sorted by atoms or wavelengths.

        Parameters:
            crit:   criterion to sort the line list ('atom' [default] or 'wave')

        """
        if crit == 'atom':
            return sorted(self.lines, key=lambda line: line.atom + str(line.wave))
        elif crit == 'wave':
            return sorted(self.lines, key=lambda line: line.wave)
        elif crit == 'mass':
            return sorted(self.lines, key=lambda line: (Z[line.elem], line.spec, line.wave))
        else:
            self.log_.error('crit = {0} is not valid'.format(crit), calling=self.calling + '.getSortedLines')


    def getUniqueAtoms(self):
        """
        Return a numpy.ndarray of the atoms of the observed lines. If an atom emits 
        more than one line, it is returned only once (numpy.unique is applied 
        to the list before returning).

        """
        return np.unique([l.atom for l in self.lines])


    def readData(self, obsFile, fileFormat='lines_in_cols', delimiter=None, err_default=0.10, corrected=False,
                 errIsRelative=True, errStr='err', Cutout2D_position=None, Cutout2D_size=None):
        """
        Read observational data from an ascii file. The lines can be listed either in columns or in rows
        and the observed objects vary in the other direction. The uncertainty on the line intensities
        can be read from the file, or a constant relative value can be assumed.
        The lines must be identified by a label in PyNeb's format ion_wave (e.g., 'O3_5007'); the list of ions and
        corresponding wavelengths can also be found in pn.LINE_LABEL_LIST.
        The following optional fields may also be included (without quotes): 'NAME' (object's name, in one string), 
        'E(B-V)', 'cHbeta', and 'e' (observational error).


        Parameters:
            obsFile:        file containing the observations. May be a file object or a string.
                             If the fileFormat is 'fits_IFU', the obsFile keyword is of the form e.g.:
                             'dir/ngc6778_MUSE_*.fits' where * is of the form O3_5007A.
                             The associated error file must be named the same way, using errStr keyword value 
                             e.g. dir/ngc6778_MUSE_O3_5007A_err.fits
            fileFormat:     emission lines vary across columns ('lines_in_cols', default) or 
                                across rows ('lines_in_rows'), or across rows with errors in columns 
                                ('lines_in_rows_err_cols') in which case the column label must start with "err"

                                The format may also be 'fits_IFU', in which case each emission line comes
                                from a different fits file

            delimiter:      field delimiter (default: None)  
            err_default:    default uncertainty on the line intensities
            corrected:      Boolean. True if the observed intensities are already corrected from extinction
                                 (default: False)
            errIsRelative:  Boolean. True if the errors are relative to the intensities, False if they
                                 are in the same unit as the intensity (default: False)
            errStr:         string to identify the error file in case the fileFormat is fits_IFU.
            Cutout2D_position: In case of reading fits images, crop the image to those pixel limits
            Cutout2D_size: In case of reading fits images, crop the image to those pixel limits

        """    
        format_list = ['lines_in_cols', 'lines_in_cols2', 'lines_in_rows', 
                       'lines_in_rows_err_cols', 'fits_IFU']
        if fileFormat not in format_list:
            self.log_.error('unknown format {0}'.format(fileFormat), calling='Observation.readData')

        if type(obsFile) is str and fileFormat not in ('fits_IFU',):
            f = open(obsFile, 'r')
            closeAfterUse = True
        else:
            f = obsFile
            closeAfterUse = False

        if fileFormat == 'lines_in_cols':
            hdr = f.readline()
            labels = hdr.split(delimiter)
            labels = [l.strip() for l in labels]
            data = f.readlines()
            if closeAfterUse:
                f.close()
            self.names = [dd.split(delimiter)[0].strip() for dd in data]
            data_tab = np.asarray([[dd.split(delimiter)[i] for dd in data] for i in np.arange(len(labels))])

            for i, label in enumerate(labels):
                if label == 'NAME':
                    pass
                elif label == 'cHbeta':
                    self.extinction.cHbeta = data_tab[i].astype(np.float32)
                elif label == 'E(B-V)':
                    self.extinction.E_BV = data_tab[i].astype(np.float32)         
                elif label[-1] != 'e':
                    intens = data_tab[i].astype(np.float32)
                    try:
                        i_error = labels.index(label + 'e')
                        error = data_tab[i_error].astype(np.float32)
                        if not errIsRelative:
                            error = quiet_divide(error, intens)
                        if self.addErrDefault:
                            error = np.sqrt(error**2 + err_default**2)
                    except:
                        self.log_.message('No error found for line {0}'.format(label), calling=self.calling)
                        error = data_tab[1].astype(np.float32) * 0. + err_default
                    try:
                        line2add = EmissionLine(label=label, obsIntens=intens, obsError=error)
                    except:
                        self.log_.warn('Unknown line label {0}'.format(label), calling=self.calling)
                    try:
                        self.addLine(line2add)
                        self.log_.message('adding line {0}'.format(label), calling=self.calling)
                    except:
                        self.log_.warn('Impossible to add line'.format(label), calling=self.calling)
        elif fileFormat == 'lines_in_cols2':
            if closeAfterUse:
                f.close()
            data_tab = np.genfromtxt(obsFile, dtype=None, delimiter=delimiter, names=True, deletechars='')
            for label in data_tab.dtype.names:
                if label == 'cHbeta':
                    self.extinction.cHbeta = data_tab[label]
                elif label == 'E(B-V)':
                    self.extinction.E_BV = data_tab[label]
                elif label == 'NAME':
                    self.names = list(data_tab[label])
                elif label == 'NAME2':
                    try:
                        names2 = list(data_tab[label])
                        self.names = [n1 + '_' + n2 for n1, n2 in zip(self.names, names2)]
                    except:
                        pass
                elif label[-1] != 'e':
                    if data_tab[label].dtype.type != np.string_:
                        intens = data_tab[label]
                        try:
                            error = data_tab[label + 'e']
                            if not errIsRelative:
                                error = error / intens
                            if self.addErrDefault:
                                error = np.sqrt(error**2 + err_default**2)
                        except:
                            self.log_.message('No error found for line {0}'.format(label), calling=self.calling)
                            error = np.ones_like(data_tab[label]) * err_default
                        try:
                            line2add = EmissionLine(label=label, obsIntens=intens, obsError=error)
                        except:
                            self.log_.warn('unkown line label {0}'.format(label), calling=self.calling)
                            print(label, intens, error)
                        try:
                            self.addLine(line2add)
                            self.log_.message('adding line {0}'.format(label), calling=self.calling)
                        except:
                            self.log_.warn('Impossible to add line'.format(label), calling=self.calling)
                            print(label, intens, error)
                    else:
                        self.log_.warn('Skipped {0}'.format(label), calling=self.calling)

        elif fileFormat == 'lines_in_rows':
            hdr = f.readline()
            self.names = hdr.split(delimiter)[1:]
            self.names =  [l.strip() for l in self.names]
            data = f.readlines()
            if closeAfterUse:
                f.close()

            labels = [dd.split(delimiter)[0].strip() for dd in data if len(dd.strip()) > 0]
            data_tab = np.asarray([[dd.split(delimiter)[i + 1] for dd in data if len(dd.strip()) > 0] for i in np.arange(len(self.names))])
            data_tab = data_tab.astype(np.float32)
            for i, label in enumerate(labels):
                if label == 'cHbeta':
                    self.extinction.cHbeta = data_tab[:, i]
                elif label == 'E(B-V)':
                    self.extinction.E_BV = data_tab[:, i]
                elif label[-1] != 'e':
                    intens = data_tab[:, i]
                    try:
                        i_error = labels.index(label + 'e')
                        error = data_tab[:, i_error]
                        if not errIsRelative:
                            error = error / intens
                        if self.addErrDefault:
                            error = np.sqrt(error**2 + err_default**2)
                    except:
                        self.log_.message('No error found for line {0}'.format(label), calling=self.calling)
                        error = np.ones_like(data_tab[:, 1]) * err_default
                    try:
                        line2add = EmissionLine(label=label, obsIntens=intens, obsError=error)
                    except:
                        self.log_.warn('unkown line label {0}'.format(label), calling=self.calling)
                        print(label, intens, error)
                    try:
                        self.addLine(line2add)
                        self.log_.message('adding line {0}'.format(label), calling=self.calling)
                    except:
                        self.log_.warn('Impossible to add line'.format(label), calling=self.calling)
                        print(label, intens, error)

        elif fileFormat == 'lines_in_rows_err_cols':

            if closeAfterUse:
                f.close()

            data_tab = np.genfromtxt(obsFile, dtype=None, delimiter=delimiter, names=True)
            self.names = [name for name in data_tab.dtype.names[1::] if name[0:3] != 'err']
            error_names = [name for name in data_tab.dtype.names if name[0:3] == 'err']
            if len(self.names) != len(error_names):
                self.log_.error('Number of columns for intensities <> number of columns for errors {} {}'.format(self.names,
                                                                                                                 error_names),
                              calling=self.calling)
                return None
            #names_locations = [name in self.names for name in data_tab.dtype.names]
            #errors_locations = [name[0:3] == 'err' for name in data_tab.dtype.names]
            for i, label in enumerate(data_tab['LINE']):
                if sys.version_info.major >= 3:
                    label = label.decode()
                label = label.strip()
                if label == 'cHbeta':
                    self.extinction.cHbeta = np.array([data_tab[i][name] for name in self.names])
                elif label == 'E(B-V)':
                    self.extinction.E_BV = np.array([data_tab[i][name] for name in self.names])
                else:
                    intens = np.array([data_tab[i][name] for name in self.names])
                    error = np.array([data_tab[i][name] for name in error_names])
                    if not errIsRelative:
                        error = error / intens
                    if self.addErrDefault:
                        error = np.sqrt(error**2 + err_default**2)
                    try:
                        line2add = EmissionLine(label=label, obsIntens=intens, obsError=error)
                    except:
                        self.log_.warn('unkown line label {0}'.format(label), calling=self.calling)
                        print(label, intens, error)
                    try:
                        self.addLine(line2add)
                        self.log_.message('adding line {0}'.format(label), calling=self.calling)
                    except:
                        self.log_.warn('Impossible to add line'.format(label), calling=self.calling)
                        print(label, intens, error)

        elif fileFormat == 'fits_IFU':
            path = Path(obsFile)
            dir_ = path.parent
            pattern = path.name
            files = dir_.glob(pattern)
            self.log_.debug('path: {}, dir_: {}, pattern: {}'.format(path, dir_, pattern),
                            calling='Observation.readData')
            str1, str2 = pattern.split('*')
            for f in files:
                obs_file = f.name
                if f.suffix == '.fits' and errStr not in obs_file:
                    self.log_.debug('analysing {}'.format(f), calling='Observation.readData')
                    lineID = strExtract(obs_file, str1, str2)
                    spl = lineID.split('_')
                    if len(spl) == 2:
                        atom = spl[0]
                        line = spl[1]
                        if atom in LINE_LABEL_LIST:
                            self.log_.message('Reading {}_{} from {}'.format(atom, line, f.name),
                                              calling='Observation.readData')
                            fits_hdu = pyfits.open(f)[0]
                            fits_data = fits_hdu.data
                            self.origin_fits_shape = fits_data.shape
                            self.fits_header = fits_hdu.header
                            self.wcs = WCS(self.fits_header).celestial
                            if Cutout2D_position is not None:
                                self.log_.debug('Cutout2D applied to data shape {}.'.format(fits_data.shape),
                                                calling='Observation.readData')
                                C2D = Cutout2D(data=fits_data, position=Cutout2D_position, 
                                               size=Cutout2D_size, wcs=WCS(fits_hdu.header), mode='trim',
                                               copy=True)
                                fits_data = C2D.data
                                self.wcs = C2D.wcs
                            if self.fits_shape is None:
                                self.fits_shape = fits_data.shape
                            else:
                                if fits_data.shape != self.fits_shape:
                                    self.log_.error('data shape in file {} is {}. Previous shape was {}.'.format(
                                                    f.name, fits_data.shape, self.fits_shape))
                            fits_data = fits_data.ravel()
                            err_file = dir_ / Path(f.stem+'_' + errStr + '.fits')
                            if err_file.exists():
                                self.log_.message('Reading error {}_{} from {}'.format(atom, line, err_file.name),
                                                  calling='Observation.readData')
                                err_fits_hdu = pyfits.open(err_file)[0]
                                if err_fits_hdu.data.shape != self.origin_fits_shape:
                                    self.log_.error('error shape in file {} is {}. data shape is {}.'.format(
                                                    err_file.name, err_fits_hdu.data.shape, self.fits_shape))
                                err_fits_data = err_fits_hdu.data
                                if Cutout2D_position is not None:
                                    C2D = Cutout2D(data=err_fits_data, position=Cutout2D_position, 
                                                   size=Cutout2D_size, mode='trim',
                                                   copy=True)
                                    err_fits_data = C2D.data
                                err_fits_data = err_fits_data.ravel()
                                if not errIsRelative:
                                    with np.errstate(divide='ignore', invalid='ignore'):
                                        err_fits_data = err_fits_data / fits_data
                                if self.addErrDefault:
                                    err_fits_data = np.sqrt(err_fits_data**2 + err_default**2)
                            else:
                                self.log_.message('No error file found for {}'.format(f.name),
                                                  calling='Observation.readData')                                
                                err_fits_data  = np.ones_like(fits_data) * err_default
                            self.addLine(EmissionLine(label=lineID,
                                                      obsIntens=fits_data, 
                                                      obsError=err_fits_data, 
                                                      corrected=corrected, errIsRelative=True))
                        else:
                            self.log_.debug('atom {} not in LINE_LABEL_LIST'.format(atom), 
                                            calling='Observation.readData')

            self.names = ['{}_{}'.format(str1, i) for i in range(self.n_obs)]
            self.data_shape = self.fits_shape

        if corrected:
            self.correctData()


    def getIntens(self, returnObs=False, obsName=None):
        """
        Return the line intensities in form of a dictionary with line labels as keys.

        Parameters:
            returnObs (bool):  If False (default), prints the corrected values. 
                            If True, prints the observed value. 
            obsName:    name of an observation. If not set or None, all the observations are printed

        """
        if obsName is not None:
            if obsName in self.names:
                obsIndex = self.names.index(obsName)
            else:
                self.log_.error('Name {} is not an Observation name'.format(obsName))
                return None
        else:
            obsIndex = np.arange(self.n_obs)
        to_return = {}
        for line in self.lines:
            if returnObs:
                to_return[line.label] = line.obsIntens[obsIndex]
            else:
                to_return[line.label] = line.corrIntens[obsIndex]
        return to_return


    def getError(self, returnObs=False, obsName=None):
        """
        Return the line intensity error in form of a dictionary with line labels as keys.

        Parameters:
            returnObs:  if False (default), prints the corrected values. 
                            If True, prints the observed value. 
            obsName:    name of an observation. If not set or None, all the observations are printed

        """
        if obsName is not None:
            if obsName in self.names:
                obsIndex = self.names.index(obsName)
            else:
                self.log_.error('Name {} is not an Observation name'.format(obsName))
                return None
        else:
            obsIndex = np.arange(self.n_obs)
        to_return = {}
        for line in self.lines:
            if returnObs:
                to_return[line.label] = line.obsError[obsIndex]
            else:
                to_return[line.label] = line.corrError[obsIndex]
        return to_return


    def printIntens(self, returnObs=False, obsName=None):
        """
        Print the line intensities.

        Parameters:
            returnObs:   if False (default), prints the corrected values. 
                            If True, prints the observed value. 
            obsName:     name of an observation. Is unset or None, all the observations are printed

        """    
        if obsName is not None:
            if obsName in self.names:
                obsIndex = np.array((self.names.index(obsName)))
            else:
                self.log_.error('Name {} is not an Observation name'.format(obsName))
                return None
        else:
            obsIndex = np.arange(self.n_obs)
        for line in self.lines:
            if isinstance(line.corrIntens[obsIndex], float):
                if returnObs:
                    to_print = np.array((line.obsIntens[obsIndex],))
                else:
                    to_print = np.array((line.corrIntens[obsIndex],))
            else:
                if returnObs:
                    to_print = line.obsIntens[obsIndex]
                else:
                    to_print = line.corrIntens[obsIndex]
            if returnObs:
                print('{:10}'.format(line.label), ' '.join(('{:8.3f}'.format(l) for l in to_print)))
            else:
                print('{:10}'.format(line.label), ' '.join(('{:8.3f}'.format(l) for l in to_print)))


    def def_EBV(self, label1="H1r_6563A", label2="H1r_4861A", r_theo=2.85):
        """
        Define the extinction parameter using the ratio of 2 lines.
        Calls extinction.setCorr to set the EBV and cHbeta according to the parameters.
        Once this is done, one may call correctData to compute the EmissionLine.corrIntens

        Parameters:
            label1: [EmissionLine.label] observed line whose intensities are used 
            label2: [EmissionLine.label] observed line whose intensities are used
            r_theo [float] theoretical line ratio

        """
        line1 = self.getLine(label=label1)
        line2 = self.getLine(label=label2)
        if line1 is None:
            self.log_.error('{0} is not a valid label or is not observed'.format(line1), calling=self.calling)
            return None
        if line2 is None:
            self.log_.error('{0} is not a valid label or is not observed'.format(line2), calling=self.calling)
            return None
        with np.errstate(divide='ignore'):
            obs_over_theo = (line1.obsIntens / line2.obsIntens) / r_theo 
        self.extinction.setCorr(obs_over_theo, line1.wave, line2.wave)


    def __normalize(self, label='H1_4861A'):
        """
        Normalize the line intensities to a reference line (Hbeta by default).
        Not yet implemented

        """
        if "=" in label:
            line_label, factor = label.split('=')
            factor = np.float64(factor)
        else:
            line_label = label
            factor = 1.
        line_norm = self.getLine(label=line_label) 
        if line_norm is None:
            self.log_.warn('No normalization possible as {0} not found'.format(line_label), calling=self.calling)
            return None
        for line in self.lines:
            line._obsIntens_n = line.obsIntens / (line_norm.obsIntens * factor)
            line._unit = line_label.strip()


    def correctData(self, line=None, normWave=None):
        """
        Correct the line intensities with the correction computed with the RedCorr class (extinction.py)
        The result is stored in line.corrIntens (corrected intensity in absolute units).

        """
        if line is None:
            line = self.lines
        if np.ndim(line) != 0:
            for l in line:
                self.correctData(l, normWave=normWave)
        else:
            if not isinstance(line, EmissionLine):
                self.log_.error('Trying to correct something that is not a line', calling=self.calling)
                return None  
            line.correctIntens(self.extinction, normWave=normWave)

            """            
            # the following is commented for now, we'll see latter how to implement normalized intensities.
            if line._unit is not None:
                try:
                    line_norm = self.getLine(label=line._unit)
                    line._corrIntens_n = line.obsIntens_n * self.extinction.getCorr(line.wave, line_norm.wave)
                except:
                    log_.warn('No normalized correction for {0}'.format(line), calling='Observation.correctData')
                    line._corrIntens_n = None
            """

    def setAllErrors(self, err_default):
        """
        Set the relative uncertainty of all emission lines to a common constant value

        Parameters:
            err_default:     default value of the relative uncertainty

        """
        for line in self.lines:
            line.obs_err = np.ones_like(line.obs_err) * err_default



    def addMonteCarloObs(self, N=0, i_obs=None, random_seed=None):
        """
        Adding MonteCarlo random-gauss values of fake observations to an obs object.
        The names of the fake observations will be OriginalName-MC-n, n ranging from 0 to N-1

        Parameters:
            N: number of new observations to be added for each original observation.
            i_obs: used in case only a given observations needs to be treated
            random_seed: [default] used to initialize the numpy random generator
        """
        if self.MC_added:
            self.log_.error('Monte Carlo already applied to this observation', calling='addMonteCarloObs')
        n_lines = self.n_lines
        n_obs = self.n_obs
        if i_obs is None:
            self.log_.message('Entering', calling='addMonteCarloObs')
            np.random.seed(random_seed)
            for l in self.lines:
                l_ori = l.obsIntens
                e_ori = l.obsError
                l_new = np.repeat(l_ori[:, np.newaxis], N+1, axis=1)
                e_new = np.repeat(e_ori[:, np.newaxis], N+1, axis=1)
                norm = np.random.standard_normal(l_new.shape)
                l_new *= (1 + e_new * norm)
                l_new[:,0] = l_ori
                l.obsIntens = l_new.ravel()
                l.obsError = e_new.ravel()
                if self.corrected:
                    l.corrIntens = l_new.ravel()
                    l.corrError = e_new.ravel()
                self.log_.debug('Adding MC to {}. {} {} {} {}'.format(l, l_new.shape, 
                                                                      l_new.ravel().shape, 
                                                                      l.obsIntens.shape,
                                                                      l.corrIntens.shape), 
                                calling='addMonteCarloObs')
            new_names = np.repeat(np.asarray(self.names)[:, np.newaxis], N+1, axis=1)
            MC_names = np.asarray(['-MC-{}'.format(i) for i in np.arange(N+1)])
            MC_names[0] = ''
            self.names = np.core.defchararray.add(new_names , MC_names).tolist()[0]
            self.log_.message('Leaving', calling='addMonteCarloObs')        
        else:
            if self.corrected:
                returnObs=False
            else:
                returnObs=True
            intens = np.array([self.getIntens(returnObs=returnObs)[label] for label in self.lineLabels])[:,i_obs] # n_lines
            error = np.array([self.getError(returnObs=returnObs)[label] for label in self.lineLabels])[:,i_obs]
            all_new_obs = np.random.standard_normal((N, n_lines))

            for i in range(N):
                new_obs = intens * (all_new_obs[i,:] * error + 1)
                new_obs[new_obs < 0.] = 0.
                self.addObs('{0}-MC-{1}'.format(self.names[i_obs], i), new_obs, error)
        self.MC_added = True
        self.N_MC = N
        if self.fits_shape is not None:    
            self.data_shape = (self.fits_shape[0], self.fits_shape[1], self.N_MC+1)
        else:
            self.data_shape = (self.N_MC+1)

    def reshape(self, data):
        """
        Return data in shape of the original data (use with fits IFUs and/or MC)
        """
        return np.reshape(data, self.data_shape)

lineLabels property

Property Array of labels of the lines

n_lines property

Property Number of lines

n_obs property

Property Number of observations. If the number of observations varies from one line to the other, returns the number of observations for each line as an array.

n_obs_origin property

Property Number of observations which are not from MonteCarlo (i.e. without -MC- in the name)

n_valid_lines property

Property Number of valid lines (i.e., lines with labels recognized by PyNeb)

__init__(obsFile=None, fileFormat='lines_in_cols', delimiter=None, err_default=0.1, corrected=False, errIsRelative=True, correcLaw='F99', errStr='err', addErrDefault=False, Cutout2D_position=None, Cutout2D_size=None)

Define the observation object, which is a collection of observated intensities of one or more emission lines for one or more objects, with the corresponding errors. The observed intensities are read from a file or filled in by the addLine method. Includes an extinction correction object (pyneb.RedCorr) as Observation.extinction.

Parameters:

Name Type Description Default
obsFile

name of the file containing the observations. May be a file object or a file name If the fileFormat is 'fits_IFU', the obsFile keyword is of the form e.g.: 'dir/ngc6778_MUSE_*.fits' where * is of the form O3_5007A. The associated error file must be named the same way, using errStr keyword value e.g. dir/ngc6778_MUSE_O3_5007A_err.fits

None
fileFormat

format of the data file, depending on how the wavelengths are ordered. Available formats are : - 'lines_in_cols' : Each object is on a different row. Each column corresponds to a given emission line. Line labels with tailing "e" are for errors on line intensities. - 'lines_in_cols2' : Each object is on a different row. Same as 'lines_in_cols' but using genfromtxt to read the file. Allows undefined values. - 'lines_in_rows' : Each object is on a different column. Each row corresponds to a given emission line. - 'lines_in_rows_err_cols' : Each object is on a different column. Each row corresponds to a given emission line. For each object (eg. "IC418"), an additional column (named eg "errIC418") contains the errors on the line intensities. - 'fits_IFU': each emission line is stored into a fits file

'lines_in_cols'
delimiter

character separating entries

None
err_default

[0.10] default uncertainty assumed on intensities. Will overwrite the error from the file.

0.1
corrected

Boolean. True if the observed intensities are already corrected from extinction (default: False)

False
errIsRelative

Boolean. True if the errors are relative to the intensities, False if they are in the same unit as the intensity (default: True)

True
correcLaw

['F99'] extinction law used to correct the observed lines.

'F99'
errStr str

String used to identify error file when fileFormat is fits_IFU

'err'
addErrDefault

if True, the default error is always quadratically added to the read error.

False
Cutout2D_position
None
Cutout2D_size

In case of reading fits images, crop the image to those pixel limits

None

Example:

Read a file containing corrected intensities

obs = pn.Observation('obs.dat', corrected = True)

To obtain a dictionary with the observed corrected intensities

i_cor = {label: obs.getLine(label = label).corrIntens for label in obs.lineLabels}

Source code in pyneb/core/pynebcore.py
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
def __init__(self, obsFile=None, fileFormat='lines_in_cols', delimiter=None, err_default=0.10,
             corrected=False, errIsRelative=True, correcLaw='F99', errStr='err',
             addErrDefault = False, Cutout2D_position=None, Cutout2D_size=None):
    """
    Define the observation object, which is a collection of observated intensities of one or more
    emission lines for one or more objects, with the corresponding errors.
    The observed intensities are read from a file or filled in by the addLine method.
    Includes an extinction correction object (pyneb.RedCorr) as Observation.extinction.

    Parameters:
        obsFile:       name of the file containing the observations. May be a file object or a file name 
                         If the fileFormat is 'fits_IFU', the obsFile keyword is of the form e.g.:
                         'dir/ngc6778_MUSE_*.fits' where * is of the form O3_5007A.
                         The associated error file must be named the same way, using errStr keyword value 
                         e.g. dir/ngc6778_MUSE_O3_5007A_err.fits
        fileFormat:    format of the data file, depending on how the wavelengths are ordered.
                        Available formats are :
                        - 'lines_in_cols' : Each object is on a different row. Each column corresponds to a given emission line. 
                           Line labels with tailing "e" are for errors on line intensities.
                        - 'lines_in_cols2' : Each object is on a different row. Same as 'lines_in_cols' but using genfromtxt to read the file.
                           Allows undefined values.
                        - 'lines_in_rows' : Each object is on a different column. Each row corresponds to a given emission line.
                        - 'lines_in_rows_err_cols' : Each object is on a different column. Each row corresponds to a given emission line. 
                           For each object (eg. "IC418"), an additional column (named eg "errIC418") contains the errors on the line intensities.
                        - 'fits_IFU': each emission line is stored into a fits file
        delimiter:     character separating entries 
        err_default:   [0.10] default uncertainty assumed on intensities. Will overwrite the error from the file.
        corrected:     Boolean. True if the observed intensities are already corrected from extinction
                            (default: False)
        errIsRelative: Boolean. True if the errors are relative to the intensities, False if they
                            are in the same unit as the intensity (default: True)
        correcLaw:   ['F99'] extinction law used to correct the observed lines.
        errStr (str):        String used to identify error file when fileFormat is fits_IFU
        addErrDefault: if True, the default error is always quadratically added to the read error.
        Cutout2D_position:
        Cutout2D_size: In case of reading fits images, crop the image to those pixel limits

    **Example:**

    Read a file containing corrected intensities:

        obs = pn.Observation('obs.dat', corrected = True)

    To obtain a dictionary with the observed  corrected intensities:

        i_cor = {label: obs.getLine(label = label).corrIntens for label in obs.lineLabels}

    """        
    self.log_ = log_ 
    self.calling = 'Observation'
    self.lines = []
    self.names = []
    self.extinction = RedCorr(law=correcLaw)
    self.corrected = corrected
    self.addErrDefault = addErrDefault
    self.MC_added = False
    self.N_MC = 0
    self.fits_shape = None
    self.data_shape = None
    if self.corrected:
        self.extinction.law = 'No correction'
    if obsFile is not None:
        self.readData(obsFile=obsFile, fileFormat=fileFormat, delimiter=delimiter,
                      err_default=err_default, corrected=corrected, errIsRelative=errIsRelative,
                      errStr=errStr, 
                      Cutout2D_position=Cutout2D_position, Cutout2D_size=Cutout2D_size)

__normalize(label='H1_4861A')

Normalize the line intensities to a reference line (Hbeta by default). Not yet implemented

Source code in pyneb/core/pynebcore.py
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
def __normalize(self, label='H1_4861A'):
    """
    Normalize the line intensities to a reference line (Hbeta by default).
    Not yet implemented

    """
    if "=" in label:
        line_label, factor = label.split('=')
        factor = np.float64(factor)
    else:
        line_label = label
        factor = 1.
    line_norm = self.getLine(label=line_label) 
    if line_norm is None:
        self.log_.warn('No normalization possible as {0} not found'.format(line_label), calling=self.calling)
        return None
    for line in self.lines:
        line._obsIntens_n = line.obsIntens / (line_norm.obsIntens * factor)
        line._unit = line_label.strip()

addLine(line)

Add a line to an existing observation

Parameters:

Name Type Description Default
line

the selected emission line (an instance of EmissionLine)

required
Source code in pyneb/core/pynebcore.py
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
def addLine(self, line):
    """
    Add a line to an existing observation

    Parameters:
        line:    the selected emission line (an instance of EmissionLine)

    """
    if not isinstance(line, EmissionLine):            
        self.log_.error('Trying to add an inappropriate record to observations', calling=self.calling)
        return None
    if self.corrected and not line.corrected:
        line.corrected = True
        self.correctData(line)
    self.lines.append(line)

addMonteCarloObs(N=0, i_obs=None, random_seed=None)

Adding MonteCarlo random-gauss values of fake observations to an obs object. The names of the fake observations will be OriginalName-MC-n, n ranging from 0 to N-1

Parameters:

Name Type Description Default
N

number of new observations to be added for each original observation.

0
i_obs

used in case only a given observations needs to be treated

None
random_seed

[default] used to initialize the numpy random generator

None
Source code in pyneb/core/pynebcore.py
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
def addMonteCarloObs(self, N=0, i_obs=None, random_seed=None):
    """
    Adding MonteCarlo random-gauss values of fake observations to an obs object.
    The names of the fake observations will be OriginalName-MC-n, n ranging from 0 to N-1

    Parameters:
        N: number of new observations to be added for each original observation.
        i_obs: used in case only a given observations needs to be treated
        random_seed: [default] used to initialize the numpy random generator
    """
    if self.MC_added:
        self.log_.error('Monte Carlo already applied to this observation', calling='addMonteCarloObs')
    n_lines = self.n_lines
    n_obs = self.n_obs
    if i_obs is None:
        self.log_.message('Entering', calling='addMonteCarloObs')
        np.random.seed(random_seed)
        for l in self.lines:
            l_ori = l.obsIntens
            e_ori = l.obsError
            l_new = np.repeat(l_ori[:, np.newaxis], N+1, axis=1)
            e_new = np.repeat(e_ori[:, np.newaxis], N+1, axis=1)
            norm = np.random.standard_normal(l_new.shape)
            l_new *= (1 + e_new * norm)
            l_new[:,0] = l_ori
            l.obsIntens = l_new.ravel()
            l.obsError = e_new.ravel()
            if self.corrected:
                l.corrIntens = l_new.ravel()
                l.corrError = e_new.ravel()
            self.log_.debug('Adding MC to {}. {} {} {} {}'.format(l, l_new.shape, 
                                                                  l_new.ravel().shape, 
                                                                  l.obsIntens.shape,
                                                                  l.corrIntens.shape), 
                            calling='addMonteCarloObs')
        new_names = np.repeat(np.asarray(self.names)[:, np.newaxis], N+1, axis=1)
        MC_names = np.asarray(['-MC-{}'.format(i) for i in np.arange(N+1)])
        MC_names[0] = ''
        self.names = np.core.defchararray.add(new_names , MC_names).tolist()[0]
        self.log_.message('Leaving', calling='addMonteCarloObs')        
    else:
        if self.corrected:
            returnObs=False
        else:
            returnObs=True
        intens = np.array([self.getIntens(returnObs=returnObs)[label] for label in self.lineLabels])[:,i_obs] # n_lines
        error = np.array([self.getError(returnObs=returnObs)[label] for label in self.lineLabels])[:,i_obs]
        all_new_obs = np.random.standard_normal((N, n_lines))

        for i in range(N):
            new_obs = intens * (all_new_obs[i,:] * error + 1)
            new_obs[new_obs < 0.] = 0.
            self.addObs('{0}-MC-{1}'.format(self.names[i_obs], i), new_obs, error)
    self.MC_added = True
    self.N_MC = N
    if self.fits_shape is not None:    
        self.data_shape = (self.fits_shape[0], self.fits_shape[1], self.N_MC+1)
    else:
        self.data_shape = (self.N_MC+1)

addObs(name, newObsIntens, newObsError=None)

Add an observation (i.e. a list of intensities corresponding to a new object) to the existing set.

Parameters:

Name Type Description Default
name

name of the new observation/object

required
newObsIntens

value(s) of the line intensities. Length must match Observation.n_lines

required
Source code in pyneb/core/pynebcore.py
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
def addObs(self, name, newObsIntens, newObsError=None):
    """
    Add an observation (i.e. a list of intensities corresponding to a new object) to the existing set.

    Parameters:
        name:            name of the new observation/object
        newObsIntens:    value(s) of the line intensities. Length must match Observation.n_lines

    """
    if np.ndim(newObsIntens) == 0:
        newObsIntens = [newObsIntens]
    if len(newObsIntens) != self.n_lines:
        self.log_.error('Length of observations to be added does not match n_lines = {0}'.format(self.n_lines),
                        calling=self.calling)
        return
    if name in self.names:
        self.log_.error('Name {0} already exists'.format(name))
        return
    for i, line in enumerate(self.lines):
        if newObsError is None:
            line.addObs(newObsIntens[i])
        else:
            line.addObs(newObsIntens[i], newObsError[i])
    self.names.append(name)

addSum(labelsToAdd, newLabel, to_eval=None)

Add a new observation. The intensity is the sum of the intensities of the lines defined by the tupple labelsToAdd. The error is the quadratic sum of the absolute errors.

Example:

addSum(('O1r_7771A', 'O1r_7773A', 'O1r_7775A'), 'O1r_7773A+', to_eval = 'S("7773+")')
Source code in pyneb/core/pynebcore.py
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
def addSum(self, labelsToAdd, newLabel, to_eval=None):
    """
    Add a new observation. The intensity is the sum of the intensities of 
    the lines defined by the tupple labelsToAdd. The error is the quadratic sum of the absolute errors.


    **Example:**

        addSum(('O1r_7771A', 'O1r_7773A', 'O1r_7775A'), 'O1r_7773A+', to_eval = 'S("7773+")')
    """

    intenses = self.getIntens(returnObs=True)
    errors = self.getError(returnObs=True)
    I = intenses[labelsToAdd[0]]
    E = errors[labelsToAdd[0]] * I


    atom = labelsToAdd[0].split('_')[0]

    for label in labelsToAdd[1:]:
        if label.split('_')[0] != atom:
            self.log_.error('Can not add lines from different atoms {} and {}.'.format(
                label.split('_')[0],atom))
        I += intenses[label]
        E = np.sqrt(E**2 + (errors[label]*I)**2)
    if to_eval is None:
        to_eval = 'S("{}")'.format(newLabel.split('_')[1])
    E = E / I
    newLine = EmissionLine(label=newLabel, obsIntens=I, obsError=E, 
                              corrected=False, errIsRelative=True, 
                              to_eval=to_eval)
    self.addLine(newLine)

correctData(line=None, normWave=None)

Correct the line intensities with the correction computed with the RedCorr class (extinction.py) The result is stored in line.corrIntens (corrected intensity in absolute units).

Source code in pyneb/core/pynebcore.py
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
def correctData(self, line=None, normWave=None):
    """
    Correct the line intensities with the correction computed with the RedCorr class (extinction.py)
    The result is stored in line.corrIntens (corrected intensity in absolute units).

    """
    if line is None:
        line = self.lines
    if np.ndim(line) != 0:
        for l in line:
            self.correctData(l, normWave=normWave)
    else:
        if not isinstance(line, EmissionLine):
            self.log_.error('Trying to correct something that is not a line', calling=self.calling)
            return None  
        line.correctIntens(self.extinction, normWave=normWave)

        """            
        # the following is commented for now, we'll see latter how to implement normalized intensities.
        if line._unit is not None:
            try:
                line_norm = self.getLine(label=line._unit)
                line._corrIntens_n = line.obsIntens_n * self.extinction.getCorr(line.wave, line_norm.wave)
            except:
                log_.warn('No normalized correction for {0}'.format(line), calling='Observation.correctData')
                line._corrIntens_n = None
        """

def_EBV(label1='H1r_6563A', label2='H1r_4861A', r_theo=2.85)

Define the extinction parameter using the ratio of 2 lines. Calls extinction.setCorr to set the EBV and cHbeta according to the parameters. Once this is done, one may call correctData to compute the EmissionLine.corrIntens

Parameters:

Name Type Description Default
label1

[EmissionLine.label] observed line whose intensities are used

'H1r_6563A'
label2

[EmissionLine.label] observed line whose intensities are used

'H1r_4861A'
Source code in pyneb/core/pynebcore.py
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
def def_EBV(self, label1="H1r_6563A", label2="H1r_4861A", r_theo=2.85):
    """
    Define the extinction parameter using the ratio of 2 lines.
    Calls extinction.setCorr to set the EBV and cHbeta according to the parameters.
    Once this is done, one may call correctData to compute the EmissionLine.corrIntens

    Parameters:
        label1: [EmissionLine.label] observed line whose intensities are used 
        label2: [EmissionLine.label] observed line whose intensities are used
        r_theo [float] theoretical line ratio

    """
    line1 = self.getLine(label=label1)
    line2 = self.getLine(label=label2)
    if line1 is None:
        self.log_.error('{0} is not a valid label or is not observed'.format(line1), calling=self.calling)
        return None
    if line2 is None:
        self.log_.error('{0} is not a valid label or is not observed'.format(line2), calling=self.calling)
        return None
    with np.errstate(divide='ignore'):
        obs_over_theo = (line1.obsIntens / line2.obsIntens) / r_theo 
    self.extinction.setCorr(obs_over_theo, line1.wave, line2.wave)

fillObs(lineLabel, default=np.nan)

Create a fake observation of a given line, filled with a given value.

Parameters:

Name Type Description Default
lineLabel

the label of the new line. If the label corresponds to an already defined observation, nothing is done and a warning is issued.

required
default

the value of the fake observations. Default is np.nan

np.nan
Source code in pyneb/core/pynebcore.py
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
def fillObs(self, lineLabel, default=np.nan):
    """
    Create a fake observation of a given line, filled with a given value.
    Parameters:
        lineLabel: the label of the new line. If the label corresponds to an already 
            defined observation, nothing is done and a warning is issued.
        default: the value of the fake observations. Default is np.nan
    """

    if lineLabel not in self.lineLabels:
        newLine = EmissionLine(label=lineLabel, obsIntens=default*np.ones(self.n_obs))
        self.addLine(newLine)
    else:
        log_.warn('Line {0} already in obs'.format(lineLabel), calling = self.calling)

getError(returnObs=False, obsName=None)

Return the line intensity error in form of a dictionary with line labels as keys.

Parameters:

Name Type Description Default
returnObs

if False (default), prints the corrected values. If True, prints the observed value.

False
obsName

name of an observation. If not set or None, all the observations are printed

None
Source code in pyneb/core/pynebcore.py
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
def getError(self, returnObs=False, obsName=None):
    """
    Return the line intensity error in form of a dictionary with line labels as keys.

    Parameters:
        returnObs:  if False (default), prints the corrected values. 
                        If True, prints the observed value. 
        obsName:    name of an observation. If not set or None, all the observations are printed

    """
    if obsName is not None:
        if obsName in self.names:
            obsIndex = self.names.index(obsName)
        else:
            self.log_.error('Name {} is not an Observation name'.format(obsName))
            return None
    else:
        obsIndex = np.arange(self.n_obs)
    to_return = {}
    for line in self.lines:
        if returnObs:
            to_return[line.label] = line.obsError[obsIndex]
        else:
            to_return[line.label] = line.corrError[obsIndex]
    return to_return

getIntens(returnObs=False, obsName=None)

Return the line intensities in form of a dictionary with line labels as keys.

Parameters:

Name Type Description Default
returnObs bool

If False (default), prints the corrected values. If True, prints the observed value.

False
obsName

name of an observation. If not set or None, all the observations are printed

None
Source code in pyneb/core/pynebcore.py
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
def getIntens(self, returnObs=False, obsName=None):
    """
    Return the line intensities in form of a dictionary with line labels as keys.

    Parameters:
        returnObs (bool):  If False (default), prints the corrected values. 
                        If True, prints the observed value. 
        obsName:    name of an observation. If not set or None, all the observations are printed

    """
    if obsName is not None:
        if obsName in self.names:
            obsIndex = self.names.index(obsName)
        else:
            self.log_.error('Name {} is not an Observation name'.format(obsName))
            return None
    else:
        obsIndex = np.arange(self.n_obs)
    to_return = {}
    for line in self.lines:
        if returnObs:
            to_return[line.label] = line.obsIntens[obsIndex]
        else:
            to_return[line.label] = line.corrIntens[obsIndex]
    return to_return

getLine(elem=None, spec=None, wave=None, label=None, blend=False, i=None, j=None)

Return the lines corresponding to elem-spec-wave or to the label.

Source code in pyneb/core/pynebcore.py
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
def getLine(self, elem=None, spec=None, wave=None, label=None, blend=False, i=None, j=None):
    """
    Return the lines corresponding to elem-spec-wave or to the label.

    """
    if label is None:
        label = getLineLabel(elem, spec, wave, blend)[2]
    lines = [line for line in self.lines if line.label == label.strip()]
    n_lines = len(lines)
    if n_lines == 0:
        self.log_.warn('No line for {0} from {1}{2} at wavelength {3} (blend={4})'.format(label, elem, spec, wave, blend),
                       calling=self.calling)
        return None
    elif n_lines == 1:
        return lines[0]
    else:
        return np.asarray(lines)

getSortedLines(crit='atom')

Return a list of lines sorted by atoms or wavelengths.

Parameters:

Name Type Description Default
crit

criterion to sort the line list ('atom' [default] or 'wave')

'atom'
Source code in pyneb/core/pynebcore.py
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
def getSortedLines(self, crit='atom'):
    """
    Return a list of lines sorted by atoms or wavelengths.

    Parameters:
        crit:   criterion to sort the line list ('atom' [default] or 'wave')

    """
    if crit == 'atom':
        return sorted(self.lines, key=lambda line: line.atom + str(line.wave))
    elif crit == 'wave':
        return sorted(self.lines, key=lambda line: line.wave)
    elif crit == 'mass':
        return sorted(self.lines, key=lambda line: (Z[line.elem], line.spec, line.wave))
    else:
        self.log_.error('crit = {0} is not valid'.format(crit), calling=self.calling + '.getSortedLines')

getUniqueAtoms()

Return a numpy.ndarray of the atoms of the observed lines. If an atom emits more than one line, it is returned only once (numpy.unique is applied to the list before returning).

Source code in pyneb/core/pynebcore.py
4514
4515
4516
4517
4518
4519
4520
4521
def getUniqueAtoms(self):
    """
    Return a numpy.ndarray of the atoms of the observed lines. If an atom emits 
    more than one line, it is returned only once (numpy.unique is applied 
    to the list before returning).

    """
    return np.unique([l.atom for l in self.lines])

printIntens(returnObs=False, obsName=None)

Print the line intensities.

Parameters:

Name Type Description Default
returnObs

if False (default), prints the corrected values. If True, prints the observed value.

False
obsName

name of an observation. Is unset or None, all the observations are printed

None
Source code in pyneb/core/pynebcore.py
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
def printIntens(self, returnObs=False, obsName=None):
    """
    Print the line intensities.

    Parameters:
        returnObs:   if False (default), prints the corrected values. 
                        If True, prints the observed value. 
        obsName:     name of an observation. Is unset or None, all the observations are printed

    """    
    if obsName is not None:
        if obsName in self.names:
            obsIndex = np.array((self.names.index(obsName)))
        else:
            self.log_.error('Name {} is not an Observation name'.format(obsName))
            return None
    else:
        obsIndex = np.arange(self.n_obs)
    for line in self.lines:
        if isinstance(line.corrIntens[obsIndex], float):
            if returnObs:
                to_print = np.array((line.obsIntens[obsIndex],))
            else:
                to_print = np.array((line.corrIntens[obsIndex],))
        else:
            if returnObs:
                to_print = line.obsIntens[obsIndex]
            else:
                to_print = line.corrIntens[obsIndex]
        if returnObs:
            print('{:10}'.format(line.label), ' '.join(('{:8.3f}'.format(l) for l in to_print)))
        else:
            print('{:10}'.format(line.label), ' '.join(('{:8.3f}'.format(l) for l in to_print)))

readData(obsFile, fileFormat='lines_in_cols', delimiter=None, err_default=0.1, corrected=False, errIsRelative=True, errStr='err', Cutout2D_position=None, Cutout2D_size=None)

Read observational data from an ascii file. The lines can be listed either in columns or in rows and the observed objects vary in the other direction. The uncertainty on the line intensities can be read from the file, or a constant relative value can be assumed. The lines must be identified by a label in PyNeb's format ion_wave (e.g., 'O3_5007'); the list of ions and corresponding wavelengths can also be found in pn.LINE_LABEL_LIST. The following optional fields may also be included (without quotes): 'NAME' (object's name, in one string), 'E(B-V)', 'cHbeta', and 'e' (observational error).

Parameters:

Name Type Description Default
obsFile

file containing the observations. May be a file object or a string. If the fileFormat is 'fits_IFU', the obsFile keyword is of the form e.g.: 'dir/ngc6778_MUSE_*.fits' where * is of the form O3_5007A. The associated error file must be named the same way, using errStr keyword value e.g. dir/ngc6778_MUSE_O3_5007A_err.fits

required
fileFormat

emission lines vary across columns ('lines_in_cols', default) or across rows ('lines_in_rows'), or across rows with errors in columns ('lines_in_rows_err_cols') in which case the column label must start with "err"

            The format may also be 'fits_IFU', in which case each emission line comes
            from a different fits file
'lines_in_cols'
delimiter

field delimiter (default: None)

None
err_default

default uncertainty on the line intensities

0.1
corrected

Boolean. True if the observed intensities are already corrected from extinction (default: False)

False
errIsRelative

Boolean. True if the errors are relative to the intensities, False if they are in the same unit as the intensity (default: False)

True
errStr

string to identify the error file in case the fileFormat is fits_IFU.

'err'
Cutout2D_position

In case of reading fits images, crop the image to those pixel limits

None
Cutout2D_size

In case of reading fits images, crop the image to those pixel limits

None
Source code in pyneb/core/pynebcore.py
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
def readData(self, obsFile, fileFormat='lines_in_cols', delimiter=None, err_default=0.10, corrected=False,
             errIsRelative=True, errStr='err', Cutout2D_position=None, Cutout2D_size=None):
    """
    Read observational data from an ascii file. The lines can be listed either in columns or in rows
    and the observed objects vary in the other direction. The uncertainty on the line intensities
    can be read from the file, or a constant relative value can be assumed.
    The lines must be identified by a label in PyNeb's format ion_wave (e.g., 'O3_5007'); the list of ions and
    corresponding wavelengths can also be found in pn.LINE_LABEL_LIST.
    The following optional fields may also be included (without quotes): 'NAME' (object's name, in one string), 
    'E(B-V)', 'cHbeta', and 'e' (observational error).


    Parameters:
        obsFile:        file containing the observations. May be a file object or a string.
                         If the fileFormat is 'fits_IFU', the obsFile keyword is of the form e.g.:
                         'dir/ngc6778_MUSE_*.fits' where * is of the form O3_5007A.
                         The associated error file must be named the same way, using errStr keyword value 
                         e.g. dir/ngc6778_MUSE_O3_5007A_err.fits
        fileFormat:     emission lines vary across columns ('lines_in_cols', default) or 
                            across rows ('lines_in_rows'), or across rows with errors in columns 
                            ('lines_in_rows_err_cols') in which case the column label must start with "err"

                            The format may also be 'fits_IFU', in which case each emission line comes
                            from a different fits file

        delimiter:      field delimiter (default: None)  
        err_default:    default uncertainty on the line intensities
        corrected:      Boolean. True if the observed intensities are already corrected from extinction
                             (default: False)
        errIsRelative:  Boolean. True if the errors are relative to the intensities, False if they
                             are in the same unit as the intensity (default: False)
        errStr:         string to identify the error file in case the fileFormat is fits_IFU.
        Cutout2D_position: In case of reading fits images, crop the image to those pixel limits
        Cutout2D_size: In case of reading fits images, crop the image to those pixel limits

    """    
    format_list = ['lines_in_cols', 'lines_in_cols2', 'lines_in_rows', 
                   'lines_in_rows_err_cols', 'fits_IFU']
    if fileFormat not in format_list:
        self.log_.error('unknown format {0}'.format(fileFormat), calling='Observation.readData')

    if type(obsFile) is str and fileFormat not in ('fits_IFU',):
        f = open(obsFile, 'r')
        closeAfterUse = True
    else:
        f = obsFile
        closeAfterUse = False

    if fileFormat == 'lines_in_cols':
        hdr = f.readline()
        labels = hdr.split(delimiter)
        labels = [l.strip() for l in labels]
        data = f.readlines()
        if closeAfterUse:
            f.close()
        self.names = [dd.split(delimiter)[0].strip() for dd in data]
        data_tab = np.asarray([[dd.split(delimiter)[i] for dd in data] for i in np.arange(len(labels))])

        for i, label in enumerate(labels):
            if label == 'NAME':
                pass
            elif label == 'cHbeta':
                self.extinction.cHbeta = data_tab[i].astype(np.float32)
            elif label == 'E(B-V)':
                self.extinction.E_BV = data_tab[i].astype(np.float32)         
            elif label[-1] != 'e':
                intens = data_tab[i].astype(np.float32)
                try:
                    i_error = labels.index(label + 'e')
                    error = data_tab[i_error].astype(np.float32)
                    if not errIsRelative:
                        error = quiet_divide(error, intens)
                    if self.addErrDefault:
                        error = np.sqrt(error**2 + err_default**2)
                except:
                    self.log_.message('No error found for line {0}'.format(label), calling=self.calling)
                    error = data_tab[1].astype(np.float32) * 0. + err_default
                try:
                    line2add = EmissionLine(label=label, obsIntens=intens, obsError=error)
                except:
                    self.log_.warn('Unknown line label {0}'.format(label), calling=self.calling)
                try:
                    self.addLine(line2add)
                    self.log_.message('adding line {0}'.format(label), calling=self.calling)
                except:
                    self.log_.warn('Impossible to add line'.format(label), calling=self.calling)
    elif fileFormat == 'lines_in_cols2':
        if closeAfterUse:
            f.close()
        data_tab = np.genfromtxt(obsFile, dtype=None, delimiter=delimiter, names=True, deletechars='')
        for label in data_tab.dtype.names:
            if label == 'cHbeta':
                self.extinction.cHbeta = data_tab[label]
            elif label == 'E(B-V)':
                self.extinction.E_BV = data_tab[label]
            elif label == 'NAME':
                self.names = list(data_tab[label])
            elif label == 'NAME2':
                try:
                    names2 = list(data_tab[label])
                    self.names = [n1 + '_' + n2 for n1, n2 in zip(self.names, names2)]
                except:
                    pass
            elif label[-1] != 'e':
                if data_tab[label].dtype.type != np.string_:
                    intens = data_tab[label]
                    try:
                        error = data_tab[label + 'e']
                        if not errIsRelative:
                            error = error / intens
                        if self.addErrDefault:
                            error = np.sqrt(error**2 + err_default**2)
                    except:
                        self.log_.message('No error found for line {0}'.format(label), calling=self.calling)
                        error = np.ones_like(data_tab[label]) * err_default
                    try:
                        line2add = EmissionLine(label=label, obsIntens=intens, obsError=error)
                    except:
                        self.log_.warn('unkown line label {0}'.format(label), calling=self.calling)
                        print(label, intens, error)
                    try:
                        self.addLine(line2add)
                        self.log_.message('adding line {0}'.format(label), calling=self.calling)
                    except:
                        self.log_.warn('Impossible to add line'.format(label), calling=self.calling)
                        print(label, intens, error)
                else:
                    self.log_.warn('Skipped {0}'.format(label), calling=self.calling)

    elif fileFormat == 'lines_in_rows':
        hdr = f.readline()
        self.names = hdr.split(delimiter)[1:]
        self.names =  [l.strip() for l in self.names]
        data = f.readlines()
        if closeAfterUse:
            f.close()

        labels = [dd.split(delimiter)[0].strip() for dd in data if len(dd.strip()) > 0]
        data_tab = np.asarray([[dd.split(delimiter)[i + 1] for dd in data if len(dd.strip()) > 0] for i in np.arange(len(self.names))])
        data_tab = data_tab.astype(np.float32)
        for i, label in enumerate(labels):
            if label == 'cHbeta':
                self.extinction.cHbeta = data_tab[:, i]
            elif label == 'E(B-V)':
                self.extinction.E_BV = data_tab[:, i]
            elif label[-1] != 'e':
                intens = data_tab[:, i]
                try:
                    i_error = labels.index(label + 'e')
                    error = data_tab[:, i_error]
                    if not errIsRelative:
                        error = error / intens
                    if self.addErrDefault:
                        error = np.sqrt(error**2 + err_default**2)
                except:
                    self.log_.message('No error found for line {0}'.format(label), calling=self.calling)
                    error = np.ones_like(data_tab[:, 1]) * err_default
                try:
                    line2add = EmissionLine(label=label, obsIntens=intens, obsError=error)
                except:
                    self.log_.warn('unkown line label {0}'.format(label), calling=self.calling)
                    print(label, intens, error)
                try:
                    self.addLine(line2add)
                    self.log_.message('adding line {0}'.format(label), calling=self.calling)
                except:
                    self.log_.warn('Impossible to add line'.format(label), calling=self.calling)
                    print(label, intens, error)

    elif fileFormat == 'lines_in_rows_err_cols':

        if closeAfterUse:
            f.close()

        data_tab = np.genfromtxt(obsFile, dtype=None, delimiter=delimiter, names=True)
        self.names = [name for name in data_tab.dtype.names[1::] if name[0:3] != 'err']
        error_names = [name for name in data_tab.dtype.names if name[0:3] == 'err']
        if len(self.names) != len(error_names):
            self.log_.error('Number of columns for intensities <> number of columns for errors {} {}'.format(self.names,
                                                                                                             error_names),
                          calling=self.calling)
            return None
        #names_locations = [name in self.names for name in data_tab.dtype.names]
        #errors_locations = [name[0:3] == 'err' for name in data_tab.dtype.names]
        for i, label in enumerate(data_tab['LINE']):
            if sys.version_info.major >= 3:
                label = label.decode()
            label = label.strip()
            if label == 'cHbeta':
                self.extinction.cHbeta = np.array([data_tab[i][name] for name in self.names])
            elif label == 'E(B-V)':
                self.extinction.E_BV = np.array([data_tab[i][name] for name in self.names])
            else:
                intens = np.array([data_tab[i][name] for name in self.names])
                error = np.array([data_tab[i][name] for name in error_names])
                if not errIsRelative:
                    error = error / intens
                if self.addErrDefault:
                    error = np.sqrt(error**2 + err_default**2)
                try:
                    line2add = EmissionLine(label=label, obsIntens=intens, obsError=error)
                except:
                    self.log_.warn('unkown line label {0}'.format(label), calling=self.calling)
                    print(label, intens, error)
                try:
                    self.addLine(line2add)
                    self.log_.message('adding line {0}'.format(label), calling=self.calling)
                except:
                    self.log_.warn('Impossible to add line'.format(label), calling=self.calling)
                    print(label, intens, error)

    elif fileFormat == 'fits_IFU':
        path = Path(obsFile)
        dir_ = path.parent
        pattern = path.name
        files = dir_.glob(pattern)
        self.log_.debug('path: {}, dir_: {}, pattern: {}'.format(path, dir_, pattern),
                        calling='Observation.readData')
        str1, str2 = pattern.split('*')
        for f in files:
            obs_file = f.name
            if f.suffix == '.fits' and errStr not in obs_file:
                self.log_.debug('analysing {}'.format(f), calling='Observation.readData')
                lineID = strExtract(obs_file, str1, str2)
                spl = lineID.split('_')
                if len(spl) == 2:
                    atom = spl[0]
                    line = spl[1]
                    if atom in LINE_LABEL_LIST:
                        self.log_.message('Reading {}_{} from {}'.format(atom, line, f.name),
                                          calling='Observation.readData')
                        fits_hdu = pyfits.open(f)[0]
                        fits_data = fits_hdu.data
                        self.origin_fits_shape = fits_data.shape
                        self.fits_header = fits_hdu.header
                        self.wcs = WCS(self.fits_header).celestial
                        if Cutout2D_position is not None:
                            self.log_.debug('Cutout2D applied to data shape {}.'.format(fits_data.shape),
                                            calling='Observation.readData')
                            C2D = Cutout2D(data=fits_data, position=Cutout2D_position, 
                                           size=Cutout2D_size, wcs=WCS(fits_hdu.header), mode='trim',
                                           copy=True)
                            fits_data = C2D.data
                            self.wcs = C2D.wcs
                        if self.fits_shape is None:
                            self.fits_shape = fits_data.shape
                        else:
                            if fits_data.shape != self.fits_shape:
                                self.log_.error('data shape in file {} is {}. Previous shape was {}.'.format(
                                                f.name, fits_data.shape, self.fits_shape))
                        fits_data = fits_data.ravel()
                        err_file = dir_ / Path(f.stem+'_' + errStr + '.fits')
                        if err_file.exists():
                            self.log_.message('Reading error {}_{} from {}'.format(atom, line, err_file.name),
                                              calling='Observation.readData')
                            err_fits_hdu = pyfits.open(err_file)[0]
                            if err_fits_hdu.data.shape != self.origin_fits_shape:
                                self.log_.error('error shape in file {} is {}. data shape is {}.'.format(
                                                err_file.name, err_fits_hdu.data.shape, self.fits_shape))
                            err_fits_data = err_fits_hdu.data
                            if Cutout2D_position is not None:
                                C2D = Cutout2D(data=err_fits_data, position=Cutout2D_position, 
                                               size=Cutout2D_size, mode='trim',
                                               copy=True)
                                err_fits_data = C2D.data
                            err_fits_data = err_fits_data.ravel()
                            if not errIsRelative:
                                with np.errstate(divide='ignore', invalid='ignore'):
                                    err_fits_data = err_fits_data / fits_data
                            if self.addErrDefault:
                                err_fits_data = np.sqrt(err_fits_data**2 + err_default**2)
                        else:
                            self.log_.message('No error file found for {}'.format(f.name),
                                              calling='Observation.readData')                                
                            err_fits_data  = np.ones_like(fits_data) * err_default
                        self.addLine(EmissionLine(label=lineID,
                                                  obsIntens=fits_data, 
                                                  obsError=err_fits_data, 
                                                  corrected=corrected, errIsRelative=True))
                    else:
                        self.log_.debug('atom {} not in LINE_LABEL_LIST'.format(atom), 
                                        calling='Observation.readData')

        self.names = ['{}_{}'.format(str1, i) for i in range(self.n_obs)]
        self.data_shape = self.fits_shape

    if corrected:
        self.correctData()

reshape(data)

Return data in shape of the original data (use with fits IFUs and/or MC)

Source code in pyneb/core/pynebcore.py
5050
5051
5052
5053
5054
def reshape(self, data):
    """
    Return data in shape of the original data (use with fits IFUs and/or MC)
    """
    return np.reshape(data, self.data_shape)

setAllErrors(err_default)

Set the relative uncertainty of all emission lines to a common constant value

Parameters:

Name Type Description Default
err_default

default value of the relative uncertainty

required
Source code in pyneb/core/pynebcore.py
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
def setAllErrors(self, err_default):
    """
    Set the relative uncertainty of all emission lines to a common constant value

    Parameters:
        err_default:     default value of the relative uncertainty

    """
    for line in self.lines:
        line.obs_err = np.ones_like(line.obs_err) * err_default

RecAtom

Bases: object

Source code in pyneb/core/pynebcore.py
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
class RecAtom(object):

    def __init__(self, elem=None, spec=None, atom=None, case='B', extrapolate=False):
        """
        RecAtom class. Used to manage recombination data and compute emissivities.

        Parameters:
            elem:          symbol of the selected element
            spec:          ionization stage in spectroscopic notation (I = 1, II = 2, etc.)
            extrapolate: use the function outside the validity range [False]

        **Usage:**
            H1 = pn.RecAtom('H', 1)
        """
        self.log_ = log_
        self.type = 'rec'
        self.is_valid = True
        self.gs = None
        self.case = case
        self.extrapolate = extrapolate
        self.sources = []
        if atom is not None:
            self.atom = str.capitalize(atom)
            self.elem = parseAtom(self.atom)[0]
            self.spec = int(parseAtom(self.atom)[1])
        else:
            self.elem = str.capitalize(elem)
            self.spec = int(spec)
            self.atom = self.elem + str(self.spec)
        self.name = sym2name[self.elem]
        self.calling = 'Atom ' + self.atom
        self.log_.message('Making rec-atom object for {0} {1:d}'.format(self.elem, self.spec), calling=self.calling)
        try:
            self.Z = Z[self.elem]
        except:
            self.Z = -1
        if self.elem in IP:
            if self.spec == 1:
                self.IP = 0
            elif self.spec < len(IP[self.elem])+2:
                self.IP = IP[self.elem][self.spec-2]
            else:
                self.IP = -1
        else:
            self.IP = -1

        self.recFitsFile = atomicData.getDataFile(self.atom, 'rec')
        self.file_type = self.recFitsFile.split('.')[-1]
        self.useNIST = False
        if self.file_type == 'fits':
            self._loadFit()
        elif self.file_type == 'hdf5':
            self._loadHDF5()
        elif self.file_type == 'func':
            self._loadFunctions()
        else:
            self.is_valid = False

        if 'trc' in atomicData.getDataFile()[self.atom].keys():
            self._loadTotRecombination()

        self.E_in_vacuum = True
        self.comments = {}

        if self.useNIST:
            self.NIST = getLevelsNIST(self.atom)
            web = 'Ref. {0} of NIST 2014 (try this: http://physics.nist.gov/cgi-bin/ASBib1/get_ASBib_ref.cgi?db=el&db_id={0}&comment_code=&element={1}&spectr_charge={2}&'
            if self.NIST is not None:
                self.NLevels = len(self.NIST)
                self._Energy = self.NIST['energy'] / 1e8
                self.comments['VACUUM'] = '1'
                self.comments['NOTE'] = 'Energy levels'
                for ref in np.unique(self.NIST['ref']):
                    self.sources.append(web.format(ref[1:], self.elem, self.spec))
            self.initWaves()
        else:
            self.NIST = None
            self.NLevels = 0
            self.wave_Ang = None

        atomicData.add2usedFiles(self.atom, self.recFitsFile)


    def _test_lev(self, level):
        """
        Test whether selected level is legal

        Parameters:
            level:        selected atom level

        """       
        if self.NLevels == 0:
            self.log_.error('No levels defined', calling=self.calling)
        if level < -1 or level == 0 or level > self.NLevels:
            self.log_.error('Wrong value for level: {0}, maximum = {1}'.format(level, self.NLevels),
                            calling=self.calling)

    def initWaves(self):
        """
        Initialization of wave_Ang

        """
        self.wave_Ang = np.zeros((self.NLevels, self.NLevels))

        for i in range(1, self.NLevels):
            for j in range(i):
                wave = 1. / abs(self._Energy[i] - self._Energy[j])
                if self.E_in_vacuum:
                    wave = vactoair(wave)
                self.wave_Ang[i, j] = self.wave_Ang[j, i] = wave


    def getWave(self, lev_i=None, lev_j=None):
        """
        Return the wavelength of a transition given the levels 

        Parameters:
            lev_i: upper level of the transition
            lev_j: lower level of the transition

        **Usage:**
            He2.getWave(4, 3)

        """ 
        self._test_lev(lev_i)
        self._test_lev(lev_j)
        return(self.wave_Ang[lev_i-1, lev_j-1])

    def _loadHDF5(self):
        """
        Method to read the atomic data hdf5 file and store the data
        Called by __init__
        """

        if not config.INSTALLED['h5py'] and not config.INSTALLED['astropy Table']:
            self.log_.error('You need to install astropy (prefered) or h5py', calling=self.calling)
        self.recFitsFile = atomicData.getDataFile(self.atom, 'rec')
        if self.recFitsFile is None:
            self.log_.error('No hdf5 data for atom: {0}'.format(self.atom), calling=self.calling)
            return None
        self.recFitsFullPath = atomicData.getDataFullPath(self.atom, 'rec')

        if config.INSTALLED['astropy Table']:
            try:
                hf5 = Table.read(self.recFitsFullPath, path='updated_data')
                self._RecombData = hf5
                self.log_.message('HDF5 data read from {} using Astropy.table'.format(self.recFitsFullPath), calling=self.calling)
            except:
                self.log_.error('{0} recombination file not read'.format(self.recFitsFullPath), calling=self.calling)
        elif config.INSTALLED['h5py']:
            try:
                hf5 = h5py.File(self.recFitsFullPath, 'r')
                try:
                    self._RecombData = hf5['updated_data'].value
                except:
                    self._RecombData = hf5['updated_data']
                hf5.close()
                self.log_.message('HDF5 data read from {} using h5py'.format(self.recFitsFullPath), calling=self.calling)
            except:
                self.log_.error('{0} recombination file not read'.format(self.recFitsFullPath), calling=self.calling)
        try:
            self.temp = self._RecombData['TEMP']
        except:
            self.log_.error('No TEMP field in {0}'.format(self.recFitsFile))
        try:
            self.log_dens = self._RecombData['DENS']
        except:
            self.log_.error('No DENS field in {0}'.format(self.recFitsFile))
        self.labels = tuple([l for l in self._RecombData.dtype.names if l not in ('TEMP', 'DENS')])
        if '_' in self._RecombData.dtype.names[0]:
            self.label_type = 'transitions'
        else:
            self.label_type = 'wavelengths'
        if 'SOURCE' in self._RecombData.meta:
            self.sources.append(self._RecombData.meta['SOURCE'])
        if self.recFitsFile.split('.')[0][-4:] == 'SH95':
            self.useNIST = True
        self.log_.message('{0} recombination data read from {1}'.format(self.atom, self.recFitsFile), calling=self.calling)

    def _loadFit(self):
        """
        Method to read the atomic data fits file and store the data
        Called by __init__

        """

        self.recFitsFullPath = atomicData.getDataFullPath(self.atom, 'rec')
        header = pyfits.open(self.recFitsFullPath, ignore_missing_end=True)[1].header
        for record in header.items():
            if 'SOURCE' in record[0]:
                number = record[0].lstrip('SOURCE')
                try:
                    print(self.atom + ': ' + header.get('NOTE' + str(number)) + ':', header.get('SOURCE' + str(number)))
                except:
                    print(self.atom + ': ' + 'Atomic data:', header.get('SOURCE' + str(number)))




        self.recFitsFile = atomicData.getDataFile(self.atom, 'rec')
        if self.recFitsFile is None:
            self.log_.error('No fits data for atom: {0}'.format(self.atom), calling=self.calling)
            return None
        self.recFitsFullPath = atomicData.getDataFullPath(self.atom, 'rec')
        try:
            hdu = pyfits.open(self.recFitsFullPath)
        except:
            self.log_.error('{0} recombination file not read'.format(self.recFitsFile), calling=self.calling)
        self._RecombData = hdu[1].data
        header = hdu[1].header
        hdu.close()
        try:
            self.temp = self._RecombData['TEMP']
        except:
            self.log_.error('No TEMP field in {0}'.format(self.recFitsFile))
        try:
            self.log_dens = self._RecombData['DENS']
        except:
            self.log_.error('No DENS field in {0}'.format(self.recFitsFile))
        self.labels = self._RecombData.names
        del self.labels[self.labels.index('TEMP')]
        del self.labels[self.labels.index('DENS')]
        if '_' in self._RecombData.names[0]:
            self.label_type = 'transitions'
        else:
            self.label_type = 'wavelengths'

        for record in header.items():
            if 'SOURCE' in record[0]:
                number = record[0].lstrip('SOURCE')
                try:
                    self.sources.append(self.atom + ': ' + header.get('NOTE' + str(number)) + ':'+ header.get('SOURCE' + str(number)))
                except:
                    self.sources.append(self.atom + ': ' + 'Atomic data:'+ header.get('SOURCE' + str(number)))


        if self.recFitsFile.split('.')[0][-4:] == 'SH95':
            self.useNIST = True
        self.log_.message('{0} recombination data read from {1}'.format(self.atom, self.recFitsFile), calling=self.calling)

    def _loadFunctions(self):
        """
        read functions to compute emissivities from formulae.
        Define the emis_func function
        """
        self.useNIST = False        

        self.recFitsFile = atomicData.getDataFile(self.atom, 'rec')
        if self.recFitsFile is None:
            self.log_.error('No func data for atom: {0}'.format(self.atom), calling=self.calling)
            return None
        self.recFitsFullPath = atomicData.getDataFullPath(self.atom, 'rec')
        with open(self.recFitsFullPath, 'r') as f:
            self._funcType = f.readline().strip()
            source = f.readline()
        if self._funcType == 'PEQ1991':
            try:
                data = np.genfromtxt(self.recFitsFullPath, skip_header=2,
                                     usecols = (0,1,2,3,4,5,6,7), 
                                     names='label, lamb, case, a, b, c, d, Br', 
                                     dtype="U5, f8, U1, f8, f8, f8, f8, f8, f8")
            except:
                self.log_.error('Error reading {}'.format(self.recFitsFullPath))
            case_mask = data['case'] == self.case
            if case_mask.sum() == 0:
                self.log_.error('No data for this case {}'.format(self.case))
            data = data[case_mask]
            data['lamb'] *= 10  # Angstrom
            self.labels = data['label']
            def emis_func(label, temp, dens):
                mask = data['label'] == label
                if mask.sum() == 1:
                    d = data[mask]
                    z = self.spec 
                    t = 1e-4 * temp / z**2
                    alpha = 1e-13 * z * d['a'] * t**d['b'] / (1. + d['c'] * t**d['d'])
                    E_Ryd = 1./(d['lamb'] * 1e-8 * CST.RYD)
                    E_erg = E_Ryd * CST.RYD2ERG   #erg
                    emis = d['Br'] * alpha * E_erg
                    single = False
                    if not self.extrapolate:
                        if np.ndim(t) == 0:
                            single = True
                            t = np.asarray([t])
                        mask = t < 0.004
                        emis[mask] = np.nan
                    if single:
                        emis = emis[0]
                    return emis
                else:
                    self.log_.error('{} is not a valid label'.format(label))
        elif self._funcType == 'S94': # O II
            try:
                data = np.genfromtxt(self.recFitsFullPath, skip_header=2,  
                                     names='label, lamb, case, a, b, c, d',
                                     dtype="U5, f8, U1, f8, f8, f8, f8")
            except:
                self.log_.error('Error reading {}'.format(self.recFitsFullPath))
            data = data[data['case'] == self.case]
            data['lamb'] *= 10  # Angstrom
            self.labels = data['label']
            def emis_func(label, temp, dens):
                mask = data['label'] == label
                if mask.sum() == 1:
                    d = data[mask]
                    t = 1e-4 * temp 
                    alpha = 1e-14 * d['a'] * t**d['b'] *(1. + d['c']*(1.-t) + d['d']*(1.-t)**2)
                    E_Ryd = 1./(d['lamb'] * 1e-8 * CST.RYD)
                    E_erg = E_Ryd * CST.RYD2ERG   #erg
                    emis = alpha * E_erg
                    single = False
                    if not self.extrapolate:
                        if np.ndim(t) == 0:
                            single = True
                            t = np.asarray([t])
                        mask = t < 0.5
                        emis[mask] = np.nan
                    if single:
                        emis = emis[0]
                    return emis
                else:
                    self.log_.error('{} is not a valid label'.format(label))
        elif self._funcType == 'D00': # C II
            try:
                data = np.genfromtxt(self.recFitsFullPath, skip_header=2,  
                                     names='ID, case, lamb, a, b, c, d, f',
                                     dtype="i, U1, f8, f8, f8, f8, f8, f8")
            except:
                 self.log_.error('Error reading {}'.format(self.recFitsFullPath))
            data = data[data['case'] == self.case]
            data['lamb'] *= 10  # Angstrom
            self.labels = np.array(['{:.1f}'.format(lamb) for lamb in data['lamb']])
            def emis_func(label, temp, dens):
                mask = self.labels == label
                if mask.sum() == 1:
                    d = data[mask]
                    t = 1e-4 * temp 
                    alpha = 1e-14 * d['a'] * t**d['f'] *(1. + d['b']*(1.-t) + 
                                     d['c']*(1.-t)**2 + d['d']*(1.-t)**3)
                    E_Ryd = 1./(d['lamb'] * 1e-8 * CST.RYD)
                    E_erg = E_Ryd * CST.RYD2ERG   #erg
                    emis = alpha * E_erg
                    single = False
                    if not self.extrapolate:
                        if np.ndim(t) == 0:
                            single = True
                            t = np.asarray([t])
                        mask = (t < 0.5) & (t > 2.0)
                        emis[mask] = np.nan
                    if single:
                        emis = emis[0]
                    return emis
                else:
                    self.log_.error('{} is not a valid label'.format(label))
        elif self._funcType == 'FSL11': # N II
            try:
                data = np.genfromtxt(self.recFitsFullPath, skip_header=2, 
                                     usecols = (0,1,2,3,4,5,6,7,8,9,10,13), 
                                     names='case, mult, lamb, a, b, c, d, e, f, g, h, dens', 
                                     dtype="U1, U1, f8, f8, f8, f8, f8, f8, f8, f8, f8, f8")
            except:
                self.log_.error('Error reading {}'.format(self.recFitsFullPath))
            data = data[data['case'] == self.case]
            labels = np.array(['{:.2f}'.format(lamb) for lamb in data['lamb']])
            def emis_func(label, temp, dens):
                if np.ndim(temp) == 0:
                    temp = np.array([temp], dtype=float)
                    single = True
                else:
                    temp = np.array(temp, dtype=float)
                    single = False
                if np.ndim(dens) == 0:
                    dens = np.array([dens], dtype=float)
                else:
                    dens = np.array(dens, dtype=float)
                mask2 = (labels == label) & (data['dens'] == 2)
                mask3 = (labels == label) & (data['dens'] == 3)
                mask4 = (labels == label) & (data['dens'] == 4)
                mask5 = (labels == label) & (data['dens'] == 5)
                if mask2.sum() == 1:
                    d2 = data[mask2]
                    d3 = data[mask3]
                    d4 = data[mask4]
                    d5 = data[mask5]
                    t = 1e-4 * temp
                    alpha_gen = lambda d, t: 10**(d['a']+d['b']*t+d['c']*t**2+
                                              (d['d']+d['e']*t+d['f']*t**2)*np.log10(t)+
                                              d['g']*(np.log10(t))**2+d['h']/t-15)
                    alpha2 = alpha_gen(d2, t)
                    alpha3 = alpha_gen(d3, t)
                    alpha4 = alpha_gen(d4, t)
                    alpha5 = alpha_gen(d5, t)

                    alpha = np.zeros_like(temp)

                    mask = dens <= 10**2
                    alpha[mask] = alpha2[mask]
                    mask = dens > 10**5
                    alpha[mask] = alpha5[mask]
                    mask = (dens > 10**2) & (dens <= 10**3)
                    alpha[mask] = alpha3[mask] * (np.log10(dens[mask]) - 2) + alpha2[mask] * (3 - np.log10(dens[mask]))
                    mask = (dens > 10**3) & (dens <= 10**4)
                    alpha[mask] = alpha4[mask] * (np.log10(dens[mask]) - 3) + alpha3[mask] * (4 - np.log10(dens[mask]))
                    mask = (dens > 10**4) & (dens <= 10**5)
                    alpha[mask] = alpha5[mask] * (np.log10(dens[mask]) - 4) + alpha4[mask] * (5 - np.log10(dens[mask]))

                    E_Ryd = 1./(d2['lamb'] * 1e-8 * CST.RYD)
                    E_erg = E_Ryd * CST.RYD2ERG   #erg
                    emis = alpha * E_erg
                    if single:
                        emis = emis[0]
                    return emis
                else:
                    self.log_.error('{} is not a valid label'.format(label))
            self.labels= np.unique(labels)

        elif self._funcType == 'KSDN1998': # Ne II
            try:
                d1 = np.genfromtxt(self.recFitsFullPath, skip_header=5, skip_footer=38, 
                                   usecols = (0, 17, 18, 19, 20, 21, 22, 23), 
                                   names='ID, case, lamb, a, b, c, d, f',
                                   dtype="i4, U1, f8, f8, f8, f8, f8, f8")
                d2 = np.genfromtxt(self.recFitsFullPath, skip_header=5+215, skip_footer=0, 
                                   usecols = (0, 12, 13), 
                                   names='ID, lamb, Br',
                                   dtype="i4, f8, f8")
            except:
                self.log_.error('Error reading {}'.format(self.recFitsFullPath))
            d1 = d1[d1['case'] == self.case]
            d1['lamb'] *= 10  # Angstrom
            d2['lamb'] *= 10  # Angstrom
            data = [d1, d2]
            labels1 = np.array(['{:.1f}+'.format(lamb) for lamb in d1['lamb']])
            labels2 = np.array(['{:.3f}'.format(lamb) for lamb in d2['lamb']])
            self.labels = np.append(labels1, labels2)
            def emis_func(label, temp, dens):
                if label[-1] == '+':
                    mask = labels1 == label
                    if mask.sum() == 1:
                        d = d1[mask]
                        t = 1e-4 * temp 
                        alpha = 1e-14 * d['a'] * t**d['f'] *(1. + d['b']*(1.-t) + d['c']*(1.-t)**2 + d['d']*(1.-t)**3)
                        E_Ryd = 1./(d['lamb'] * 1e-8 * CST.RYD)
                        E_erg = E_Ryd * CST.RYD2ERG   #erg
                        emis = alpha * E_erg
                        single = False
                        if not self.extrapolate:
                            if np.ndim(t) == 0:
                                single = True
                                t = np.asarray([t])
                            mask = t < 0.1
                            emis[mask] = np.nan
                        if single:
                            emis = emis[0]
                        return emis
                    else:
                        self.log_.error('{} is not a valid label'.format(label))
                else:
                    mask = labels2 == label
                    if mask.sum() == 1:
                        dd2 = d2[mask]
                        mask1 = (d1['ID'] == dd2['ID']) | (d1['ID'] == dd2['ID']+1)
                        dd1 = d1[mask1]
                        t = 1e-4 * temp
                        alpha = 1e-14 * dd1['a'] * t**dd1['f'] *(1. + dd1['b']*(1.-t) + dd1['c']*(1.-t)**2 + dd1['d']*(1.-t)**3)
                        E_Ryd = 1./(dd2['lamb'] * 1e-8 * CST.RYD)
                        E_erg = E_Ryd * CST.RYD2ERG   #erg
                        emis = alpha * E_erg * dd2['Br']
                        single = False
                        if not self.extrapolate:
                            if np.ndim(t) == 0:
                                single = True
                                t = np.asarray([t])
                            mask = t < 0.1
                            emis[mask] = np.nan
                        if single:
                            emis = emis[0]
                        return emis
                    else:
                        self.log_.error('{} is not a valid label'.format(label))       
        else:
            self.log_.error('{} is not a valid function label'.format(self._funcType))
        self._func_data = data 
        if '_' in self.labels[0]:
            self.label_type = 'transitions'
        elif '+' in self.labels[0]:
            self.label_type = 'wavelengths'
        else:
            self.label_type = 'wavelengths'
        self.sources.append(source)
        self._emis_func = emis_func
        self.log_.message('{0} recombination data built from {1}'.format(self.atom, self.recFitsFile), 
                     calling=self.calling)

    def _loadTotRecombination(self):
        """
        Load the total recombination coefficient table. The case (A or B) is set by selecting the corresponding trc file. 
        """ 
        self.TotRecFile = atomicData.getDataFullPath(self.atom, 'trc')
        f = open(self.TotRecFile)
        data = f.readlines()
        f.close()
        den_points = [np.float64(d) for d in data[0].split()]
        tem_points = [np.float64(d) for d in data[1].split()]
        self.alpha_grid = np.array([d.split() for d in data if d[0:3]!='***'][2::], dtype='float')
        self.lg_den_grid, self.lg_tem_grid = np.meshgrid(np.log10(den_points), np.log10(tem_points))


    def _Transition(self, wave, maxErrorA = 5.e-3, maxErrorm = 5.e-2):
        """
        Return an array with computed upper level, computed lower level, computed wavelength, 
            input wavelength

        Parameters:
            wave:       wavelength either in Angstrom (a float or a label: e.g., 5007, '5007A') 
                            or in micron (a label: '51.5m')
            maxErrorA: tolerance if the input wavelength is in Angstrom
            maxErrorm: tolerance if the input wavelength is in micron

        """
        if self.wave_Ang is None:
            return(None)
        if str(wave)[-1] == 'A':
            inputWave = float(wave[:-1])
            label = '{0}_{1}'.format(self.atom, wave)
            maxError = maxErrorA
        elif str(wave)[-1] == 'm':
            inputWave = float(wave[:-1]) * 1e4
            label = '{0}_{1}'.format(self.atom, wave)
            maxError = maxErrorm
        else:
            inputWave = wave
            label = '{0}_{1}A'.format(self.atom, int(wave))
            maxError = maxErrorA

        if label in label2levelDict:
            result = [label2levelDict[label][0], label2levelDict[label][1], inputWave, inputWave]
            return(result)

        j, i = np.unravel_index(np.argmin(abs(self.wave_Ang - inputWave)), self.wave_Ang.shape)
        bestWave = self.wave_Ang[i, j]
        error = np.abs(bestWave - inputWave) / inputWave
        result = [i + 1, j + 1, bestWave, inputWave]
        if error > maxError:
            self.log_.warn('_Transition: wavelengths differ by more than {0:.2f}%: input = {1:.2f}, output = {2:.2f}'\
                           .format(100 * maxError, inputWave, bestWave), calling=self.calling)
        return(result)


    def getTotRecombination(self, tem, den, method='linear'):
        """
        Return the total recombination coefficient. The case (A or B) is set by selecting the corresponding trc file.

        Parameters:
            tem:  temperature 
            den: density
            method:    interpolation method in the grid ('linear' = default, 'nearest', 'cubic')    

        **Usage:**
            atomicData.setDataFile('h_i_trc_SH95-caseA.dat')
            h1.getTotRecombination(tem=10000, den=5.e3)

        """ 
        self.calling = 'getTotRecombination'
        if 'trc' in atomicData.getDataFile()[self.atom].keys():
            return interpolate.griddata((self.lg_den_grid.ravel(), self.lg_tem_grid.ravel()), self.alpha_grid.ravel(), (np.log10(den), np.log10(tem)), method=method)
        else:
            self.log_.warn('No recombination data available for {0} in the adopted dictionary (but data may exist: please query atomicData.getAllAvailableFiles("<atom>") for trc files)'.format(self.atom), calling=self.calling)
            return None


    def getTransition(self, wave, maxErrorA = 5.e-3, maxErrorm = 5.e-2):
        """
        Return the indexes (upper level, lower level) of a transition for a given atom 
            from the wavelength.

        Parameters:
            wave:      wavelength in Angstrom (a float or a label: e.g., 5007, '5007A') 
                or in micron (a label: '51.5m')
            maxErrorA: tolerance if the input wavelength is in Angstrom
            maxErrorm: tolerance if the input wavelength is in micron

        **Usage:**

            O3.getTransition(4959)

        """ 
        res = self._Transition(wave, maxErrorA = maxErrorA, maxErrorm = maxErrorm)
        if res is None:
            return(None)
        else:
            return(res[0], res[1])


    def printTransition(self, wave):
        """
        Print info on transition associated to input wavelength.

        Parameters:
            wave:      wavelength in Angstrom (a float or a label: e.g., 5007, '5007A') 
                or in micron (a label: '51.5m')

        **Usage:**

            O3.printTransition(4959)

        """
        closestTransition = self._Transition(wave)
        if closestTransition is None:
            print('No wavelengths defined')
        else:
            relativeError = closestTransition[3] / closestTransition[2] - 1
            print('Input wave: {0:.1F}'.format(closestTransition[3]))
            print('Closest wave found: {0:.1F}'.format(closestTransition[2]))
            print('Relative error: {0:.0E} '.format(relativeError))
            print('Transition: {0[0]} -> {0[1]}'.format(closestTransition))

    def grepLabels(self, str_):
        """
        Return all the labels containing str_
        """
        return [l for l in self.labels if str_ in l]

    def printSources(self):

        for source in self.sources:
            print(source)

    def getSources(self):

        return(self.sources)

    def getEnergy(self, level= -1, unit='1/Ang'):
        """
        Return energy level of selected level (or array of energy levels, if level not given) 
            in Angstrom^-1 (default) or another unit

        Parameters:
            level:  selected atomic level (default= -1, returns complete array)
            unit:   [str] one of '1/Ang' (default), 'eV', or 'Ryd'    

        **Usage:**
            O3.getEnergy(4, unit='eV')    
        """
        self._test_lev(level)

        unit_dict = {'1/Ang': 1.,
                     'Ryd': CST.RYD_ANG,
                     'eV': CST.RYD_ANG * CST.RYD_EV,
                     'cm-1': 1e8}
        if unit not in unit_dict:
            self.log_.warn('Unit {0} unknown, using 1/Ang'.format(unit), calling=self.calling + '.getEnergy')
            unit = '1/Ang'        

        if level == -1:
            return self._Energy * unit_dict[unit]
        else:
            return self._Energy[level-1] * unit_dict[unit]


    def _checkLabel(self, label):
        """
        Return True if the label is compatible with the type of labels read form the data file
        'transitions' labels are of the form "J_I"
        'wavelengths' labels are of the form "1234.5" (dot is mandatory)

        """
        if ('_' in label) and (self.label_type == 'transitions'):
            return True
        elif ('+' in label) and (self.label_type == 'wavelengths'):
            return True
        elif ('.' in label) and (self.label_type == 'wavelengths'):
            return True
        else:
            return False


    def _getLabelStr(self, label, warn=True):
        """
        Returns a string containing the label. 
        If label is a float, it is transormed into a string .
        If label is not in the self.labels list, None is returned

        """
        if np.isreal(label):
            label_str0 = '{0:.0f}'.format(label)
            label_str1 = '{0:.1f}'.format(label)
            label_str2 = '{0:.2f}'.format(label)
        else:
            label_str0 = label_str1 = label_str2 = str(label)
        if label_str0 in self.labels:
            return label_str0
        elif label_str1 in self.labels:
            return label_str1
        elif label_str2 in self.labels:
            return label_str2
        else:
            if warn:
                self.log_.warn('Label {0} not in {1}.'.format(label, self.recFitsFile), calling=self.calling)
            return None


    def getEmissivity(self, tem, den, lev_i=None, lev_j=None, wave=None, label=None,
                      method='linear', product=True):
        """
        Return the emissivity of a recombination line (erg.s-1.cm3). The arguments used to 
        define the line depend on whether the atom is an hydrogenoid or not. 
        In the first case, the transition can be specified either as a pair 
        of levels lev_i, lev_j or as a label. 
        In the second case, the transition can be specified either as a wavelength 
        or as a label.
        In either case, enter <atom>.labels to display the valid labels.

        Parameters:
            tem:            temperature (K)
            den:            density (cm-3)
            lev_i: upper level of transition
            lev_j: lower level of transition
            wave:           wavelength of the transition
            label:          label of the transition (e.g. "50_3", "1234.5")
            method:         interpolation method ('linear', 'nearest', 'cubic'), 
                             sent to scipy.interpolate.griddata    
            product:        Boolean. If True (default), all the combination of (tem, den) are used. 
                             If False, tem and den must have the same size and are joined.

        Usage:

            H1 = pn.RecAtom('H', 1)

            H1.getEmissivity([1e4, 1.2e4], [1e3, 1e2], lev_i = 4, lev_j = 2)

            H1.getEmissivity([1e4, 1.2e4], [1e3, 1e2], label='4_2', product=False)

            tem = np.linspace(5000, 20000, 100)

            den = np.logspace(2, 6, 100)

            imHab = H1.getEmissivity(tem, den, label='3_2') / H1.getEmissivity(tem, den, label='4_2')

            He1 = pn.RecAtom('He', 1)

            He1.getEmissivity(1e4, 1e2, wave=4471.0)

            He1.getEmissivity(1e4, 1e2, label='4471.0')
        """

        if not config.INSTALLED['scipy']:
            self.log_.error('Scipy not installed, no RecAtom emissivities available',
                          calling=self.calling)
            return None
        tem = np.asarray(tem, dtype=float)
        den = np.asarray(den, dtype=float)
        if product:
            if tem.size == 1 or den.size == 1:
                temg = tem
                deng = den
            else:
                temg, deng = np.meshgrid(tem, den)
                temg = temg.T
                deng = deng.T
        else:
            if tem.size != den.size:
                self.log_.error('tem and den must have the same size', calling=self.calling)
                return None
            else:
                temg = tem
                deng = den
        if (lev_i is not None) and (lev_j is not None):
            label = '{0}_{1}'.format(lev_i, lev_j)
        if wave is not None:
            #label = '{0:.1f}'.format(wave)
            #label_str = self._getLabelStr(label, warn=False)
            label_str = self._getLabelStr(wave, warn=False)
            label = label_str
            if label_str is None:
                ij = self.getTransition(wave)
                if ij is not None:
                    label = '{}_{}'.format(ij[0], ij[1])
        if label is None:
            res = {label: self.getEmissivity(tem, den, label=label, method=method, product=product) for label in self.labels}
            return res
        label_str = self._getLabelStr(label, warn=False)
        if label_str is None:
            self.log_.warn('Wrong label {0}'.format(label), calling=self.calling)
            return None
        if not self._checkLabel(label_str):
            self.log_.warn('Wrong label {0}'.format(label_str), calling=self.calling)
            return None

        if self.file_type == 'func':
            res = self._emis_func(label_str, temg, deng)
        else:
            enu = self._RecombData[label_str]

            logd = np.log10(deng)
            temp_min = np.min(self.temp)
            temp_max = np.max(self.temp)
            log_dens_min = np.min(self.log_dens)
            log_dens_max = np.max(self.log_dens)
            tt = (logd < log_dens_min)
            if np.ndim(logd) == 0: 
                if tt == True:
                    logd = log_dens_min
            else:
                logd[tt] = log_dens_min
            tt = (logd > log_dens_max)
            if np.ndim(logd) == 0:
                if tt == True:
                    logd = log_dens_max
            else:
                logd[tt] = log_dens_max
            res = interpolate.griddata((1./self.temp.ravel(), self.log_dens.ravel()), enu.ravel(),
                                       (1./temg, logd), method=method)
            if (temg < temp_min).sum() != 0 and self.extrapolate:
                masklowte = temg < temp_min
                temp_min2 = np.min(self.temp[self.temp > temp_min])

                em_min = self.getEmissivity(temp_min, deng[masklowte].ravel(),
                                            lev_i=lev_i, lev_j=lev_j, wave=wave, 
                                            label=label, method=method)
                em_min2 = self.getEmissivity(temp_min2, deng[masklowte].ravel(),
                                            lev_i=lev_i, lev_j=lev_j, wave=wave, 
                                            label=label, method=method)
                a = (em_min - em_min2) / (1./temp_min - 1./temp_min2)
                b = em_min - a / temp_min
                em = a / temg[masklowte].ravel() + b
                self.log_.warn('{}/Te + {} extrapolation on low Te'.format(a, b), calling=self.calling)
                res[masklowte]=em
        return res


    def getIonAbundance(self, int_ratio, tem, den, lev_i= -1, lev_j= -1, wave= -1, label=None,
                        to_eval=None, Hbeta=100., tem_HI=None, den_HI=None):
        """
        Compute the ionic abundance relative to H+ given the temperature, the density and the 
            intensity of a line or sum of lines.
        The arguments used to define the line depend on whether the atom is an hydrogenoid or not. 
        For hydrogenoids, the transition can be specified either as a pair of levels 
            lev_i, lev_j, as a label, or as an I-type expression as the argument of to_eval 
            (e.g. to_eval='I(50, 19)' for the 50->19 transition). Wavelengths or L-type expressions 
            will not work in this case. 
        For non-hydrogenoids, the transition can be specified either as an integer wavelength, 
            as a label, or as an A-type expression as the argument of to_eval (e.g. to_eval='A(4471)' 
            for the lambda=4471 transition). Note that all these alternatives imply that the wavelength
            is known. Pairs of levels and I or L-type expressions would not work.

        The preferred method are the label and the I-type expressions, as the remaining parameters 
            are inherently fragile.

        Parameters:
            int_ratio:    relative line intensity (default normalization: Hbeta = 100). 
                            May be an array.
            tem:          electronic temperature in K. May be an array.
            den:          electronic density in cm^-3. May be an array.
            lev_i:        upper level of transition
            lev_j:        lower level of transition
            wave:         wavelength of transition. Takes precedence on lev_i and lev_j if set, 
                            ignored otherwise 
            to_eval:      expression to be evaluated. Takes precedence on wave if set, 
                            ignored otherwise.
            Hbeta:        line intensity normalization at Hbeta (default Hbeta = 100)
            tem_HI:       HI temperature. If not set, tem is used.
            den_HI:       HI density. If not set, den is used.

        **Usage:**

            He2.getIonAbundance(130, 1.5e4, 100., lev_i=5, lev_j=4)

            He2.getIonAbundance(130, 1.5e4, 100., label="5_4")

            He2.getIonAbundance(130, 1.5e4, 100., to_eval='I(4,3) + I(4,2)')

            He1.getIonAbundance(100, 1.5e4, 100., wave=5016)

            He1.getIonAbundance(100, 1.5e4, 100., label="5016.0")

            He1.getIonAbundance(100, 1.5e4, 100., to_eval='S(5016)')

            He1.getIonAbundance(np.array([100, 150]), np.array([1.5e4, 1.2e4]), np.array([100., 120]), 
                label="10830.0")

        """
        if tem_HI is None:
            tem_HI = tem
        if den_HI is None:
            den_HI = den
        if np.ndim(tem) != np.ndim(den):
            self.log_.error('ten and den must have the same shape', calling=self.calling)
            return None
        if ((np.squeeze(np.asarray(int_ratio)).shape != np.squeeze(np.asarray(tem)).shape) | 
            (np.squeeze(np.asarray(den)).shape != np.squeeze(np.asarray(tem)).shape)):
            self.log_.warn('int_ratio, tem and den must does not have the same shape', calling=self.calling)
        if (lev_i == -1) & (lev_j == -1) & (wave == -1) & (to_eval is None) & (label is None):
            self.log_.error('At least one of lev_i, lev_j, or wave, or to_eval must be supplied', calling=self.calling)
            return None
        if to_eval == None:
            if wave != -1:
                to_eval = 'L({0})'.format(wave)
            elif label is not None:
                to_eval = 'S("{0}")'.format(label)
            else:
                to_eval = 'I({0}, {1})'.format(lev_i, lev_j)
        I = lambda lev_i, lev_j: self.getEmissivity(tem, den, lev_i, lev_j, product=False)
        L = lambda wave: self.getEmissivity(tem, den, wave=wave, product=False)
        S = lambda label: self.getEmissivity(tem, den, label=label, product=False)

        try:
            emis = eval(to_eval)
        except:
            self.log_.error('Unable to eval {0}'.format(to_eval), calling=self.calling)
            return None
        if emis is not None:
            #int_ratio is in units of Hb = Hbeta keyword
            ionAbundance = ((int_ratio / Hbeta) * (getRecEmissivity(tem_HI, den_HI, 4, 2, atom='H1', product=False) / emis))
        else:
            ionAbundance = None
        return ionAbundance


    def __repr__(self):
        return 'Atom {0}{1} from {2}'.format(self.elem, self.spec, self.recFitsFile)

__init__(elem=None, spec=None, atom=None, case='B', extrapolate=False)

RecAtom class. Used to manage recombination data and compute emissivities.

Parameters:

Name Type Description Default
elem

symbol of the selected element

None
spec

ionization stage in spectroscopic notation (I = 1, II = 2, etc.)

None
extrapolate

use the function outside the validity range [False]

False

Usage: H1 = pn.RecAtom('H', 1)

Source code in pyneb/core/pynebcore.py
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
def __init__(self, elem=None, spec=None, atom=None, case='B', extrapolate=False):
    """
    RecAtom class. Used to manage recombination data and compute emissivities.

    Parameters:
        elem:          symbol of the selected element
        spec:          ionization stage in spectroscopic notation (I = 1, II = 2, etc.)
        extrapolate: use the function outside the validity range [False]

    **Usage:**
        H1 = pn.RecAtom('H', 1)
    """
    self.log_ = log_
    self.type = 'rec'
    self.is_valid = True
    self.gs = None
    self.case = case
    self.extrapolate = extrapolate
    self.sources = []
    if atom is not None:
        self.atom = str.capitalize(atom)
        self.elem = parseAtom(self.atom)[0]
        self.spec = int(parseAtom(self.atom)[1])
    else:
        self.elem = str.capitalize(elem)
        self.spec = int(spec)
        self.atom = self.elem + str(self.spec)
    self.name = sym2name[self.elem]
    self.calling = 'Atom ' + self.atom
    self.log_.message('Making rec-atom object for {0} {1:d}'.format(self.elem, self.spec), calling=self.calling)
    try:
        self.Z = Z[self.elem]
    except:
        self.Z = -1
    if self.elem in IP:
        if self.spec == 1:
            self.IP = 0
        elif self.spec < len(IP[self.elem])+2:
            self.IP = IP[self.elem][self.spec-2]
        else:
            self.IP = -1
    else:
        self.IP = -1

    self.recFitsFile = atomicData.getDataFile(self.atom, 'rec')
    self.file_type = self.recFitsFile.split('.')[-1]
    self.useNIST = False
    if self.file_type == 'fits':
        self._loadFit()
    elif self.file_type == 'hdf5':
        self._loadHDF5()
    elif self.file_type == 'func':
        self._loadFunctions()
    else:
        self.is_valid = False

    if 'trc' in atomicData.getDataFile()[self.atom].keys():
        self._loadTotRecombination()

    self.E_in_vacuum = True
    self.comments = {}

    if self.useNIST:
        self.NIST = getLevelsNIST(self.atom)
        web = 'Ref. {0} of NIST 2014 (try this: http://physics.nist.gov/cgi-bin/ASBib1/get_ASBib_ref.cgi?db=el&db_id={0}&comment_code=&element={1}&spectr_charge={2}&'
        if self.NIST is not None:
            self.NLevels = len(self.NIST)
            self._Energy = self.NIST['energy'] / 1e8
            self.comments['VACUUM'] = '1'
            self.comments['NOTE'] = 'Energy levels'
            for ref in np.unique(self.NIST['ref']):
                self.sources.append(web.format(ref[1:], self.elem, self.spec))
        self.initWaves()
    else:
        self.NIST = None
        self.NLevels = 0
        self.wave_Ang = None

    atomicData.add2usedFiles(self.atom, self.recFitsFile)

getEmissivity(tem, den, lev_i=None, lev_j=None, wave=None, label=None, method='linear', product=True)

Return the emissivity of a recombination line (erg.s-1.cm3). The arguments used to define the line depend on whether the atom is an hydrogenoid or not. In the first case, the transition can be specified either as a pair of levels lev_i, lev_j or as a label. In the second case, the transition can be specified either as a wavelength or as a label. In either case, enter .labels to display the valid labels.

Parameters:

Name Type Description Default
tem

temperature (K)

required
den

density (cm-3)

required
lev_i

upper level of transition

None
lev_j

lower level of transition

None
wave

wavelength of the transition

None
label

label of the transition (e.g. "50_3", "1234.5")

None
method

interpolation method ('linear', 'nearest', 'cubic'), sent to scipy.interpolate.griddata

'linear'
product

Boolean. If True (default), all the combination of (tem, den) are used. If False, tem and den must have the same size and are joined.

True
Usage

H1 = pn.RecAtom('H', 1)

H1.getEmissivity([1e4, 1.2e4], [1e3, 1e2], lev_i = 4, lev_j = 2)

H1.getEmissivity([1e4, 1.2e4], [1e3, 1e2], label='4_2', product=False)

tem = np.linspace(5000, 20000, 100)

den = np.logspace(2, 6, 100)

imHab = H1.getEmissivity(tem, den, label='3_2') / H1.getEmissivity(tem, den, label='4_2')

He1 = pn.RecAtom('He', 1)

He1.getEmissivity(1e4, 1e2, wave=4471.0)

He1.getEmissivity(1e4, 1e2, label='4471.0')

Source code in pyneb/core/pynebcore.py
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
def getEmissivity(self, tem, den, lev_i=None, lev_j=None, wave=None, label=None,
                  method='linear', product=True):
    """
    Return the emissivity of a recombination line (erg.s-1.cm3). The arguments used to 
    define the line depend on whether the atom is an hydrogenoid or not. 
    In the first case, the transition can be specified either as a pair 
    of levels lev_i, lev_j or as a label. 
    In the second case, the transition can be specified either as a wavelength 
    or as a label.
    In either case, enter <atom>.labels to display the valid labels.

    Parameters:
        tem:            temperature (K)
        den:            density (cm-3)
        lev_i: upper level of transition
        lev_j: lower level of transition
        wave:           wavelength of the transition
        label:          label of the transition (e.g. "50_3", "1234.5")
        method:         interpolation method ('linear', 'nearest', 'cubic'), 
                         sent to scipy.interpolate.griddata    
        product:        Boolean. If True (default), all the combination of (tem, den) are used. 
                         If False, tem and den must have the same size and are joined.

    Usage:

        H1 = pn.RecAtom('H', 1)

        H1.getEmissivity([1e4, 1.2e4], [1e3, 1e2], lev_i = 4, lev_j = 2)

        H1.getEmissivity([1e4, 1.2e4], [1e3, 1e2], label='4_2', product=False)

        tem = np.linspace(5000, 20000, 100)

        den = np.logspace(2, 6, 100)

        imHab = H1.getEmissivity(tem, den, label='3_2') / H1.getEmissivity(tem, den, label='4_2')

        He1 = pn.RecAtom('He', 1)

        He1.getEmissivity(1e4, 1e2, wave=4471.0)

        He1.getEmissivity(1e4, 1e2, label='4471.0')
    """

    if not config.INSTALLED['scipy']:
        self.log_.error('Scipy not installed, no RecAtom emissivities available',
                      calling=self.calling)
        return None
    tem = np.asarray(tem, dtype=float)
    den = np.asarray(den, dtype=float)
    if product:
        if tem.size == 1 or den.size == 1:
            temg = tem
            deng = den
        else:
            temg, deng = np.meshgrid(tem, den)
            temg = temg.T
            deng = deng.T
    else:
        if tem.size != den.size:
            self.log_.error('tem and den must have the same size', calling=self.calling)
            return None
        else:
            temg = tem
            deng = den
    if (lev_i is not None) and (lev_j is not None):
        label = '{0}_{1}'.format(lev_i, lev_j)
    if wave is not None:
        #label = '{0:.1f}'.format(wave)
        #label_str = self._getLabelStr(label, warn=False)
        label_str = self._getLabelStr(wave, warn=False)
        label = label_str
        if label_str is None:
            ij = self.getTransition(wave)
            if ij is not None:
                label = '{}_{}'.format(ij[0], ij[1])
    if label is None:
        res = {label: self.getEmissivity(tem, den, label=label, method=method, product=product) for label in self.labels}
        return res
    label_str = self._getLabelStr(label, warn=False)
    if label_str is None:
        self.log_.warn('Wrong label {0}'.format(label), calling=self.calling)
        return None
    if not self._checkLabel(label_str):
        self.log_.warn('Wrong label {0}'.format(label_str), calling=self.calling)
        return None

    if self.file_type == 'func':
        res = self._emis_func(label_str, temg, deng)
    else:
        enu = self._RecombData[label_str]

        logd = np.log10(deng)
        temp_min = np.min(self.temp)
        temp_max = np.max(self.temp)
        log_dens_min = np.min(self.log_dens)
        log_dens_max = np.max(self.log_dens)
        tt = (logd < log_dens_min)
        if np.ndim(logd) == 0: 
            if tt == True:
                logd = log_dens_min
        else:
            logd[tt] = log_dens_min
        tt = (logd > log_dens_max)
        if np.ndim(logd) == 0:
            if tt == True:
                logd = log_dens_max
        else:
            logd[tt] = log_dens_max
        res = interpolate.griddata((1./self.temp.ravel(), self.log_dens.ravel()), enu.ravel(),
                                   (1./temg, logd), method=method)
        if (temg < temp_min).sum() != 0 and self.extrapolate:
            masklowte = temg < temp_min
            temp_min2 = np.min(self.temp[self.temp > temp_min])

            em_min = self.getEmissivity(temp_min, deng[masklowte].ravel(),
                                        lev_i=lev_i, lev_j=lev_j, wave=wave, 
                                        label=label, method=method)
            em_min2 = self.getEmissivity(temp_min2, deng[masklowte].ravel(),
                                        lev_i=lev_i, lev_j=lev_j, wave=wave, 
                                        label=label, method=method)
            a = (em_min - em_min2) / (1./temp_min - 1./temp_min2)
            b = em_min - a / temp_min
            em = a / temg[masklowte].ravel() + b
            self.log_.warn('{}/Te + {} extrapolation on low Te'.format(a, b), calling=self.calling)
            res[masklowte]=em
    return res

getEnergy(level=-1, unit='1/Ang')

Return energy level of selected level (or array of energy levels, if level not given) in Angstrom^-1 (default) or another unit

Parameters:

Name Type Description Default
level

selected atomic level (default= -1, returns complete array)

-1
unit

[str] one of '1/Ang' (default), 'eV', or 'Ryd'

'1/Ang'

Usage: O3.getEnergy(4, unit='eV')

Source code in pyneb/core/pynebcore.py
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
def getEnergy(self, level= -1, unit='1/Ang'):
    """
    Return energy level of selected level (or array of energy levels, if level not given) 
        in Angstrom^-1 (default) or another unit

    Parameters:
        level:  selected atomic level (default= -1, returns complete array)
        unit:   [str] one of '1/Ang' (default), 'eV', or 'Ryd'    

    **Usage:**
        O3.getEnergy(4, unit='eV')    
    """
    self._test_lev(level)

    unit_dict = {'1/Ang': 1.,
                 'Ryd': CST.RYD_ANG,
                 'eV': CST.RYD_ANG * CST.RYD_EV,
                 'cm-1': 1e8}
    if unit not in unit_dict:
        self.log_.warn('Unit {0} unknown, using 1/Ang'.format(unit), calling=self.calling + '.getEnergy')
        unit = '1/Ang'        

    if level == -1:
        return self._Energy * unit_dict[unit]
    else:
        return self._Energy[level-1] * unit_dict[unit]

getIonAbundance(int_ratio, tem, den, lev_i=-1, lev_j=-1, wave=-1, label=None, to_eval=None, Hbeta=100.0, tem_HI=None, den_HI=None)

Compute the ionic abundance relative to H+ given the temperature, the density and the intensity of a line or sum of lines. The arguments used to define the line depend on whether the atom is an hydrogenoid or not. For hydrogenoids, the transition can be specified either as a pair of levels lev_i, lev_j, as a label, or as an I-type expression as the argument of to_eval (e.g. to_eval='I(50, 19)' for the 50->19 transition). Wavelengths or L-type expressions will not work in this case. For non-hydrogenoids, the transition can be specified either as an integer wavelength, as a label, or as an A-type expression as the argument of to_eval (e.g. to_eval='A(4471)' for the lambda=4471 transition). Note that all these alternatives imply that the wavelength is known. Pairs of levels and I or L-type expressions would not work.

The preferred method are the label and the I-type expressions, as the remaining parameters are inherently fragile.

Parameters:

Name Type Description Default
int_ratio

relative line intensity (default normalization: Hbeta = 100). May be an array.

required
tem

electronic temperature in K. May be an array.

required
den

electronic density in cm^-3. May be an array.

required
lev_i

upper level of transition

-1
lev_j

lower level of transition

-1
wave

wavelength of transition. Takes precedence on lev_i and lev_j if set, ignored otherwise

-1
to_eval

expression to be evaluated. Takes precedence on wave if set, ignored otherwise.

None
Hbeta

line intensity normalization at Hbeta (default Hbeta = 100)

100.0
tem_HI

HI temperature. If not set, tem is used.

None
den_HI

HI density. If not set, den is used.

None

Usage:

He2.getIonAbundance(130, 1.5e4, 100., lev_i=5, lev_j=4)

He2.getIonAbundance(130, 1.5e4, 100., label="5_4")

He2.getIonAbundance(130, 1.5e4, 100., to_eval='I(4,3) + I(4,2)')

He1.getIonAbundance(100, 1.5e4, 100., wave=5016)

He1.getIonAbundance(100, 1.5e4, 100., label="5016.0")

He1.getIonAbundance(100, 1.5e4, 100., to_eval='S(5016)')

He1.getIonAbundance(np.array([100, 150]), np.array([1.5e4, 1.2e4]), np.array([100., 120]), 
    label="10830.0")
Source code in pyneb/core/pynebcore.py
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
def getIonAbundance(self, int_ratio, tem, den, lev_i= -1, lev_j= -1, wave= -1, label=None,
                    to_eval=None, Hbeta=100., tem_HI=None, den_HI=None):
    """
    Compute the ionic abundance relative to H+ given the temperature, the density and the 
        intensity of a line or sum of lines.
    The arguments used to define the line depend on whether the atom is an hydrogenoid or not. 
    For hydrogenoids, the transition can be specified either as a pair of levels 
        lev_i, lev_j, as a label, or as an I-type expression as the argument of to_eval 
        (e.g. to_eval='I(50, 19)' for the 50->19 transition). Wavelengths or L-type expressions 
        will not work in this case. 
    For non-hydrogenoids, the transition can be specified either as an integer wavelength, 
        as a label, or as an A-type expression as the argument of to_eval (e.g. to_eval='A(4471)' 
        for the lambda=4471 transition). Note that all these alternatives imply that the wavelength
        is known. Pairs of levels and I or L-type expressions would not work.

    The preferred method are the label and the I-type expressions, as the remaining parameters 
        are inherently fragile.

    Parameters:
        int_ratio:    relative line intensity (default normalization: Hbeta = 100). 
                        May be an array.
        tem:          electronic temperature in K. May be an array.
        den:          electronic density in cm^-3. May be an array.
        lev_i:        upper level of transition
        lev_j:        lower level of transition
        wave:         wavelength of transition. Takes precedence on lev_i and lev_j if set, 
                        ignored otherwise 
        to_eval:      expression to be evaluated. Takes precedence on wave if set, 
                        ignored otherwise.
        Hbeta:        line intensity normalization at Hbeta (default Hbeta = 100)
        tem_HI:       HI temperature. If not set, tem is used.
        den_HI:       HI density. If not set, den is used.

    **Usage:**

        He2.getIonAbundance(130, 1.5e4, 100., lev_i=5, lev_j=4)

        He2.getIonAbundance(130, 1.5e4, 100., label="5_4")

        He2.getIonAbundance(130, 1.5e4, 100., to_eval='I(4,3) + I(4,2)')

        He1.getIonAbundance(100, 1.5e4, 100., wave=5016)

        He1.getIonAbundance(100, 1.5e4, 100., label="5016.0")

        He1.getIonAbundance(100, 1.5e4, 100., to_eval='S(5016)')

        He1.getIonAbundance(np.array([100, 150]), np.array([1.5e4, 1.2e4]), np.array([100., 120]), 
            label="10830.0")

    """
    if tem_HI is None:
        tem_HI = tem
    if den_HI is None:
        den_HI = den
    if np.ndim(tem) != np.ndim(den):
        self.log_.error('ten and den must have the same shape', calling=self.calling)
        return None
    if ((np.squeeze(np.asarray(int_ratio)).shape != np.squeeze(np.asarray(tem)).shape) | 
        (np.squeeze(np.asarray(den)).shape != np.squeeze(np.asarray(tem)).shape)):
        self.log_.warn('int_ratio, tem and den must does not have the same shape', calling=self.calling)
    if (lev_i == -1) & (lev_j == -1) & (wave == -1) & (to_eval is None) & (label is None):
        self.log_.error('At least one of lev_i, lev_j, or wave, or to_eval must be supplied', calling=self.calling)
        return None
    if to_eval == None:
        if wave != -1:
            to_eval = 'L({0})'.format(wave)
        elif label is not None:
            to_eval = 'S("{0}")'.format(label)
        else:
            to_eval = 'I({0}, {1})'.format(lev_i, lev_j)
    I = lambda lev_i, lev_j: self.getEmissivity(tem, den, lev_i, lev_j, product=False)
    L = lambda wave: self.getEmissivity(tem, den, wave=wave, product=False)
    S = lambda label: self.getEmissivity(tem, den, label=label, product=False)

    try:
        emis = eval(to_eval)
    except:
        self.log_.error('Unable to eval {0}'.format(to_eval), calling=self.calling)
        return None
    if emis is not None:
        #int_ratio is in units of Hb = Hbeta keyword
        ionAbundance = ((int_ratio / Hbeta) * (getRecEmissivity(tem_HI, den_HI, 4, 2, atom='H1', product=False) / emis))
    else:
        ionAbundance = None
    return ionAbundance

getTotRecombination(tem, den, method='linear')

Return the total recombination coefficient. The case (A or B) is set by selecting the corresponding trc file.

Parameters:

Name Type Description Default
tem

temperature

required
den

density

required
method

interpolation method in the grid ('linear' = default, 'nearest', 'cubic')

'linear'

Usage: atomicData.setDataFile('h_i_trc_SH95-caseA.dat') h1.getTotRecombination(tem=10000, den=5.e3)

Source code in pyneb/core/pynebcore.py
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
def getTotRecombination(self, tem, den, method='linear'):
    """
    Return the total recombination coefficient. The case (A or B) is set by selecting the corresponding trc file.

    Parameters:
        tem:  temperature 
        den: density
        method:    interpolation method in the grid ('linear' = default, 'nearest', 'cubic')    

    **Usage:**
        atomicData.setDataFile('h_i_trc_SH95-caseA.dat')
        h1.getTotRecombination(tem=10000, den=5.e3)

    """ 
    self.calling = 'getTotRecombination'
    if 'trc' in atomicData.getDataFile()[self.atom].keys():
        return interpolate.griddata((self.lg_den_grid.ravel(), self.lg_tem_grid.ravel()), self.alpha_grid.ravel(), (np.log10(den), np.log10(tem)), method=method)
    else:
        self.log_.warn('No recombination data available for {0} in the adopted dictionary (but data may exist: please query atomicData.getAllAvailableFiles("<atom>") for trc files)'.format(self.atom), calling=self.calling)
        return None

getTransition(wave, maxErrorA=0.005, maxErrorm=0.05)

Return the indexes (upper level, lower level) of a transition for a given atom from the wavelength.

Parameters:

Name Type Description Default
wave

wavelength in Angstrom (a float or a label: e.g., 5007, '5007A') or in micron (a label: '51.5m')

required
maxErrorA

tolerance if the input wavelength is in Angstrom

0.005
maxErrorm

tolerance if the input wavelength is in micron

0.05

Usage:

O3.getTransition(4959)
Source code in pyneb/core/pynebcore.py
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
def getTransition(self, wave, maxErrorA = 5.e-3, maxErrorm = 5.e-2):
    """
    Return the indexes (upper level, lower level) of a transition for a given atom 
        from the wavelength.

    Parameters:
        wave:      wavelength in Angstrom (a float or a label: e.g., 5007, '5007A') 
            or in micron (a label: '51.5m')
        maxErrorA: tolerance if the input wavelength is in Angstrom
        maxErrorm: tolerance if the input wavelength is in micron

    **Usage:**

        O3.getTransition(4959)

    """ 
    res = self._Transition(wave, maxErrorA = maxErrorA, maxErrorm = maxErrorm)
    if res is None:
        return(None)
    else:
        return(res[0], res[1])

getWave(lev_i=None, lev_j=None)

Return the wavelength of a transition given the levels

Parameters:

Name Type Description Default
lev_i

upper level of the transition

None
lev_j

lower level of the transition

None

Usage: He2.getWave(4, 3)

Source code in pyneb/core/pynebcore.py
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
def getWave(self, lev_i=None, lev_j=None):
    """
    Return the wavelength of a transition given the levels 

    Parameters:
        lev_i: upper level of the transition
        lev_j: lower level of the transition

    **Usage:**
        He2.getWave(4, 3)

    """ 
    self._test_lev(lev_i)
    self._test_lev(lev_j)
    return(self.wave_Ang[lev_i-1, lev_j-1])

grepLabels(str_)

Return all the labels containing str_

Source code in pyneb/core/pynebcore.py
3535
3536
3537
3538
3539
def grepLabels(self, str_):
    """
    Return all the labels containing str_
    """
    return [l for l in self.labels if str_ in l]

initWaves()

Initialization of wave_Ang

Source code in pyneb/core/pynebcore.py
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
def initWaves(self):
    """
    Initialization of wave_Ang

    """
    self.wave_Ang = np.zeros((self.NLevels, self.NLevels))

    for i in range(1, self.NLevels):
        for j in range(i):
            wave = 1. / abs(self._Energy[i] - self._Energy[j])
            if self.E_in_vacuum:
                wave = vactoair(wave)
            self.wave_Ang[i, j] = self.wave_Ang[j, i] = wave

printTransition(wave)

Print info on transition associated to input wavelength.

Parameters:

Name Type Description Default
wave

wavelength in Angstrom (a float or a label: e.g., 5007, '5007A') or in micron (a label: '51.5m')

required

Usage:

O3.printTransition(4959)
Source code in pyneb/core/pynebcore.py
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
def printTransition(self, wave):
    """
    Print info on transition associated to input wavelength.

    Parameters:
        wave:      wavelength in Angstrom (a float or a label: e.g., 5007, '5007A') 
            or in micron (a label: '51.5m')

    **Usage:**

        O3.printTransition(4959)

    """
    closestTransition = self._Transition(wave)
    if closestTransition is None:
        print('No wavelengths defined')
    else:
        relativeError = closestTransition[3] / closestTransition[2] - 1
        print('Input wave: {0:.1F}'.format(closestTransition[3]))
        print('Closest wave found: {0:.1F}'.format(closestTransition[2]))
        print('Relative error: {0:.0E} '.format(relativeError))
        print('Transition: {0[0]} -> {0[1]}'.format(closestTransition))

getAtomDict(atom_list=None, elem_list=None, spec_list=None, only_coll=False, **kwargs)

Initializes all atoms, according to the atomic files available. The elem objects are given conventional names elem+spec (e.g., O III is O3)

Parameters:

Name Type Description Default
atom_list

a list of the ions for which the elem is to be computed Takes precedence on elem_list and spec_list

None
elem_list

a list of all the elements for which the elem is to be computed (all by default)

None
spec_list

a list of the spectra for which the elem is to be computed (all by default)

None
only_coll

if True, ionly Atom are sent back,. Otherwise (default), Atom and RecAtom are sent back

False

Usage:

all = pn.getAtomDict()

print(all['S2'].name)

some = pn.getAtomDict(elem_list=['C', 'N', 'O'])

some = pn.getAtomDict(atom_list=['O2', 'O3', 'Ar3'])
Source code in pyneb/core/pynebcore.py
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
def getAtomDict(atom_list=None, elem_list=None, spec_list=None, only_coll=False, **kwargs):
    """ 
    Initializes all atoms, according to the atomic files available.
    The elem objects are given conventional names elem+spec (e.g., O III is O3)

    Parameters:
        atom_list:     a list of the ions for which the elem is to be computed 
                        Takes precedence on elem_list and spec_list
        elem_list:     a list of all the elements for which the elem is to be computed (all by default)
        spec_list:     a list of the spectra for which the elem is to be computed (all by default)
        only_coll:     if True, ionly Atom are sent back,. Otherwise (default), Atom and RecAtom are sent back
        _ **kwargs      argumentas passed to Atom, e.g. OmegaInterp

    **Usage:**

        all = pn.getAtomDict()

        print(all['S2'].name)

        some = pn.getAtomDict(elem_list=['C', 'N', 'O'])

        some = pn.getAtomDict(atom_list=['O2', 'O3', 'Ar3'])

    """ 
    all_atoms = {}

    if atom_list is None:       
        if spec_list is None:
            spec_list = SPEC_LIST
        if elem_list is None:
            atom_list = atomicData.getAllAtoms()
        else:
            atom_list = []
            for elem in elem_list:
                for spec in spec_list:
                    atom_list.append(elem + str(spec)) 

    for atom in atom_list:
        elem, spec = parseAtom(atom)        
        try:
            this_atom = Atom(elem, spec, **kwargs)
            if this_atom.is_valid:
                all_atoms[atom] = this_atom
            log_.message('Including ' + atom, calling='getAtomDict')
        except:
            log_.message(atom + ' not found', calling='getAtomDict')
        if not only_coll:
            try:
                this_atom = RecAtom(elem, spec, **kwargs)
                if this_atom.is_valid:
                    if atom[-1] != 'r':
                        add_r = 'r'
                    else:
                        add_r = ''
                    all_atoms[atom+add_r] = this_atom
                log_.message('Including ' + atom, calling='getAtomDict')
            except:
                log_.message(atom + ' not found', calling='getAtomDict')

    return all_atoms

getHbEmissivity(tem=-1, den=1.0)

Compute Hbeta emissivity in erg/s/(N(H+)*N(e-)) for a given temperature with the formula by Aller (1984)

Parameters:

Name Type Description Default
tem

electronic temperature in K

-1

Usage:

getHbemissivity(tem=10000)
Source code in pyneb/core/pynebcore.py
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
def getHbEmissivity(tem= -1, den=1.):
    """ 
    Compute Hbeta emissivity in erg/s/(N(H+)*N(e-)) for a given temperature with the formula 
        by Aller (1984)

    Parameters:
        tem:     electronic temperature in K

    **Usage:**

        getHbemissivity(tem=10000)
    """ 
#    tem4 = np.asarray(tem) * 1.0e-4
#    j_hb = 1.387 / pow(tem4, 0.983) / pow(10., 0.0424 / tem4) * 1.e-25
#
#    # Remove jhb for tem4 < 0 or tem4 > 1e2
#    ((tem4 < 0.) | (tem4 > 1e2)).choose(j_hb, -1)
#
#    return j_hb

    tem4 = np.asarray(tem) * 1.0e-4
    j_hb = 1.387e-25 / tem4**0.983 / 10.**(0.0424 / tem4)

    j_hb_500 = 10**(-23.95 + 0.00013*np.log10(den)**4.0)
    j_hb_3000 = 1.387e-25 / .3**0.983 / 10.**(0.0424 / .3)
    a = (j_hb_3000 - j_hb_500) / (1./3000 - 1./500.)
    b = j_hb_3000 - a / 3000.
    j_hb_low = a / np.asarray(tem) + b

    j_hb = (tem4 < 0.3).choose(j_hb, j_hb_low)
    j_hb = ((tem4 < .0) | (tem4 > 1e2)).choose(j_hb, -1)

    return j_hb

getLineLabel(elem, spec, wave, blend=False)

Build a line label in the standard PyNeb format. Return atom_label, wave_label, and line_label (strings representing the atom and wave fragments of the line label and the complete line label)

Parameters:

Name Type Description Default
elem

symbol of the selected element

required
spec

ionization stage in spectroscopic notation (I = 1, II = 2, etc.)

required
wave

wavelength of the line

required
blend

blend flag (default = False)

False

@see parseLineLabel

Source code in pyneb/core/pynebcore.py
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
def getLineLabel(elem, spec, wave, blend=False):
    """
    Build a line label in the standard PyNeb format. Return atom_label, wave_label, and line_label 
            (strings representing the atom and wave fragments of the line label and the 
                complete line label)

    Parameters:
        elem:      symbol of the selected element
        spec:      ionization stage in spectroscopic notation (I = 1, II = 2, etc.)
        wave:      wavelength of the line
        blend:     blend flag (default = False)

    @see parseLineLabel

    """    
    if isinstance(wave, str):
        wave_label = wave
    else:
        wave4 = wave / 1.e4
        if wave < 10000.:
            wave_label = "{0:.0f}A".format(wave)
        else:
            wave_label = "{0:.1f}m".format(wave4)
    atom_label = elem + str(spec)
    if blend:
        blend_flag = '+'
    else:
        blend_flag = ''
    line_label = atom_label + '_' + wave_label + blend_flag

    return atom_label, wave_label, line_label

getRecEmissivity(tem, den, lev_i=None, lev_j=None, atom='H1', method='linear', wave=None, product=True)

The function instantiates a RecAtom and store it into atomicData._RecombData for a further use. More possibilities are obtained using the RecAtom class.

Parameters:

Name Type Description Default
tem

temperature in K

required
den

density in cm-3

required
lev_i

levels (lev_i>lev_j, i_min=1)

None
lev_j

levels (lev_i>lev_j, i_min=1)

None
atom

atom (e.g. 'H1', 'He1')

'H1'
method

interpolation method ('linear', 'nearest', 'cubic'), sent to scipy.interpolate.griddata

'linear'
wave

alternative way of identifying emision line.

None

Usage:

print(getRecEmissivity(1e4, 1e3, 3, 2, atom='H1') / getRecEmissivity(1e4, 1e3, 4, 2, atom='H1')) 
    # return Ha/Hb
Source code in pyneb/core/pynebcore.py
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
def getRecEmissivity(tem, den, lev_i=None, lev_j=None, atom='H1', method='linear', wave=None, product=True):
    """
    The function instantiates a RecAtom and store it into atomicData._RecombData for a further use.
    More possibilities are obtained using the RecAtom class.



    Parameters:
        tem:           temperature in K
        den:           density in cm-3
        lev_i:  levels (lev_i>lev_j, i_min=1)
        lev_j:  levels (lev_i>lev_j, i_min=1)
        atom:          atom (e.g. 'H1', 'He1')
        method:        interpolation method ('linear', 'nearest', 'cubic'), sent to scipy.interpolate.griddata
        wave:          alternative way of identifying emision line.

    **Usage:**

        print(getRecEmissivity(1e4, 1e3, 3, 2, atom='H1') / getRecEmissivity(1e4, 1e3, 4, 2, atom='H1')) 
            # return Ha/Hb 

    """
    calling = 'getRecEmissivity'

    if config.INSTALLED['scipy']:
        elem, spec = parseAtom(atom)

        if atom not in atomicData._RecombData:
            atomicData._RecombData[atom] = RecAtom(elem, spec)
        return atomicData._RecombData[atom].getEmissivity(tem=tem, den=den, lev_i=lev_i, lev_j=lev_j,
                                                             method=method, wave=wave, product=product)
    else:
        if (atom == 'H1') and (lev_i == 4) and (lev_j == 2):
            log_.warn('Scipy is missing, {0} returning Hbeta from Aller 84'.format(calling), calling)
            return getHbEmissivity(tem, den)
        else:
            log_.error('Only Hbeta emissivity available, as scipy not installed', calling)

isValid(line_label)

Return True if the line label correspond to a valid line from LINE_LABEL_LIST or BLEND_LIST

Parameters:

Name Type Description Default
line_label

label to be tested

required

Usage:

isValid('O3_5007A')
Source code in pyneb/core/pynebcore.py
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
def isValid(line_label):
    """
    Return True if the line label correspond to a valid line from LINE_LABEL_LIST or BLEND_LIST

    Parameters:
        line_label: label to be tested

    **Usage:**

        isValid('O3_5007A')

    """
    elem, spec, atom, wave, waveLabel, blend = parseLineLabel(line_label)
    if atom in LINE_LABEL_LIST:
            if (waveLabel in LINE_LABEL_LIST[atom]) or (line_label in BLEND_LIST):
                is_valid = True
            else:
                is_valid = False
    else:
        is_valid = False
    return is_valid

parseLineLabel(lineLabel)

Parse the line label to extract the substrings referring to the atom (elem, spec and atom) and the numerical value of the wave

Parameters:

Name Type Description Default
label

line label in the standard PyNeb format

required

Returns:

Type Description

elem, spec, atom_label, wave, wave_label, blend strings containing the elem, spec, atom and wave; numerical value of the wave, in Angstrom; and blend flag

Source code in pyneb/core/pynebcore.py
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
def parseLineLabel(lineLabel):
    """
    Parse the line label to extract the substrings referring to the atom (elem, spec and atom)
    and the numerical value of the wave

    Parameters:
        label:    line label in the standard PyNeb format

    Returns:
        elem, spec, atom_label, wave, wave_label, blend  strings containing the elem, spec, atom and 
                                                              wave; numerical value of the wave, 
                                                              in Angstrom; and blend flag 
    """
    ##
    # @todo maybe rearrange the order so 1) it is compatible with getLineLabel, or 2) it lists all the strings first 

    blend = False
    wave_unit = 'A'
    # extract information on the atom
    elem_spec = strExtract(lineLabel, ' ', '_')
    elem, spec = parseAtom(elem_spec)
    atom_label = elem + str(spec)
    if len(elem_spec) > 0:
        if elem_spec[-1] == 'r':
            atom_label += 'r'
    # extract information on the wave
    wave_label = lineLabel.split('_')[1]
    wave = ''
    for s in wave_label:
        if s.isdigit() or s == '.':
            wave += s
        elif s == '+':
            blend = True
        elif s in ('A', 'm'):
            wave_unit = s
    try:
        wave = float(wave)
    except:
        wave = 0.    
    if wave_unit == 'm':
        wave = wave * 1.e4

    return elem, spec, atom_label, wave, wave_label, blend