Coverage for spectractor/config.py: 27%

Shortcuts on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

80 statements  

1import configparser 

2import os 

3import sys 

4import re 

5import numpy as np 

6import logging 

7import astropy.units as units 

8 

9from spectractor import parameters 

10if not parameters.CALLING_CODE: 10 ↛ 13line 10 didn't jump to line 13, because the condition on line 10 was never false

11 import coloredlogs 

12 

13logging.getLogger("matplotlib").setLevel(logging.ERROR) 

14logging.getLogger("numba").setLevel(logging.ERROR) 

15logging.getLogger("h5py").setLevel(logging.ERROR) 

16 

17 

18def from_config_to_parameters(config): 

19 """Convert config file keywords into spectractor.parameters parameters. 

20 

21 Parameters 

22 ---------- 

23 config: ConfigParser 

24 The ConfigParser instance to convert 

25 

26 Examples 

27 -------- 

28 

29 >>> config = configparser.ConfigParser() 

30 >>> config.read(os.path.join(parameters.CONFIG_DIR,"default.ini")) # doctest: +ELLIPSIS 

31 ['/.../config/default.ini'] 

32 >>> from_config_to_parameters(config) 

33 >>> assert parameters.OBS_NAME == "DEFAULT" 

34 

35 """ 

36 # List all contents 

37 for section in config.sections(): 

38 for options in config.options(section): 

39 value = config.get(section, options) 

40 if re.match("[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?", value): 

41 if ' ' in value: 

42 value = str(value) 

43 elif '.' in value or 'e' in value: 

44 value = float(value) 

45 else: 

46 value = int(value) 

47 elif value == 'True' or value == 'False': 

48 value = config.getboolean(section, options) 

49 else: 

50 value = str(value) 

51 setattr(parameters, options.upper(), value) 

52 

53 

54def load_config(config_filename): 

55 """Load configuration parameters from a .ini config file. 

56 

57 Parameters 

58 ---------- 

59 config_filename: str 

60 The path to the config file. 

61 

62 Examples 

63 -------- 

64 

65 >>> load_config("./config/ctio.ini") 

66 >>> assert parameters.OBS_NAME == "CTIO" 

67 

68 .. doctest: 

69 :hide: 

70 

71 >>> load_config("./config/ctio.ini") 

72 >>> load_config("ctio.ini") 

73 >>> load_config("./config/unknown_file.ini") #doctest: +ELLIPSIS 

74 Traceback (most recent call last): 

75 ... 

76 FileNotFoundError: Config file ./config/unknown_file.ini does not exist. 

77 

78 """ 

79 if not os.path.isfile(os.path.join(parameters.CONFIG_DIR, "default.ini")): 

80 raise FileNotFoundError('Config file default.ini does not exist.') 

81 # Load the configuration file 

82 config = configparser.ConfigParser() 

83 config.read(os.path.join(parameters.CONFIG_DIR, "default.ini")) 

84 from_config_to_parameters(config) 

85 

86 if not os.path.isfile(config_filename): 

87 if not os.path.isfile(os.path.join(parameters.CONFIG_DIR, config_filename)): 

88 raise FileNotFoundError(f'Config file {config_filename} does not exist.') 

89 else: 

90 config_filename = os.path.join(parameters.CONFIG_DIR, config_filename) 

91 # Load the configuration file 

92 config = configparser.ConfigParser() 

93 config.read(config_filename) 

94 from_config_to_parameters(config) 

95 

96 # Derive other parameters 

97 parameters.MY_FORMAT = "%(asctime)-20s %(name)-10s %(funcName)-20s %(levelname)-6s %(message)s" 

98 logging.basicConfig(format=parameters.MY_FORMAT, level=logging.WARNING) 

99 mypath = os.path.dirname(__file__) 

100 parameters.DISPERSER_DIR = os.path.join(mypath, parameters.DISPERSER_DIR) 

101 parameters.THROUGHPUT_DIR = os.path.join(mypath, parameters.THROUGHPUT_DIR) 

