Coverage for datastorage.py: 57%

46 statements  

« prev     ^ index     » next       coverage.py v7.5.1, created at 2024-05-29 20:53 +0000

1import json 

2import idgenerator 

3import logging 

4 

5class DataPoint(object): 

6 """This class is used to represent one datapoint""" 

7 def __init__(self, patient_id, experiment_id, data): 

8 self.id = idgenerator.create_unique_identifier() 

9 self.patient_id = patient_id 

10 self.experiment_id = experiment_id 

11 self.data = data 

12 

13class DataStorage(object): 

14 def __new__(cls): 

15 if not hasattr(cls, 'instance'): 

16 cls.instance = super(DataStorage, cls).__new__(cls) 

17 cls.instance.experiments = {} 

18 cls.instance.patients = {} 

19 cls.instance.data = [] 

20 return cls.instance 

21 

22 def create_patient(self, name): 

23 """Creates a patient with the given name and an identifier. The identifier is the return value.""" 

24 id = len(self.patients) 

25 self.patients[id] = name 

26 return id 

27 

28 def create_experiment(self, name): 

29 id = len(self.experiments) 

30 self.experiments[id] = name 

31 return id 

32 

33 def get_patients(self): 

34 return self.patients 

35 

36 def get_experiments(self): 

37 return self.experiments 

38 

39 def add_data(self, dataobj): 

40 self.data.append(dataobj) 

41 

42 def store_data(self, filename): 

43 # store data into file 

44 self.store(filename, self.data) 

45 self.data.clear() 

46 

47 def store_patients(self, filename): 

48 self.store(filename, self.patients) 

49 

50 def store_experiments(self, filename): 

51 self.store(filename, self.experiments) 

52 

53 def store(self, filename, data): 

54 json_object = json.dumps(data, indent=4) 

55 fn = filename + ".json" 

56 with open(fn + ".json", "w") as outfile: 

57 outfile.write(json_object) 

58 logging.info("File saved: " + fn) 

59 

60if __name__ == '__main__': 

61 print(DataPoint.__doc__)