39 lines
1.3 KiB
Python
Executable File
39 lines
1.3 KiB
Python
Executable File
# Copyright 2022 Diagnostic Image Analysis Group, Radboudumc, Nijmegen, The Netherlands
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
|
|
import os
|
|
import numpy as np
|
|
import json
|
|
|
|
|
|
def save_metrics(metrics, file_path=None):
|
|
# convert dtypes to stock Python
|
|
save_metrics = sterilize(metrics)
|
|
|
|
# save metrics using safe file write
|
|
file_path_tmp = file_path + '.tmp'
|
|
with open(file_path_tmp, 'w') as fp:
|
|
json.dump(save_metrics, fp, indent=4)
|
|
os.rename(file_path_tmp, file_path)
|
|
|
|
|
|
def sterilize(obj):
|
|
if isinstance(obj, dict):
|
|
return {k: sterilize(v) for k, v in obj.items()}
|
|
elif isinstance(obj, (list, tuple, np.ndarray)):
|
|
return [sterilize(v) for v in obj]
|
|
elif isinstance(obj, (str, int, bool, float)):
|
|
return obj
|
|
else:
|
|
return obj.__repr__() |