102 parameters.CCD_ARCSEC2RADIANS = np.pi / (180. * 3600.) # conversion factor from arcsec to radians 

103 parameters.OBS_DIAMETER = parameters.OBS_DIAMETER * units.m # Diameter of the telescope 

104 parameters.OBS_SURFACE = np.pi * parameters.OBS_DIAMETER ** 2 / 4. # Surface of telescope 

105 parameters.LAMBDAS = np.arange(parameters.LAMBDA_MIN, parameters.LAMBDA_MAX, 1) 

106 parameters.FLAM_TO_ADURATE = ((parameters.OBS_SURFACE * parameters.SED_UNIT * parameters.TIME_UNIT 

107 * parameters.wl_dwl_unit / parameters.hc / parameters.CCD_GAIN).decompose()).value 

108 parameters.CALIB_BGD_NPARAMS = parameters.CALIB_BGD_ORDER + 1 

109 

110 # check consistency 

111 if parameters.PIXWIDTH_BOXSIZE > parameters.PIXWIDTH_BACKGROUND: 

112 sys.exit(f'parameters.PIXWIDTH_BOXSIZE must be smaller than parameters.PIXWIDTH_BACKGROUND (or equal).') 

113 

114 if parameters.VERBOSE: 

115 for section in config.sections(): 

116 print(f"Section: {section}") 

117 for options in config.options(section): 

118 value = config.get(section, options) 

119 par = getattr(parameters, options.upper()) 

120 print(f"x {options}: {value}\t=> parameters.{options.upper()}: {par}\t {type(par)}") 

121 

122 

123def set_logger(logger): 

124 """Logger function for all classes. 

125 

126 Parameters 

127 ---------- 

128 logger: str 

129 Name of the class, usually self.__class__.__name__ 

130 

131 Returns 

132 ------- 

133 my_logger: logging 

134 Logging object 

135 

136 Examples 

137 -------- 

138 

139 >>> class Test: 

140 ... def __init__(self): 

141 ... self.my_logger = set_logger(self.__class__.__name__) 

142 ... def log(self): 

143 ... self.my_logger.info('This info test function works.') 

144 ... self.my_logger.debug('This debug test function works.') 

145 ... self.my_logger.warning('This warning test function works.') 

146 >>> from spectractor import parameters 

147 >>> parameters.VERBOSE = True 

148 >>> parameters.DEBUG = True 

149 >>> test = Test() 

150 >>> test.log() 

151  

152 """ 

153 my_logger = logging.getLogger(logger) 

154 if not parameters.CALLING_CODE: 154 ↛ 157line 154 didn't jump to line 157, because the condition on line 154 was never false

155 coloredlogs.DEFAULT_LEVEL_STYLES['warn'] = {'color': 'yellow'} 

156 coloredlogs.DEFAULT_FIELD_STYLES['levelname'] = {'color': 'white', 'bold': True} 

157 if parameters.VERBOSE > 0: 157 ↛ 158line 157 didn't jump to line 158, because the condition on line 157 was never true

158 my_logger.setLevel(logging.INFO) 

159 if not parameters.CALLING_CODE: 

160 coloredlogs.install(fmt=parameters.MY_FORMAT, level=logging.INFO) 

161 else: 

162 my_logger.setLevel(logging.WARNING) 

163 if not parameters.CALLING_CODE: 163 ↛ 165line 163 didn't jump to line 165, because the condition on line 163 was never false

164 coloredlogs.install(fmt=parameters.MY_FORMAT, level=logging.WARNING) 

165 if parameters.DEBUG_LOGGING: 165 ↛ 166line 165 didn't jump to line 166, because the condition on line 165 was never true

166 my_logger.setLevel(logging.DEBUG) 

167 if not parameters.CALLING_CODE: 

168 coloredlogs.install(fmt=parameters.MY_FORMAT, level=logging.DEBUG) 

169 return my_logger 

170 

171 

172if __name__ == "__main__": 172 ↛ 173line 172 didn't jump to line 173, because the condition on line 172 was never true

173 import doctest 

174 

175 doctest.testmod()