-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_db.py
More file actions
601 lines (457 loc) · 17.7 KB
/
create_db.py
File metadata and controls
601 lines (457 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
#!/usr/bin/python3
import logging
import pprint
import yaml
import json
from pathlib import Path
import gridfs
from pymongo import MongoClient
from pymongo.errors import BulkWriteError
from simtools import db_handler
def readDescriptions(prefixInputDB):
sections = [
'Telescope_optics',
'Camera',
'Photon_conversion',
'Trigger',
'Readout_electronics',
'Sites_DB'
]
descriptions = dict()
for sectionNow in sections:
inputFileNow = '{}/descriptionsYml/{}.yml'.format(prefixInputDB, sectionNow)
with open(inputFileNow, 'r') as stream:
descriptions.update(yaml.load(stream, Loader=yaml.FullLoader))
# Read also raw sim_telarray descriptions of parameters which are not in the reports.
inputFileNow = '{}/descriptionsYml/otherDescriptions.yml'.format(prefixInputDB)
with open(inputFileNow, 'r') as stream:
otherDescriptions = yaml.load(stream, Loader=yaml.FullLoader)
for parNow, descNow in otherDescriptions.items():
if parNow in descriptions:
continue
else:
descriptions[parNow] = descNow
return descriptions
def readOneTelYamlDB(fInputDB):
with open(fInputDB, 'r') as stream:
parsDB = yaml.load(stream, Loader=yaml.FullLoader)
return parsDB
def insertFileToDB(db, file, **kwargs):
fileSystem = gridfs.GridFS(db)
if fileSystem.exists({'filename': kwargs['filename']}):
return fileSystem.find_one({'filename': kwargs['filename']})
with open(file, 'rb') as dataFile:
file_id = fileSystem.put(dataFile, **kwargs)
return file_id
def insertFilesToDB(dbClient, dbName, filesToAddToDB):
db = dbClient[dbName]
for fileNow in filesToAddToDB:
kwargs = {'content_type': 'ascii/dat', 'filename': Path(fileNow).name}
insertFileToDB(db, fileNow, **kwargs)
return
def dropDatabases(dbClient):
dbClient.drop_database(DB_TABULATED_DATA)
dbClient.drop_database(DB_CTA_SIMULATION_MODEL)
dbClient.drop_database(DB_CTA_SIMULATION_MODEL_DESCRIPTIONS)
return
def getFile(dbClient, dbName, fileName):
db = dbClient[dbName]
fileSystem = gridfs.GridFS(db)
if fileSystem.exists({'filename': fileName}):
return fileSystem.find_one({'filename': fileName})
else:
raise FileNotFoundError(
'The file {} does not exist in the database {}'.format(fileName, dbName)
)
def writeFileToDisk(dbClient, dbName, path, file):
db = dbClient[dbName]
fsOutput = gridfs.GridFSBucket(db)
with open(Path(path).joinpath(file.filename), 'wb') as outputFile:
fsOutput.download_to_stream_by_name(file.filename, outputFile)
return
def getYamlDB(telescopeType, prefixInputDB):
telNameInYamlDB = telescopeType
if telNameInYamlDB == 'MST-Structure':
telNameInYamlDB = 'MST-optics'
if telNameInYamlDB in sstNamesDict.keys():
telNameInYamlDB = sstNamesDict[telescopeType]
fileInputDB = '{}configReports/parValues-{}.yml'.format(prefixInputDB, telNameInYamlDB)
return readOneTelYamlDB(fileInputDB)
def inferType(descriptions, par, value):
if par not in descriptions.keys():
return str
parDesc = descriptions[par]
if 'type' not in parDesc:
return str
typeNow = parDesc['type'].lower()
if typeNow in ['string', 'text', 'unknown']:
return str
elif typeNow == 'double':
try:
_value = float(value)
return float
except ValueError:
return str
elif 'int' in typeNow: # Include also UInt
try:
_value = int(value)
return int
except ValueError:
return str
else:
return str # Shouldn't actually reach here
def additionalEntries(parDesc):
addEntriesDict = dict()
if 'unit' in parDesc:
addEntriesDict['unit'] = parDesc['unit']
if 'items' in parDesc:
addEntriesDict['items'] = parDesc['items']
if 'minimum' in parDesc:
addEntriesDict['minimum'] = parDesc['minimum']
if 'maximum' in parDesc:
addEntriesDict['maximum'] = parDesc['maximum']
return addEntriesDict
def getDescriptions(parDesc):
descriptionDict = dict()
if 'description' in parDesc:
descriptionDict['description'] = parDesc['description']
if 'shortDescription' in parDesc:
descriptionDict['shortDescription'] = parDesc['shortDescription']
if 'assembly' in parDesc:
descriptionDict['assembly'] = parDesc['assembly']
if 'parOrAlg' in parDesc:
descriptionDict['parOrAlg'] = parDesc['parOrAlg']
# These are for skipping printing parameter based on list condition,
# i.e., print only if the value of parameter A is in the list 1,2,3 ---> { A : [1,2,3] }
if 'printIf' in parDesc:
descriptionDict['printIf'] = parDesc['printIf']
if 'printIfNot' in parDesc:
descriptionDict['printIfNot'] = parDesc['printIfNot']
# These are for skipping printing parameter based on their value (e.g., zero)
if 'printIfValue' in parDesc:
descriptionDict['printIfValue'] = parDesc['printIfValue']
if 'printIfNotValue' in parDesc:
descriptionDict['printIfNotValue'] = parDesc['printIfNotValue']
# These are for skipping printing parameter based on the value of another parameter
if 'printIfValueEqualTo' in parDesc:
descriptionDict['printIfValueEqualTo'] = parDesc['printIfValueEqualTo']
if 'printIfValueNotEqualTo' in parDesc:
descriptionDict['printIfValueNotEqualTo'] = parDesc['printIfValueNotEqualTo']
return descriptionDict
def createDB(dbClient, prefixInputDB):
dropDatabases(dbClient)
descriptions = readDescriptions(prefixInputDB)
filesToAddToDB = set()
dbEntries = list()
descriptionEntries = list()
for site, layout in layouts.items():
for telNow, telTypes in layout.items():
if not isinstance(telTypes, list):
telTypes = [telTypes]
print('Preparing input for {} {} telescopes in the {}'.format(
len(telTypes),
telNow,
site)
)
pars = getYamlDB(telNow, prefixInputDB)
# Extract a list of all versions currently in the yaml DB.
# Can be extracted from a random telescope/parameter, as they are all the same.
versions = pars['fadc_amplitude'].copy()
versions.pop('Applicable', None)
for telTypeNow in telTypes:
for versionNow in versions:
for parNow in pars:
if versionNow not in pars[parNow]:
continue
dbEntry = dict()
dbEntry['Telescope'] = '{}-{}-{}'.format(site, telNow, telTypeNow)
dbEntry['Parameter'] = parNow
dbEntry['Applicable'] = pars[parNow]['Applicable']
dbEntry['Version'] = versionNow
value = pars[parNow][versionNow] # Shorter for the code below
valueType = inferType(descriptions, parNow, value)
dbEntry['Type'] = str(valueType)
if '.dat' in str(value) or '.txt' in str(value):
dbEntry['File'] = True
if versionNow != 'default':
filesToAddToDB.add('{}datFiles/{}'.format(prefixInputDB, value))
else:
dbEntry['File'] = False
try:
value = valueType(value)
except ValueError:
pass
dbEntry['Value'] = value
dbEntry.update(additionalEntries(descriptions[parNow]))
dbEntries.append(dbEntry)
print('Preparing description entries')
for parNow in pars:
descNow = dict()
descNow['Parameter'] = parNow
descNow.update(getDescriptions(descriptions[parNow]))
descriptionEntries.append(descNow)
print('Filling {} DB'.format(DB_CTA_SIMULATION_MODEL))
db = dbClient[DB_CTA_SIMULATION_MODEL]
collection = db.telescopes
try:
collection.insert_many(dbEntries)
except BulkWriteError as exc:
raise exc(exc.details)
print('Adding files to {} DB'.format(DB_TABULATED_DATA))
insertFilesToDB(dbClient, DB_TABULATED_DATA, filesToAddToDB)
print('Filling {} DB'.format(DB_CTA_SIMULATION_MODEL_DESCRIPTIONS))
db = dbClient[DB_CTA_SIMULATION_MODEL_DESCRIPTIONS]
collection = db.telescopes
try:
collection.insert_many(descriptionEntries)
except BulkWriteError as exc:
raise exc(exc.details)
createSitesDB(dbClient, prefixInputDB, descriptions)
addMetadata(dbClient)
return
def writeJSON(dbClient, version='prod4', onlyApplicable=False):
telsToRead = {
'LST': {
'dbName': 'North-LST-D234',
'jsonName': 'Lx',
'nTel': 4
},
'MST': {
'dbName': ['North-MST-Structure-D', 'North-MST-NectarCam-D'],
'jsonName': 'Mx',
'nTel': 15
}
}
with open('/Users/ogueta/work/cta/gammasim/gammasim-tools/play/db/sections.yml', 'r') as stream:
try:
sections = yaml.load(stream, Loader=yaml.FullLoader)
except yaml.YAMLError as exc:
raise exc
collection = dbClient[DB_CTA_SIMULATION_MODEL].telescopes
parameters = dict()
for telNow, telNamesDict in telsToRead.items():
genericTelPars = dict()
telNameDB = telNamesDict['dbName']
if not isinstance(telNameDB, list):
telNameDB = [telNameDB]
_parsFromDB = dict()
for telNameNow in telNameDB:
# We take the defaults from the structure entries
if telNameNow == 'North-MST-FlashCam-D':
onlyApplicable = True
query = {
'Telescope': telNameNow,
'Version': version,
}
if onlyApplicable:
query['Applicable'] = onlyApplicable
for i_entry, post in enumerate(collection.find(query)):
parNow = post['Parameter']
_parsFromDB[parNow] = post
_parsFromDB[parNow].pop('_id', None)
_parsFromDB[parNow].pop('Parameter', None)
_parsFromDB[parNow].pop('Telescope', None)
for sectionNow, parList in sections.items():
if sectionNow in ['Sites', 'Sections', 'Unnecessary']:
continue
genericTelPars[sectionNow] = dict()
genericTelPars[sectionNow]['id'] = sectionNow
genericTelPars[sectionNow]['title'] = sectionNow
genericTelPars[sectionNow]['val'] = 0
genericTelPars[sectionNow]['children'] = list()
for parNow in parList:
# if onlyApplicable:
# if not _parsFromDB[parNow]['Applicable']:
# continue
if parNow not in _parsFromDB:
continue
childDict = dict()
childDict['id'] = parNow
childDict['title'] = parNow
childDict['val'] = _parsFromDB[parNow]['Value']
genericTelPars[sectionNow]['children'].append(childDict)
for i_tel in range(1, telNamesDict['nTel'] + 1):
telNameJson = '{0}{1:02}'.format(telNamesDict['jsonName'], i_tel)
parameters[telNameJson] = genericTelPars
with open('telescopeModel.json', 'w') as fp:
json.dump(parameters, fp, sort_keys=False, indent=4)
def updateParameter(dbClient, telescope, version, parameter, newValue):
collection = dbClient[DB_CTA_SIMULATION_MODEL].telescopes
query = {
'Telescope': telescope,
'Version': version,
'Parameter': parameter,
}
parEntry = collection.find_one(query)
oldValue = parEntry['Value']
print('For telescope {}, version {}\nreplacing {} value from {} to {}'.format(
telescope,
version,
parameter,
oldValue,
newValue
))
queryUpdate = {'$set': {'Value': newValue}}
collection.update_one(query, queryUpdate)
return
def createSitesDB(dbClient, prefixInputDB, descriptions):
print('Preparing sites DB')
filesToAddToDB = set()
dbEntries = list()
descriptionEntries = list()
sites = {
'lapalma': 'North',
'paranal': 'South'
}
pars = getYamlDB('Sites', prefixInputDB)
# Extract a list of all versions currently in the yaml DB.
# Can be extracted from a random parameter, as they are all the same.
versions = pars['paranal_altitude'].copy()
versions.pop('Applicable', None)
for versionNow in versions:
for parNow in pars:
if versionNow not in pars[parNow]:
continue
dbEntry = dict()
dbEntry['Site'] = sites[parNow.split('_')[0]]
dbEntry['Parameter'] = '_'.join(parNow.split('_')[1:])
dbEntry['Applicable'] = pars[parNow]['Applicable']
dbEntry['Version'] = versionNow
value = pars[parNow][versionNow] # Shorter for the code below
valueType = inferType(descriptions, parNow, value)
dbEntry['Type'] = str(valueType)
if any(ext in str(value) for ext in ['.dat', '.txt', '.lis']):
dbEntry['File'] = True
if versionNow != 'default':
filesToAddToDB.add('{}datFiles/{}'.format(prefixInputDB, value))
else:
dbEntry['File'] = False
try:
value = valueType(value)
except ValueError:
pass
dbEntry['Value'] = value
dbEntry.update(additionalEntries(descriptions[parNow]))
dbEntries.append(dbEntry)
print('Preparing description entries')
for parNow in pars:
descNow = dict()
descNow['Parameter'] = '_'.join(parNow.split('_')[1:])
descNow.update(getDescriptions(descriptions[parNow]))
descriptionEntries.append(descNow)
print('Filling {} DB'.format(DB_CTA_SIMULATION_MODEL))
db = dbClient[DB_CTA_SIMULATION_MODEL]
siteCollection = db.sites
try:
siteCollection.insert_many(dbEntries)
except BulkWriteError as exc:
raise exc(exc.details)
print('Adding files to {} DB'.format(DB_TABULATED_DATA))
insertFilesToDB(dbClient, DB_TABULATED_DATA, filesToAddToDB)
print('Filling {} DB'.format(DB_CTA_SIMULATION_MODEL_DESCRIPTIONS))
db = dbClient[DB_CTA_SIMULATION_MODEL_DESCRIPTIONS]
siteCollection = db.sites
try:
siteCollection.insert_many(descriptionEntries)
except BulkWriteError as exc:
raise exc(exc.details)
return
def addMetadata(dbClient):
print('Adding Metadata')
dbEntries = list()
dbEntry = dict()
dbEntry['Entry'] = 'Simulation-Model-Tags'
dbEntry['Tags'] = {
'Current': {
'Value': '2020-06-28',
'Label': 'Prod5'
},
'Latest': {
'Value': '2020-06-28',
'Label': 'Prod5'
}
}
dbEntries.append(dbEntry)
print('Filling {} DB'.format(DB_CTA_SIMULATION_MODEL))
db = dbClient[DB_CTA_SIMULATION_MODEL]
metadataCollection = db.metadata
try:
metadataCollection.insert_many(dbEntries)
except BulkWriteError as exc:
raise exc(exc.details)
return
if __name__ == '__main__':
logger = logging.getLogger('createDB')
logger.setLevel('INFO')
# dict in Python >=3.6 is ordered (finally),
# so we can use this order to deal with MST structure/cameras reading sequence.
layouts = {
'North': {
'LST': [1, 'D234'],
'MST-Structure': 'D',
'MST-FlashCam': 'D',
'MST-NectarCam': 'D'
},
'South': {
'LST': 'D',
'MST-Structure': 'D',
'MST-FlashCam': 'D',
'SCT': 'D',
'SST-Structure': 'D',
'SST-Camera': 'D',
'SST-ASTRI': 'D',
'SST-1M': 'D',
'SST-GCT': 'D'
}
}
sstNamesDict = {
'SST-ASTRI': 'SST-2M-ASTRI',
'SST-1M': 'SST-1M',
'SST-GCT': 'SST-2M-GCT-S'
}
prefixInputDB = (
'/Users/ogueta/work/cta/aswg/simulations/simulation-model/simulation-model-description/'
)
DB_TABULATED_DATA = 'CTA-Simulation-Model'
DB_CTA_SIMULATION_MODEL = 'CTA-Simulation-Model'
DB_CTA_SIMULATION_MODEL_DESCRIPTIONS = 'CTA-Simulation-Model-Descriptions'
# DB_TABULATED_DATA = 'cta'
# DB_CTA_SIMULATION_MODEL = 'cta'
remoteDB = True
if remoteDB:
db = db_handler.DatabaseHandler(logger.name)
dbClient, _tunnel = db._openMongoDB()
else:
dbClient = MongoClient()
pprint.pprint(dbClient.list_database_names())
# dropDatabases(dbClient)
createDB(dbClient, prefixInputDB)
db.updateParameter(
DB_CTA_SIMULATION_MODEL,
'North-LST-1',
'2020-06-28',
'mirror_list',
'mirror_CTA-N-LST1_v2019-03-31.dat'
)
db.updateParameter(
DB_CTA_SIMULATION_MODEL,
'North-LST-D234',
'2020-06-28',
'mirror_list',
'mirror_CTA-N-LST2_v2020-04-07.dat'
)
# writeJSON(dbClient, 'prod4', False)
# updateParameter(
# dbClient,
# 'North-LST-1',
# '2020-06-28',
# 'mirror_list',
# 'mirror_CTA-N-LST1_v2019-03-31.dat'
# )
# updateParameter(
# dbClient,
# 'North-LST-D234',
# '2020-06-28',
# 'mirror_list',
# 'mirror_CTA-N-LST2_v2020-04-07.dat'
# )