Coverage for spectractor/config.py: 24%

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

97 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, rebin=True): 

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 rebin: bool, optional 

62 If True, the parameters.REBIN parameter is used and every parameters are changed to comply with the REBIN value. 

63 If False, the parameters.REBIN parameter is skipped and set to 1. 

64 

65 Examples 

66 -------- 

67 

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

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

70 

71 .. doctest: 

72 :hide: 

73 

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

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

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

77 Traceback (most recent call last): 

78 ... 

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

80 

81 """ 

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

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

84 # Load the configuration file 

85 config = configparser.ConfigParser() 

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

87 from_config_to_parameters(config) 

88 

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

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

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

92 else: 

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

94 # Load the configuration file 

95 config = configparser.ConfigParser() 

96 config.read(config_filename) 

97 from_config_to_parameters(config) 

98 

99 # Derive other parameters 

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

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

102 mypath = os.path.dirname(__file__) 

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

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

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

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

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

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

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

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

111 parameters.CALIB_BGD_NPARAMS = parameters.CALIB_BGD_ORDER + 1 

112 

113 if parameters.CCD_REBIN > 1 and rebin: 

114 apply_rebinning_to_parameters() 

115 else: 

116 parameters.CCD_REBIN = 1 

117 print("No rebinning: parameters.REBIN is forced to 1.") 

118 

119 # check consistency 

120 if parameters.PIXWIDTH_BOXSIZE > parameters.PIXWIDTH_BACKGROUND: 

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

122 

123 if parameters.VERBOSE: 

124 for section in config.sections(): 

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

126 for options in config.options(section): 

127 value = config.get(section, options) 

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

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

130 

131 

132def apply_rebinning_to_parameters(): 

133 """Divide or multiply original parameters by parameters.CCD_REBIN to set them correctly 

134 in the case of an image rebinning. 

135 

136 Examples 

137 -------- 

138 >>> parameters.PIXWIDTH_SIGNAL = 40 

139 >>> parameters.CCD_PIXEL2MM = 10 

140 >>> parameters.CCD_REBIN = 2 

141 >>> apply_rebinning_to_parameters() 

142 >>> parameters.PIXWIDTH_SIGNAL 

143 20 

144 >>> parameters.CCD_PIXEL2MM 

145 20 

146 

147 """ 

148 # Apply rebinning 

149 parameters.PIXDIST_BACKGROUND //= parameters.CCD_REBIN 

150 parameters.PIXWIDTH_BOXSIZE = max(10, parameters.PIXWIDTH_BOXSIZE // parameters.CCD_REBIN) 

151 parameters.PIXWIDTH_BACKGROUND //= parameters.CCD_REBIN 

152 parameters.PIXWIDTH_SIGNAL //= parameters.CCD_REBIN 

153 parameters.CCD_IMSIZE //= parameters.CCD_REBIN 

154 parameters.CCD_PIXEL2MM *= parameters.CCD_REBIN 

155 parameters.CCD_PIXEL2ARCSEC *= parameters.CCD_REBIN 

156 parameters.XWINDOW //= parameters.CCD_REBIN 

157 parameters.YWINDOW //= parameters.CCD_REBIN 

158 parameters.XWINDOW_ROT //= parameters.CCD_REBIN 

159 parameters.YWINDOW_ROT //= parameters.CCD_REBIN 

160 parameters.PSF_PIXEL_STEP_TRANSVERSE_FIT //= parameters.CCD_REBIN 

161 

162 

163def set_logger(logger): 

164 """Logger function for all classes. 

165 

166 Parameters 

167 ---------- 

168 logger: str 

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

170 

171 Returns 

172 ------- 

173 my_logger: logging 

174 Logging object 

175 

176 Examples 

177 -------- 

178 

179 >>> class Test: 

180 ... def __init__(self): 

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

182 ... def log(self): 

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

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

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

186 >>> from spectractor import parameters 

187 >>> parameters.VERBOSE = True 

188 >>> parameters.DEBUG = True 

189 >>> test = Test() 

190 >>> test.log() 

191  

192 """ 

193 my_logger = logging.getLogger(logger) 

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

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

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

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

198 my_logger.setLevel(logging.INFO) 

199 if not parameters.CALLING_CODE: 

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

201 else: 

202 my_logger.setLevel(logging.WARNING) 

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

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

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

206 my_logger.setLevel(logging.DEBUG) 

207 if not parameters.CALLING_CODE: 

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

209 return my_logger 

210 

211 

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

213 import doctest 

214 

215 doctest.testmod()