#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------------------------------------
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
# CANN Open Software License Agreement Version 2.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# -----------------------------------------------------------------------------------------------------------

"""Shared float16 output verification for runtime samples."""

import sys
import logging
import os
import numpy as np

# for float16
RELATIVE_TOL = 1e-3
ABSOLUTE_TOL = 1e-5
ERROR_TOL = 1e-3

logging.basicConfig(level=logging.INFO, format='%(message)s', handlers=[logging.StreamHandler()])
logger = logging.getLogger(__name__)


def verify_result(output, golden):
    element_size = np.dtype(np.float16).itemsize
    if os.path.getsize(output) % element_size or os.path.getsize(golden) % element_size:
        logger.error("output and golden must contain complete float16 elements")
        return False
    output = np.fromfile(output, dtype=np.float16).reshape(-1)
    golden = np.fromfile(golden, dtype=np.float16).reshape(-1)
    if golden.size == 0 or output.size != golden.size:
        logger.error("output and golden must have the same nonzero element count")
        return False
    different_element_results = np.isclose(output,
                                           golden,
                                           rtol=RELATIVE_TOL,
                                           atol=ABSOLUTE_TOL,
                                           equal_nan=True)
    different_element_indexes = np.where(different_element_results == False)[0]
    for index, real_index in enumerate(different_element_indexes):
        golden_data = golden[real_index]
        output_data = output[real_index]
        logger.info(
            "data index: %06d, expected: %-.9f, actual: %-.9f, rdiff: %-.6f",
            real_index, golden_data, output_data,
            abs(output_data - golden_data) / golden_data)
        if index == 100:
            break
    error_ratio = float(different_element_indexes.size) / golden.size
    logger.info("error ratio: %.4f, tolerance: %.4f", error_ratio, ERROR_TOL)
    return error_ratio <= ERROR_TOL


def main(args):
    try:
        if not verify_result(args[0], args[1]):
            raise ValueError("[FAILURE] result error")
        logger.info("[SUCCESS] result correct")
        return 0
    except Exception as exc:
        logger.error(exc)
        return 1


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))