diff --git a/algorithm/__init__.py b/algorithm/__init__.py new file mode 100644 index 0000000..ed3608a --- /dev/null +++ b/algorithm/__init__.py @@ -0,0 +1,4 @@ +from .config_reader import config_read_double +from .geometry_utils import strng2, strngellips + +__all__ = ['config_read_double', 'strng2', 'strngellips'] diff --git a/algorithm/analysis_utils.py b/algorithm/analysis_utils.py new file mode 100644 index 0000000..e8e471e --- /dev/null +++ b/algorithm/analysis_utils.py @@ -0,0 +1,391 @@ +import numpy as np + + +def xray2000_ana_m(normvideo, settings, errorin, ovrvwmem): + from curvefit_analysis import ( + analy01, anajack2, ana_curvefit_tube, ana_curvefit_Uponor, + ana_curvefit_cable, ana_curvefit_2l_tube + ) + + conf_data = np.asarray(settings['confData'], dtype=np.float64).copy() + conf20 = conf_data[19] + + xL = np.zeros((1, 4)) + xR = np.zeros((1, 4)) + status = np.zeros((1, 4)) + statusL = np.zeros((1, 4)) + statusR = np.zeros((1, 4)) + attL = np.zeros(2) + attR = np.zeros(2) + errorlevel = np.zeros((2, 1)) + layeruse = np.zeros(5) + IN = np.array([]) + detail = { + 'IN': np.nan, 'nominal': np.nan, + 'left': { + 'pos': {'result': np.nan, 'start': np.nan, + 'limit': {'left': np.nan, 'right': np.nan}}, + 'att': {'outer': np.nan, 'inner': np.nan}, + 'error': np.array([np.nan, np.nan]) + }, + 'att': {'min': np.nan, 'max': np.nan}, + 'contr': {'min': np.nan, 'max': np.nan, 'sign': np.nan}, + } + detail['right'] = {k: (v.copy() if isinstance(v, dict) else v) + for k, v in detail['left'].items()} + + if ((30 <= conf20 <= 50) or conf20 == 53 or + (62000000 <= conf20 < 63000000) or + (151 <= conf20 < 160)): + xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, ovrvwmem, IN = \ + anajack2(normvideo, conf_data, settings, ovrvwmem, errorin) + elif 63000000 <= conf20 < 64000000: + xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, ovrvwmem, IN = \ + anajack2(normvideo, conf_data, settings, ovrvwmem, errorin) + elif 70 <= conf20 <= 90: + xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN = \ + ana_curvefit_tube(normvideo, conf_data, errorin) + elif 101 <= conf20 <= 104: + xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN = \ + ana_curvefit_Uponor(normvideo, conf_data, errorin) + elif 105 <= conf20 <= 110: + xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN = \ + ana_curvefit_Uponor(normvideo, conf_data, errorin) + elif 111 <= conf20 <= 130: + if conf20 == 112: + conf_data[19] = 111 + conf_data[2] = 0 + conf_data[3] = 0 + conf_data[4] = 0 + xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN, detail = \ + ana_curvefit_cable(normvideo, conf_data, errorin, settings) + elif 131 <= conf20 <= 150: + xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, ovrvwmem, IN = \ + ana_curvefit_2l_tube(normvideo, conf_data, errorin, ovrvwmem) + else: + if conf20 == 51: + conf_data[19] = 1 + conf_data[2] = 0 + conf_data[3] = 0 + conf_data[4] = 0 + elif conf20 == 52: + conf_data[19] = 2 + conf_data[2] = 0 + conf_data[3] = 0 + conf_data[4] = 0 + elif conf20 == 60 or conf20 == 62: + conf_data[19] = 1 + conf_data[2] = 0 + conf_data[3] = 0 + conf_data[4] = 0 + elif conf20 == 61 or conf20 == 63: + conf_data[19] = 2 + conf_data[2] = 0 + conf_data[3] = 0 + conf_data[4] = 0 + xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN = \ + analy01(normvideo, conf_data, errorin) + + return xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, ovrvwmem, IN, detail + + +def rotangle(settings, edges, results, status, avgmem): + avw = np.zeros((3, 1)) + avw[1, 0] = 45 + x = np.zeros((3, 4)) + y = np.zeros((3, 4)) + return avw, avgmem, x, y + + +def twist_compensation_sector(dk_x, dk_y, phi, xk, yk, x0_x, y0_y, + b0, d0, r1, r2, maxTwist, orientation): + b = np.array(dk_x).copy() + d = np.array(dk_y).copy() + return b, d + + +def attprofile(IN_x, IN_y, dxZeile, edges, results, avgresults, + attprofsett, avgdata, bRotateXDir, unit, att_avgmem): + avgattcoeff = np.zeros(2) + ringinfovek = np.zeros(10) + return avgattcoeff, ringinfovek, att_avgmem + + +def voiddetect(IN_x, IN_y, dxZeile, edges, results, voiddetectsett, unit, layeruse): + return {} + + +def startx2ana(rawvideo, rawdarkvideo, rawvideoDark_static, rawvideoDark_dynamic, + rawbrightvideo, settings, errsettings, mem, init): + from signal_utils import scan_norm + from validation_utils import chksettings, plausi2000, plausi_layer, chk_tolchksettings + from averaging_utils import avg_mval + from detection_utils import AutoDetect + from geometry_utils import xy_correct, modify_cable_position + from layer_calibration_utils import layer_correct, uponor_alucorrect2 + + settings, err_meas_head = chksettings(settings, errsettings) + + if errsettings is None: + errsettings = np.zeros((2, 1)) + errsettings = np.atleast_2d(errsettings) + if errsettings.shape[0] < 2: + errsettings = np.zeros((2, 1)) + + gap = settings.get('gap', np.array([])) + videoOffs = settings.get('videoOffs', 0) + conf_data = np.asarray(settings['confData'], dtype=np.float64) + + dxZeile = conf_data[91] + video_req_time = conf_data[163] if len(conf_data) > 163 else 0.04 + + normvideo_x, mmPixel_x, errnorm, mem = scan_norm( + rawvideo[0], rawbrightvideo[0], rawvideoDark_static[0], rawvideoDark_dynamic[0], + dxZeile, gap, videoOffs, errsettings, mem, init, video_req_time + ) + normvideo_y, mmPixel_y, errnorm, mem = scan_norm( + rawvideo[1], rawbrightvideo[1], rawvideoDark_static[1], rawvideoDark_dynamic[1], + dxZeile, gap, videoOffs, errsettings, mem, init, video_req_time + ) + + normvideo = {'x': normvideo_x, 'y': normvideo_y} + + settings['geometryData'] = settings.get('geometryData', {}) + settings['geometryData']['x_mmPixel'] = mmPixel_x + settings['geometryData']['y_mmPixel'] = mmPixel_y + + if 'StartX2Ana' not in mem: + mem['StartX2Ana'] = {} + if 'CableType' not in mem['StartX2Ana']: + mem['StartX2Ana']['CableType'] = {} + if 'ovrvwmem' not in mem['StartX2Ana']: + mem['StartX2Ana']['ovrvwmem'] = {} + if 'avgmem' not in mem['StartX2Ana']: + mem['StartX2Ana']['avgmem'] = {} + if 'att_avgmem' not in mem['StartX2Ana']: + mem['StartX2Ana']['att_avgmem'] = {} + if 'avgresults' not in mem['StartX2Ana']: + mem['StartX2Ana']['avgresults'] = None + + AutoDet = np.zeros(4) + AutoDetHVon = conf_data[118] if len(conf_data) > 118 else 0 + + if AutoDetHVon == 0: + if conf_data[19] == 0 and mem['StartX2Ana']['CableType'].get('BitInit', 0) == 0: + mem['StartX2Ana']['CableType']['Number'] = np.zeros(25) + mem['StartX2Ana']['CableType']['Counter'] = 0 + mem['StartX2Ana']['CableType']['Type'] = 0 + mem['StartX2Ana']['CableType']['NOMOSC'] = 0 + mem['StartX2Ana']['CableType']['NOMINS'] = 0 + mem['StartX2Ana']['CableType']['NOMISC'] = 0 + mem['StartX2Ana']['CableType']['BitInit'] = 1 + AutoDet = np.array([0, 0, 0, 0]) + elif conf_data[19] == 0 and mem['StartX2Ana']['CableType'].get('BitInit', 0) == 1: + AutoDet = np.array([ + mem['StartX2Ana']['CableType'].get('Type', 0), + mem['StartX2Ana']['CableType'].get('NOMOSC', 0), + mem['StartX2Ana']['CableType'].get('NOMINS', 0), + mem['StartX2Ana']['CableType'].get('NOMISC', 0), + ]) + elif conf_data[19] != 0 and mem['StartX2Ana']['CableType'].get('BitInit', 0) == 1: + mem['StartX2Ana']['CableType']['BitInit'] = 0 + AutoDet = np.array([ + conf_data[19], + mem['StartX2Ana']['CableType'].get('NOMOSC', 0), + mem['StartX2Ana']['CableType'].get('NOMINS', 0), + mem['StartX2Ana']['CableType'].get('NOMISC', 0), + ]) + elif conf_data[19] != 0 and mem['StartX2Ana']['CableType'].get('BitInit', 0) == 0: + AutoDet = np.array([ + conf_data[19], + mem['StartX2Ana']['CableType'].get('NOMOSC', 0), + mem['StartX2Ana']['CableType'].get('NOMINS', 0), + mem['StartX2Ana']['CableType'].get('NOMISC', 0), + ]) + + if mem['StartX2Ana']['CableType'].get('BitInit', 0) == 1: + conf_data[92] = 1 + settings['confData'] = conf_data + errnorm_in = np.asarray(errnorm).ravel()[:2] + mem['StartX2Ana']['CableType'], errnorm_out = AutoDetect( + normvideo['x'], conf_data, errnorm_in, mem['StartX2Ana']['CableType']) + errnorm_flat = np.asarray(errnorm_out).ravel() + errnorm[0, 0] = float(errnorm_flat[0]) + errnorm[1, 0] = float(errnorm_flat[1]) if len(errnorm_flat) > 1 else 0.0 + conf_data[92] = 0 + settings['confData'] = conf_data + errnorm_in = np.asarray(errnorm).ravel()[:2] + mem['StartX2Ana']['CableType'], errnorm_out = AutoDetect( + normvideo['y'], conf_data, errnorm_in, mem['StartX2Ana']['CableType']) + errnorm_flat = np.asarray(errnorm_out).ravel() + errnorm[0, 0] = float(errnorm_flat[0]) + errnorm[1, 0] = float(errnorm_flat[1]) if len(errnorm_flat) > 1 else 0.0 + + if errnorm[0, 0] == 0: + errnorm[0, 0] = 202 + + if mem['StartX2Ana']['CableType'].get('Type', 0) != 0: + settings['CableType'] = mem['StartX2Ana']['CableType']['Type'] + settings['confData'][19] = mem['StartX2Ana']['CableType']['Type'] + AutoDet = np.array([ + mem['StartX2Ana']['CableType']['Type'], + mem['StartX2Ana']['CableType'].get('NOMOSC', 0), + mem['StartX2Ana']['CableType'].get('NOMINS', 0), + mem['StartX2Ana']['CableType'].get('NOMISC', 0), + ]) + mem['StartX2Ana']['CableType']['BitInit'] = 0 + + conf_data[92] = 1 + settings['confData'] = conf_data + (edgesL_x, edgesR_x, status_x, statusL_x, statusR_x, attL_x, attR_x, err_x, + layeruse, mem['StartX2Ana']['ovrvwmem'], IN_x) = xray2000_ana_m( + normvideo['x'], settings, errnorm, mem['StartX2Ana']['ovrvwmem'])[:11] + + conf_data[92] = 0 + settings['confData'] = conf_data + (edgesL_y, edgesR_y, status_y, statusL_y, statusR_y, attL_y, attR_y, err_y, + layeruse, mem['StartX2Ana']['ovrvwmem'], IN_y) = xray2000_ana_m( + normvideo['y'], settings, errnorm, mem['StartX2Ana']['ovrvwmem'])[:11] + + edges = { + 'left': {'x': edgesL_x + settings['geometryData']['x_mmPixel'], + 'y': edgesL_y + settings['geometryData']['y_mmPixel']}, + 'right': {'x': edgesR_x + settings['geometryData']['x_mmPixel'], + 'y': edgesR_y + settings['geometryData']['y_mmPixel']}, + } + + geom_x = settings['geometryData'].get('x', {}) + geom_y = settings['geometryData'].get('y', {}) + + settings['correctionData'] = settings.get('correctionData', {}) + settings['correctionData']['delta_xk'] = 0 + settings['correctionData']['delta_yk'] = 0 + settings['correctionData']['x'] = settings['correctionData'].get('x', np.zeros(32)) + settings['correctionData']['y'] = settings['correctionData'].get('y', np.zeros(32)) + + (dmOut, oscL, oscR, isoL, isoR, iscL, iscR, coreDm, wthL, wthR, xk_res, yk_res) = xy_correct( + edges['left']['x'], edges['right']['x'], edges['left']['y'], edges['right']['y'], + geom_x.get('x0', 600), geom_x.get('y0', 600), + geom_x.get('xCCD', 0), geom_x.get('yCCD', 0), + geom_y.get('x0', 600), geom_y.get('y0', 600), + geom_y.get('xCCD', 0), geom_y.get('yCCD', 0), + geom_x.get('gamma', 90), geom_y.get('gamma', 90), + status_x, status_y, statusL_x, statusR_x, statusL_y, statusR_y, + settings['correctionData']['delta_xk'], settings['correctionData']['delta_yk'], + settings['correctionData']['x'], settings['correctionData']['y'], 1, layeruse + ) + + results = { + 'dmOut': dmOut, + 'left': {'osc': oscL, 'iso': isoL, 'isc': iscL, 'wth': wthL}, + 'right': {'osc': oscR, 'iso': isoR, 'isc': iscR, 'wth': wthR}, + 'coreDm': coreDm, + 'x': xk_res, + 'y': yk_res, + 'vw': np.zeros((3, 1)), + } + results['vw'][1, 0] = 45 + + cableType = conf_data[19] + settings['cableData'] = settings.get('cableData', {}) + + if cableType in (51, 52, 53): + if settings['cableData'].get('baseAngle', 0) > 0: + orientation = settings['cableData'].get('orientation', 0) + if orientation in (1, 3): + settings['cableData']['height'] = dmOut[0, 0] * (dmOut[1, 0] == 0) + else: + settings['cableData']['height'] = dmOut[0, 1] * (dmOut[1, 1] == 0) + + delta_xk, delta_yk = modify_cable_position( + settings['cableData']['baseAngle'], + orientation, + settings['cableData']['height']) + settings['correctionData']['delta_xk'] = delta_xk + settings['correctionData']['delta_yk'] = delta_yk + + (dmOut, oscL, oscR, isoL, isoR, iscL, iscR, coreDm, wthL, wthR, xk_res, yk_res) = xy_correct( + edges['left']['x'], edges['right']['x'], edges['left']['y'], edges['right']['y'], + geom_x.get('x0', 600), geom_x.get('y0', 600), + geom_x.get('xCCD', 0), geom_x.get('yCCD', 0), + geom_y.get('x0', 600), geom_y.get('y0', 600), + geom_y.get('xCCD', 0), geom_y.get('yCCD', 0), + geom_x.get('gamma', 90), geom_y.get('gamma', 90), + status_x, status_y, statusL_x, statusR_x, statusL_y, statusR_y, + settings['correctionData']['delta_xk'], settings['correctionData']['delta_yk'], + settings['correctionData']['x'], settings['correctionData']['y'], 1, layeruse + ) + results['dmOut'] = dmOut + results['left']['osc'] = oscL + results['right']['osc'] = oscR + results['left']['iso'] = isoL + results['right']['iso'] = isoR + results['left']['isc'] = iscL + results['right']['isc'] = iscR + results['coreDm'] = coreDm + results['left']['wth'] = wthL + results['right']['wth'] = wthR + results['x'] = xk_res + results['y'] = yk_res + + defaultval = np.array([[0, 0], [45, 45], [0, 0]]) + results['coreDm'] = defaultval.copy() + results['left']['iso'] = defaultval.copy() + results['left']['isc'] = defaultval.copy() + results['right']['iso'] = defaultval.copy() + results['right']['isc'] = defaultval.copy() + if cableType in (51, 52): + results['dmOut'] = defaultval.copy() + + calib_struct = settings.get('calib_struct', {}) + _int = calib_struct.get('int') + if _int is not None and (not isinstance(_int, np.ndarray) or _int.size > 0): + results = layer_correct(results, calib_struct['int'], layeruse, cableType) + else: + defaultval = np.array([[0, 0], [191, 191], [0, 0]]) + results['dmOut'] = defaultval.copy() + results['coreDm'] = defaultval.copy() + results['left']['wth'] = defaultval.copy() + results['left']['osc'] = defaultval.copy() + results['left']['iso'] = defaultval.copy() + results['left']['isc'] = defaultval.copy() + results['right']['wth'] = defaultval.copy() + results['right']['osc'] = defaultval.copy() + results['right']['iso'] = defaultval.copy() + results['right']['isc'] = defaultval.copy() + + results = uponor_alucorrect2(results, cableType) + + _ext = calib_struct.get('ext') + if _ext is not None and (not isinstance(_ext, np.ndarray) or _ext.size > 0): + results = layer_correct(results, calib_struct['ext'], layeruse, cableType) + + tolchkactive = chk_tolchksettings(settings.get('tolchk', {})) + if not tolchkactive: + results = plausi2000(results, mem['StartX2Ana'].get('avgresults'), settings) + + avgresults, mem['StartX2Ana']['avgmem'] = avg_mval( + results, settings.get('avgData', {}), mem['StartX2Ana']['avgmem']) + + if cableType == 53: + avgresults['coreDm'][0, 0:2] = 0 + avgresults['coreDm'][1, 0:2] = 45 + avgresults['coreDm'][2, 0:2] = 0 + + avgresults = plausi_layer(avgresults, settings) + mem['StartX2Ana']['avgresults'] = avgresults + + attprofsett = settings.get('attprofsett', {}) + avgdata = settings.get('avgData', {}) + bRotateXDir = settings.get('bRotateXDir', 0) + unit = settings.get('unit', 0) + + AttCoeff, AttCoeffSt, mem['StartX2Ana']['att_avgmem'] = attprofile( + IN_x, IN_y, conf_data[89], edges, results, avgresults, + attprofsett, avgdata, bRotateXDir, unit, mem['StartX2Ana']['att_avgmem']) + + voiddetectsett = settings.get('voiddetectsett', {}) + Void = voiddetect(IN_x, IN_y, conf_data[89], edges, results, voiddetectsett, unit, layeruse) + + return avgresults, results, edges, status_x, status_y, attL_x, attR_x, attL_y, attR_y, \ + errnorm, AutoDet, mem, IN_x, IN_y, AttCoeff, AttCoeffSt, Void diff --git a/algorithm/averaging_utils.py b/algorithm/averaging_utils.py new file mode 100644 index 0000000..853c9c4 --- /dev/null +++ b/algorithm/averaging_utils.py @@ -0,0 +1,642 @@ +import numpy as np +import copy +try: + from .filtering_utils import buttmat +except ImportError: + from filtering_utils import buttmat + + +def digfilt(B, A, Bst, Ast, x, xstat, avgmem, init): + y = np.array([]) + ystat = 0 + + if x.ndim > 1 and min(x.shape) > 1: + raise ValueError('digfilt.m: min(size(x)) > 1!') + else: + x = x.ravel() + + if len(A) < 3 or len(B) < 3: + raise ValueError('digfilt.m: (length(A) < 3) || (length(B) < 3)') + + if init.get('st', False) or avgmem is None or not avgmem: + old_startup = avgmem.get('startup_percent') if isinstance(avgmem, dict) else None + old_loop = avgmem.get('loop') if isinstance(avgmem, dict) else None + avgmem = {} + if old_startup is not None: + avgmem['startup_percent'] = old_startup + if old_loop is not None: + avgmem['loop'] = old_loop + avgmem['xold'] = np.array([]) + avgmem['yold'] = np.array([]) + avgmem['xstold'] = np.array([]) + avgmem['ystold'] = np.array([]) + avgmem['true_st'] = np.array([]) + avgmem['oldsinglestatus'] = np.array([]) + + if xstat.ndim > 1 and min(xstat.shape) > 1: + raise ValueError('digfilt.m: min(size(xstat)) > 1') + else: + xstat = xstat.ravel() + ystat = np.zeros(len(xstat)) + + if len(x) == 0: + xstat = np.zeros(len(xstat)) + + memempty = (len(avgmem.get('xold', [])) == 0 or len(avgmem.get('xstold', [])) == 0 or len(avgmem.get('true_st', [])) == 0) + mememptyst = (len(avgmem.get('xold', [])) == 0 or len(avgmem.get('xstold', [])) == 0) + + if not (memempty and len(x) == 0): + rowx = len(x) if x.ndim == 1 else x.shape[0] + + init_Filt = (init.get('st', False) or memempty or + (len(x) > 0 and rowx != len(avgmem.get('yold', [])))) + + init_Filtst = (init.get('st', False) or mememptyst or + (len(x) > 0 and rowx != len(avgmem.get('yold', [])))) + + if init_Filt: + if init.get('typ', 1) == 2: + avgmem['xold'] = init.get('val', 0) * np.ones((rowx, 2)) + avgmem['yold'] = init.get('val', 0) * np.ones((rowx, 2)) + else: + avgmem['xold'] = np.zeros((rowx, 2)) + avgmem['yold'] = np.zeros((rowx, 2)) + avgmem['xold'][:, 0] = x[0] * xstat[0] * np.ones(rowx) + avgmem['yold'][:, 0] = x[0] * xstat[0] * np.ones(rowx) + avgmem['xold'][:, 1] = avgmem['xold'][:, 0] + avgmem['yold'][:, 1] = avgmem['yold'][:, 0] + if xstat[0]: + avgmem['true_st'] = np.array([1]) + else: + avgmem['true_st'] = np.array([]) + + if not xstat[0]: + x = avgmem['yold'][:, 0].copy() + + y = B[0] * x + B[1] * avgmem['xold'][:, 0] + B[2] * avgmem['xold'][:, 1] - A[1] * avgmem['yold'][:, 0] - A[2] * avgmem['yold'][:, 1] + + avgmem['xold'] = np.column_stack([x, avgmem['xold'][:, 0]]) + avgmem['yold'] = np.column_stack([y, avgmem['yold'][:, 0]]) + + if init_Filtst: + stval = init.get('stval', [0, 1]) + if len(stval) == 2 and len(xstat) == 2: + avgmem['xstold'] = np.zeros((len(xstat), 2)) + avgmem['ystold'] = np.zeros((len(xstat), 2)) + avgmem['xstold'][0, :] = xstat[0] * stval[0] * np.ones(2) + avgmem['ystold'][0, :] = xstat[0] * stval[0] * np.ones(2) + avgmem['xstold'][1, :] = stval[1] * np.ones(2) + avgmem['ystold'][1, :] = stval[1] * np.ones(2) + else: + avgmem['xstold'] = xstat[0] * stval[0] * np.ones((len(xstat), 2)) + avgmem['ystold'] = xstat[0] * stval[0] * np.ones((len(xstat), 2)) + + ystat = Bst[0] * xstat + Bst[1] * avgmem['xstold'][:, 0] + Bst[2] * avgmem['xstold'][:, 1] - Ast[1] * avgmem['ystold'][:, 0] - Ast[2] * avgmem['ystold'][:, 1] + + avgmem['xstold'] = np.column_stack([xstat, avgmem['xstold'][:, 0]]) + avgmem['ystold'] = np.column_stack([ystat, avgmem['ystold'][:, 0]]) + + return y, ystat, avgmem + + +def fpara(Status, initin, avgn, avgmem, xray8k): + errorl = np.zeros(2) + + if avgmem is None or not avgmem or initin: + old_startup = avgmem.get('startup_percent') if isinstance(avgmem, dict) else None + avgmem = {} + if old_startup is not None: + avgmem['startup_percent'] = old_startup + avgmem['loop'] = np.array([]) + avgmem['xold'] = np.array([]) + avgmem['yold'] = np.array([]) + avgmem['xstold'] = np.array([]) + avgmem['ystold'] = np.array([]) + avgmem['true_st'] = np.array([]) + avgmem['oldsinglestatus'] = np.array([]) + + if initin or len(avgmem.get('loop', [])) == 0: + avgmem['loop'] = np.array([1]) + elif Status: + if avgmem['loop'][0] != 65535: + avgmem['loop'][0] = avgmem['loop'][0] + 1 + + if avgmem['loop'][0] < avgn: + fgn = 1 / avgmem['loop'][0] + else: + fgn = 1 / avgn + + B, A, errorl[1] = buttmat(fgn) + filterr = errorl[1] > 0 + + if xray8k: + Bst = B.copy() + Ast = A.copy() + else: + Bst, Ast, _ = buttmat(1 / avgn) + + return B, A, Bst, Ast, avgmem, filterr + + +def statuscheck2(avgvalue, avgstatus, singlestatus, insens, + filterr, startup_percent, warninginsens, setupfailure, avgmem): + StWait = 249 + StDefault = 255 + StFilterr = 70 + avgoutvalue = np.zeros_like(avgvalue) + avgoutstatus = np.zeros(3) + avgoutstatus[2] = (1 - avgstatus[0]) * 100 + if avgoutstatus[2] < 0: + avgoutstatus[2] = 0 + if avgoutstatus[2] > 100: + avgoutstatus[2] = 100 + + if warninginsens is None or (isinstance(warninginsens, (list, np.ndarray)) and len(warninginsens) == 0): + warninginsens = insens + + if avgmem is None or len(avgmem.get('oldsinglestatus', [])) == 0: + avgmem['oldsinglestatus'] = np.array(singlestatus, dtype=float) + + if singlestatus[0]: + avgmem['oldsinglestatus'][0] = singlestatus[0] + if len(singlestatus) == 2 and singlestatus[1]: + avgmem['oldsinglestatus'][1] = singlestatus[1] + + if avgstatus[0] > (1 - insens / 100): + avgoutvalue = avgvalue.copy() + avgoutstatus[0] = 0 + else: + avgoutvalue = avgvalue.copy() + if setupfailure: + avgoutstatus[0] = avgmem['oldsinglestatus'][0] + elif startup_percent < 100: + avgoutstatus[0] = StWait + else: + if avgmem['oldsinglestatus'][0]: + avgoutstatus[0] = avgmem['oldsinglestatus'][0] + else: + avgoutstatus[0] = StDefault + + avgoutstatus[1] = 0 + length2 = (len(avgstatus) == 2 and len(avgmem.get('oldsinglestatus', [])) == 2) + + if startup_percent > 98: + if avgstatus[0] < (1 - warninginsens / 100) and not avgoutstatus[0]: + avgoutstatus[1] = avgmem['oldsinglestatus'][0] + elif length2 and avgstatus[1] < (1 - warninginsens / 100) and avgmem['oldsinglestatus'][1]: + avgoutstatus[1] = -avgmem['oldsinglestatus'][1] + elif filterr: + avgoutstatus[1] = -StFilterr + + return avgoutvalue, avgoutstatus, avgmem + + +def _avg_result_pair(result_a, result_b): + result_a = np.asarray(result_a, dtype=np.float64).ravel() + result_b = np.asarray(result_b, dtype=np.float64).ravel() + out = np.ones(3) * 255 + if len(result_a) >= 3 and len(result_b) >= 3: + if not result_a[1] and not result_b[1]: + out[0] = (result_a[0] + result_b[0]) / 2 + out[1] = 0 + out[2] = result_a[2] + elif not result_a[1] and result_b[1]: + out[0] = result_a[0] + out[1] = 0 + out[2] = result_a[2] + elif result_a[1] and not result_b[1]: + out[0] = result_b[0] + out[1] = 0 + out[2] = result_b[2] + else: + out[0] = 0 + out[1] = result_a[1] + out[2] = result_a[2] + return out + + +def avg_ab(tmp, conf): + dmOut = _avg_result_pair(tmp['results']['dmOut']['a'], tmp['results']['dmOut']['b']) + + oscL = _avg_result_pair(tmp['results']['left']['osc']['a'], tmp['results']['left']['osc']['b']) + oscR = _avg_result_pair(tmp['results']['right']['osc']['a'], tmp['results']['right']['osc']['b']) + + isoL = _avg_result_pair(tmp['results']['left']['iso']['a'], tmp['results']['left']['iso']['b']) + isoR = _avg_result_pair(tmp['results']['right']['iso']['a'], tmp['results']['right']['iso']['b']) + + iscL = _avg_result_pair(tmp['results']['left']['isc']['a'], tmp['results']['left']['isc']['b']) + iscR = _avg_result_pair(tmp['results']['right']['isc']['a'], tmp['results']['right']['isc']['b']) + + coreDm = _avg_result_pair(tmp['results']['coreDm']['a'], tmp['results']['coreDm']['b']) + + wthL = _avg_result_pair(tmp['results']['left']['wth']['a'], tmp['results']['left']['wth']['b']) + wthR = _avg_result_pair(tmp['results']['right']['wth']['a'], tmp['results']['right']['wth']['b']) + + axis = {'a': tmp['results']['a'], 'b': tmp['results']['b']} + + return dmOut, oscL, oscR, isoL, isoR, iscL, iscR, coreDm, wthL, wthR, axis + + +def avg_mval_sub(in_dict, skip_startup=False): + if in_dict.get('status') is None or len(in_dict.get('status', [])) == 0: + results_arr = np.atleast_1d(np.asarray(in_dict['results'], dtype=float)) + value = np.array([results_arr[0]]) + status = results_arr[1:] if len(results_arr) > 1 else np.array([0.0]) + else: + value = np.atleast_1d(np.asarray(in_dict['results'], dtype=float)).ravel() + status = in_dict['status'] + + status = np.atleast_1d(np.asarray(status, dtype=float)) + setupfailure = ((status[0] >= 180 and status[0] <= 220) or (status[0] == 45)) + + avgmem = in_dict.get('avgmem', None) + if in_dict.get('init', {}).get('st', False) or avgmem is None or not avgmem: + avgmem = {} + if skip_startup: + avgmem['startup_percent'] = 100 + else: + avgmem['startup_percent'] = 0 + avgmem['loop'] = np.array([]) + avgmem['xold'] = np.array([]) + avgmem['yold'] = np.array([]) + avgmem['xstold'] = np.array([]) + avgmem['ystold'] = np.array([]) + avgmem['true_st'] = np.array([]) + avgmem['oldsinglestatus'] = np.array([]) + + if skip_startup: + avgmem['startup_percent'] = 100 + + if avgmem.get('startup_percent', 0) < 100 and not setupfailure: + avgmem['startup_percent'] = avgmem.get('startup_percent', 0) + 100 * in_dict['video_req_time'] / in_dict['meantime'] + + statusd = np.zeros(2) + statusd[0] = (status[0] == 0) + if len(status) > 1: + statusd[1] = (status[1] == 0) + + B, A, Bst, Ast, avgmem, filterr = fpara( + statusd[0], in_dict['init']['st'], + (in_dict['meantime'] / in_dict['video_req_time']), + avgmem, in_dict['xray8k'] + ) + + y, ystat, avgmem = digfilt(B, A, Bst, Ast, value, statusd, avgmem, in_dict['init']) + + avgoutvalue, avgoutstatus, avgmem = statuscheck2( + y, ystat, status, in_dict['insens'], filterr, + avgmem.get('startup_percent', 0), in_dict.get('warninsens', in_dict['insens']), + setupfailure, avgmem + ) + + if in_dict.get('status') is None or len(in_dict.get('status', [])) == 0: + avgresults = np.concatenate([np.atleast_1d(avgoutvalue).ravel(), avgoutstatus.ravel()]) + avgstatus_out = np.array([]) + else: + avgresults = avgoutvalue + avgstatus_out = avgoutstatus + + return avgresults, avgmem, avgstatus_out + + +def avg_mval(results, avgsettings, avgmem, eval_axis=2, cableType=0, err_meas_head=None): + if err_meas_head is None: + err_meas_head = np.zeros(2) + + BOTH = 2 + EVALX = 1 + EVALY = 0 + + if avgsettings.get('init', 0) or avgmem is None or len(avgmem) == 0: + avgmem = {} + avgmem['dm'] = {'x': None, 'y': None} + for layer in ['osc', 'isc', 'iso', 'wth']: + avgmem['left'] = avgmem.get('left', {}) + avgmem['right'] = avgmem.get('right', {}) + avgmem['left'][layer] = {'x': None, 'y': None} + avgmem['right'][layer] = {'x': None, 'y': None} + avgmem['eightPT'] = copy.deepcopy(avgmem) + + avgresults = {} + avgresults['dmOut'] = np.zeros((4, 2)) + avgresults['coreDm'] = np.zeros((4, 2)) + for layer in ['osc', 'isc', 'iso', 'wth']: + avgresults['left'] = avgresults.get('left', {}) + avgresults['right'] = avgresults.get('right', {}) + avgresults['left'][layer] = np.zeros((4, 2)) + avgresults['right'][layer] = np.zeros((4, 2)) + avgresults['eightPT'] = copy.deepcopy(avgresults) + + StWait = 249 + + in_dict = {} + in_dict['init'] = { + 'val': 0, + 'stval': np.array([0, 1]), + 'st': avgsettings.get('init', 0), + 'typ': 1 + } + in_dict['status'] = None + in_dict['err_meas_head'] = err_meas_head + in_dict['xray8k'] = avgsettings.get('xray8k', 0) + in_dict['meantime'] = avgsettings.get('mean_time_dm', 1.0) + in_dict['video_req_time'] = avgsettings.get('video_req_time', 0.04) + in_dict['insens'] = avgsettings.get('dia_insens', 5.0) + in_dict['warninsens'] = avgsettings.get('dia_warninsens', None) + + if eval_axis == EVALX or eval_axis == BOTH: + in_dict['results'] = results['dmOut'][:, 0] + in_dict['avgmem'] = avgmem.get('dm', {}).get('x') + res, avgmem_dm_x, _ = avg_mval_sub(in_dict) + avgresults['dmOut'][:, 0] = res[:4] if len(res) >= 4 else res + avgmem['dm']['x'] = avgmem_dm_x + + if eval_axis == EVALY or eval_axis == BOTH: + in_dict['results'] = results['dmOut'][:, 1] + in_dict['avgmem'] = avgmem.get('dm', {}).get('y') + res, avgmem_dm_y, _ = avg_mval_sub(in_dict) + avgresults['dmOut'][:, 1] = res[:4] if len(res) >= 4 else res + avgmem['dm']['y'] = avgmem_dm_y + + in_dict['meantime'] = avgsettings.get('mean_time_lay', 1.0) + in_dict['insens'] = avgsettings.get('lay_insens', 5.0) + in_dict['warninsens'] = avgsettings.get('lay_warninsens', None) + + for layer in ['osc', 'isc', 'iso']: + if eval_axis == EVALX or eval_axis == BOTH: + in_dict['results'] = results['left'][layer][:, 0] + in_dict['avgmem'] = avgmem['left'][layer].get('x') + res, new_mem, _ = avg_mval_sub(in_dict) + avgresults['left'][layer][:, 0] = res[:4] if len(res) >= 4 else res + avgmem['left'][layer]['x'] = new_mem + + in_dict['results'] = results['right'][layer][:, 0] + in_dict['avgmem'] = avgmem['right'][layer].get('x') + res, new_mem, _ = avg_mval_sub(in_dict) + avgresults['right'][layer][:, 0] = res[:4] if len(res) >= 4 else res + avgmem['right'][layer]['x'] = new_mem + + if eval_axis == EVALY or eval_axis == BOTH: + in_dict['results'] = results['left'][layer][:, 1] + in_dict['avgmem'] = avgmem['left'][layer].get('y') + res, new_mem, _ = avg_mval_sub(in_dict) + avgresults['left'][layer][:, 1] = res[:4] if len(res) >= 4 else res + avgmem['left'][layer]['y'] = new_mem + + in_dict['results'] = results['right'][layer][:, 1] + in_dict['avgmem'] = avgmem['right'][layer].get('y') + res, new_mem, _ = avg_mval_sub(in_dict) + avgresults['right'][layer][:, 1] = res[:4] if len(res) >= 4 else res + avgmem['right'][layer]['y'] = new_mem + + in_dict['meantime'] = avgsettings.get('mean_time_dm', 1.0) + in_dict['insens'] = avgsettings.get('dia_insens', 5.0) + in_dict['warninsens'] = avgsettings.get('dia_warninsens', None) + + for side in ['left', 'right']: + if eval_axis == EVALX or eval_axis == BOTH: + in_dict['results'] = results[side]['wth'][:, 0] + in_dict['avgmem'] = avgmem[side]['wth'].get('x') + res, new_mem, _ = avg_mval_sub(in_dict) + avgresults[side]['wth'][:, 0] = res[:4] if len(res) >= 4 else res + avgmem[side]['wth']['x'] = new_mem + + if eval_axis == EVALY or eval_axis == BOTH: + in_dict['results'] = results[side]['wth'][:, 1] + in_dict['avgmem'] = avgmem[side]['wth'].get('y') + res, new_mem, _ = avg_mval_sub(in_dict) + avgresults[side]['wth'][:, 1] = res[:4] if len(res) >= 4 else res + avgmem[side]['wth']['y'] = new_mem + + avgresults['coreDm'] = np.zeros((4, 2)) + + if (eval_axis == EVALX or eval_axis == BOTH) and cableType not in [62, 63]: + measvek = np.array([avgresults['dmOut'][0, 0], avgresults['left']['wth'][0, 0], avgresults['right']['wth'][0, 0]]) + errvek = np.array([avgresults['dmOut'][1, 0], avgresults['left']['wth'][1, 0], avgresults['right']['wth'][1, 0]]) + warnvek = np.array([avgresults['dmOut'][2, 0], avgresults['left']['wth'][2, 0], avgresults['right']['wth'][2, 0]]) + + core_wait = np.where(errvek == StWait)[0] + core_err = np.where(errvek != 0)[0] + core_warn = np.where(warnvek != 0)[0] + + if len(core_err) == 0: + avgresults['coreDm'][0, 0] = avgresults['dmOut'][0, 0] - avgresults['left']['wth'][0, 0] - avgresults['right']['wth'][0, 0] + avgresults['coreDm'][1, 0] = 0 + elif len(core_wait) > 0: + avgresults['coreDm'][0, 0] = measvek[core_wait[0]] + avgresults['coreDm'][1, 0] = errvek[core_wait[0]] + else: + avgresults['coreDm'][0, 0] = 0 + avgresults['coreDm'][1, 0] = errvek[core_err[0]] + + if len(core_warn) == 0: + avgresults['coreDm'][2, 0] = 0 + else: + avgresults['coreDm'][2, 0] = warnvek[core_warn[0]] + + avgresults['coreDm'][3, 0] = max([avgresults['dmOut'][3, 0], avgresults['left']['wth'][3, 0], avgresults['right']['wth'][3, 0]]) + else: + avgresults['coreDm'][0:2, 0] = results['coreDm'][0:2, 0] + + if (eval_axis == EVALY or eval_axis == BOTH) and cableType not in [62, 63]: + measvek = np.array([avgresults['dmOut'][0, 1], avgresults['left']['wth'][0, 1], avgresults['right']['wth'][0, 1]]) + errvek = np.array([avgresults['dmOut'][1, 1], avgresults['left']['wth'][1, 1], avgresults['right']['wth'][1, 1]]) + warnvek = np.array([avgresults['dmOut'][2, 1], avgresults['left']['wth'][2, 1], avgresults['right']['wth'][2, 1]]) + + core_wait = np.where(errvek == StWait)[0] + core_err = np.where(errvek != 0)[0] + core_warn = np.where(warnvek != 0)[0] + + if len(core_err) == 0: + avgresults['coreDm'][0, 1] = avgresults['dmOut'][0, 1] - avgresults['left']['wth'][0, 1] - avgresults['right']['wth'][0, 1] + avgresults['coreDm'][1, 1] = 0 + elif len(core_wait) > 0: + avgresults['coreDm'][0, 1] = measvek[core_wait[0]] + avgresults['coreDm'][1, 1] = errvek[core_wait[0]] + else: + avgresults['coreDm'][0, 1] = 0 + avgresults['coreDm'][1, 1] = errvek[core_err[0]] + + if len(core_warn) == 0: + avgresults['coreDm'][2, 1] = 0 + else: + avgresults['coreDm'][2, 1] = warnvek[core_warn[0]] + + avgresults['coreDm'][3, 1] = max([avgresults['dmOut'][3, 1], avgresults['left']['wth'][3, 1], avgresults['right']['wth'][3, 1]]) + else: + avgresults['coreDm'][0:2, 1] = results['coreDm'][0:2, 1] + + return avgresults, avgmem + + +def avg_mval_8pt(results, avgsettings, avgmem, eval_axis=2, cableType=0, err_meas_head=None): + if err_meas_head is None: + err_meas_head = np.zeros(2) + + avgsettings = dict(avgsettings) + avgsettings['mean_time_dm'] = avgsettings.get('mean_time_lay', 1.0) + avgsettings['dia_insens'] = avgsettings.get('lay_insens', 5.0) + avgsettings['dia_warninsens'] = avgsettings.get('lay_warninsens', None) + + BOTH = 2 + EVALX = 1 + EVALY = 0 + + if avgsettings.get('init', 0) or avgmem is None or len(avgmem) == 0: + avgmem = {} + avgmem['dm'] = {'x': None, 'y': None} + for layer in ['osc', 'isc', 'iso', 'wth']: + avgmem['left'] = avgmem.get('left', {}) + avgmem['right'] = avgmem.get('right', {}) + avgmem['left'][layer] = {'x': None, 'y': None} + avgmem['right'][layer] = {'x': None, 'y': None} + + avgresults = {} + avgresults['dmOut'] = np.zeros((4, 2)) + avgresults['coreDm'] = np.zeros((4, 2)) + for layer in ['osc', 'isc', 'iso', 'wth']: + avgresults['left'] = avgresults.get('left', {}) + avgresults['right'] = avgresults.get('right', {}) + avgresults['left'][layer] = np.zeros((4, 2)) + avgresults['right'][layer] = np.zeros((4, 2)) + + StWait = 249 + + in_dict = {} + in_dict['init'] = { + 'val': 0, + 'stval': np.array([0, 1]), + 'st': avgsettings.get('init', 0), + 'typ': 1 + } + in_dict['status'] = None + in_dict['err_meas_head'] = err_meas_head + in_dict['xray8k'] = avgsettings.get('xray8k', 0) + in_dict['meantime'] = avgsettings.get('mean_time_dm', 1.0) + in_dict['video_req_time'] = avgsettings.get('video_req_time', 0.04) + in_dict['insens'] = avgsettings.get('dia_insens', 5.0) + in_dict['warninsens'] = avgsettings.get('dia_warninsens', None) + + if eval_axis == EVALX or eval_axis == BOTH: + in_dict['results'] = results['dmOut'][:, 0] + in_dict['avgmem'] = avgmem.get('dm', {}).get('x') + res, avgmem_dm_x, _ = avg_mval_sub(in_dict, skip_startup=True) + avgresults['dmOut'][:, 0] = res[:4] if len(res) >= 4 else res + avgmem['dm']['x'] = avgmem_dm_x + + if eval_axis == EVALY or eval_axis == BOTH: + in_dict['results'] = results['dmOut'][:, 1] + in_dict['avgmem'] = avgmem.get('dm', {}).get('y') + res, avgmem_dm_y, _ = avg_mval_sub(in_dict, skip_startup=True) + avgresults['dmOut'][:, 1] = res[:4] if len(res) >= 4 else res + avgmem['dm']['y'] = avgmem_dm_y + + in_dict['meantime'] = avgsettings.get('mean_time_lay', 1.0) + in_dict['insens'] = avgsettings.get('lay_insens', 5.0) + in_dict['warninsens'] = avgsettings.get('lay_warninsens', None) + + for layer in ['osc', 'isc', 'iso']: + if eval_axis == EVALX or eval_axis == BOTH: + in_dict['results'] = results['left'][layer][:, 0] + in_dict['avgmem'] = avgmem['left'][layer].get('x') + res, new_mem, _ = avg_mval_sub(in_dict, skip_startup=True) + avgresults['left'][layer][:, 0] = res[:4] if len(res) >= 4 else res + avgmem['left'][layer]['x'] = new_mem + + in_dict['results'] = results['right'][layer][:, 0] + in_dict['avgmem'] = avgmem['right'][layer].get('x') + res, new_mem, _ = avg_mval_sub(in_dict, skip_startup=True) + avgresults['right'][layer][:, 0] = res[:4] if len(res) >= 4 else res + avgmem['right'][layer]['x'] = new_mem + + if eval_axis == EVALY or eval_axis == BOTH: + in_dict['results'] = results['left'][layer][:, 1] + in_dict['avgmem'] = avgmem['left'][layer].get('y') + res, new_mem, _ = avg_mval_sub(in_dict, skip_startup=True) + avgresults['left'][layer][:, 1] = res[:4] if len(res) >= 4 else res + avgmem['left'][layer]['y'] = new_mem + + in_dict['results'] = results['right'][layer][:, 1] + in_dict['avgmem'] = avgmem['right'][layer].get('y') + res, new_mem, _ = avg_mval_sub(in_dict, skip_startup=True) + avgresults['right'][layer][:, 1] = res[:4] if len(res) >= 4 else res + avgmem['right'][layer]['y'] = new_mem + + in_dict['meantime'] = avgsettings.get('mean_time_dm', 1.0) + in_dict['insens'] = avgsettings.get('dia_insens', 5.0) + in_dict['warninsens'] = avgsettings.get('dia_warninsens', None) + + for side in ['left', 'right']: + if eval_axis == EVALX or eval_axis == BOTH: + in_dict['results'] = results[side]['wth'][:, 0] + in_dict['avgmem'] = avgmem[side]['wth'].get('x') + res, new_mem, _ = avg_mval_sub(in_dict, skip_startup=True) + avgresults[side]['wth'][:, 0] = res[:4] if len(res) >= 4 else res + avgmem[side]['wth']['x'] = new_mem + + if eval_axis == EVALY or eval_axis == BOTH: + in_dict['results'] = results[side]['wth'][:, 1] + in_dict['avgmem'] = avgmem[side]['wth'].get('y') + res, new_mem, _ = avg_mval_sub(in_dict, skip_startup=True) + avgresults[side]['wth'][:, 1] = res[:4] if len(res) >= 4 else res + avgmem[side]['wth']['y'] = new_mem + + avgresults['coreDm'] = np.zeros((4, 2)) + + if (eval_axis == EVALX or eval_axis == BOTH) and cableType not in [62, 63]: + measvek = np.array([avgresults['dmOut'][0, 0], avgresults['left']['wth'][0, 0], avgresults['right']['wth'][0, 0]]) + errvek = np.array([avgresults['dmOut'][1, 0], avgresults['left']['wth'][1, 0], avgresults['right']['wth'][1, 0]]) + warnvek = np.array([avgresults['dmOut'][2, 0], avgresults['left']['wth'][2, 0], avgresults['right']['wth'][2, 0]]) + + core_wait = np.where(errvek == StWait)[0] + core_err = np.where(errvek != 0)[0] + core_warn = np.where(warnvek != 0)[0] + + if len(core_err) == 0: + avgresults['coreDm'][0, 0] = avgresults['dmOut'][0, 0] - avgresults['left']['wth'][0, 0] - avgresults['right']['wth'][0, 0] + avgresults['coreDm'][1, 0] = 0 + elif len(core_wait) > 0: + avgresults['coreDm'][0, 0] = measvek[core_wait[0]] + avgresults['coreDm'][1, 0] = errvek[core_wait[0]] + else: + avgresults['coreDm'][0, 0] = 0 + avgresults['coreDm'][1, 0] = errvek[core_err[0]] + + if len(core_warn) == 0: + avgresults['coreDm'][2, 0] = 0 + else: + avgresults['coreDm'][2, 0] = warnvek[core_warn[0]] + + avgresults['coreDm'][3, 0] = max([avgresults['dmOut'][3, 0], avgresults['left']['wth'][3, 0], avgresults['right']['wth'][3, 0]]) + else: + avgresults['coreDm'][0:2, 0] = results['coreDm'][0:2, 0] + + if (eval_axis == EVALY or eval_axis == BOTH) and cableType not in [62, 63]: + measvek = np.array([avgresults['dmOut'][0, 1], avgresults['left']['wth'][0, 1], avgresults['right']['wth'][0, 1]]) + errvek = np.array([avgresults['dmOut'][1, 1], avgresults['left']['wth'][1, 1], avgresults['right']['wth'][1, 1]]) + warnvek = np.array([avgresults['dmOut'][2, 1], avgresults['left']['wth'][2, 1], avgresults['right']['wth'][2, 1]]) + + core_wait = np.where(errvek == StWait)[0] + core_err = np.where(errvek != 0)[0] + core_warn = np.where(warnvek != 0)[0] + + if len(core_err) == 0: + avgresults['coreDm'][0, 1] = avgresults['dmOut'][0, 1] - avgresults['left']['wth'][0, 1] - avgresults['right']['wth'][0, 1] + avgresults['coreDm'][1, 1] = 0 + elif len(core_wait) > 0: + avgresults['coreDm'][0, 1] = measvek[core_wait[0]] + avgresults['coreDm'][1, 1] = errvek[core_wait[0]] + else: + avgresults['coreDm'][0, 1] = 0 + avgresults['coreDm'][1, 1] = errvek[core_err[0]] + + if len(core_warn) == 0: + avgresults['coreDm'][2, 1] = 0 + else: + avgresults['coreDm'][2, 1] = warnvek[core_warn[0]] + + avgresults['coreDm'][3, 1] = max([avgresults['dmOut'][3, 1], avgresults['left']['wth'][3, 1], avgresults['right']['wth'][3, 1]]) + else: + avgresults['coreDm'][0:2, 1] = results['coreDm'][0:2, 1] + + return avgresults, avgmem diff --git a/algorithm/calibration_utils.py b/algorithm/calibration_utils.py new file mode 100644 index 0000000..1b4658c --- /dev/null +++ b/algorithm/calibration_utils.py @@ -0,0 +1,199 @@ +import numpy as np +import os + +try: + from .config_reader import config_read_double as ConfigReadDouble +except ImportError: + from config_reader import config_read_double as ConfigReadDouble + + +def floatread(filepath, columns): + filepath = str(filepath) + if not os.path.isfile(filepath): + print(f'file ={filepath}') + return np.array([]) + + try: + data = np.loadtxt(filepath) + if data.size == 0: + return np.array([]) + if data.ndim == 1: + return data + if columns == 1 and data.shape[1] == 1: + return data.ravel() + return data + except Exception: + try: + with open(filepath, 'r') as f: + lines = f.readlines() + values = [] + for line in lines: + parts = line.strip().split() + if parts: + row = [] + for p in parts: + try: + row.append(float(p)) + except ValueError: + pass + if row: + values.append(row) + if values: + return np.array(values) + return np.array([]) + except Exception as e: + print(f'file ={filepath}') + print(str(e)) + return np.array([]) + + +def _chkvek(calib_struct, prefix, nom, act, lengthconflict): + nom = np.asarray(nom, dtype=np.float64).ravel() + act = np.asarray(act, dtype=np.float64).ravel() + + if len(nom) > 0 and len(nom) == len(act): + sort_idx = np.argsort(nom) + nom = nom[sort_idx] + act = act[sort_idx] + + idx = np.where(nom <= 0)[0] + if len(idx) > 0: + nom = np.delete(nom, idx) + act = np.delete(act, idx) + + calib_struct[f'{prefix}nom'] = np.concatenate([[0.0], nom, [1000.0]]) + calib_struct[f'{prefix}act'] = np.concatenate([[0.0], act, [1000.0]]) + calib_struct[f'{prefix}err'] = 0 + elif len(nom) == 0 and len(act) == 0: + calib_struct[f'{prefix}nom'] = np.array([]) + calib_struct[f'{prefix}act'] = np.array([]) + calib_struct[f'{prefix}err'] = 0 + else: + calib_struct[f'{prefix}nom'] = np.array([]) + calib_struct[f'{prefix}act'] = np.array([]) + calib_struct[f'{prefix}err'] = lengthconflict + if calib_struct.get('err', 0) == 0: + calib_struct['err'] = lengthconflict + + return calib_struct + + +def read_calibration(filename): + lengthconflict = 189 + doubledefined = 190 + + calib_struct = {} + + try: + calib_struct['calibrationoff'] = ConfigReadDouble( + filename, 'cableType to calibration section link', 'calibrationoff') + calib_struct['mincableType'] = ConfigReadDouble( + filename, 'cableType to calibration section link', 'mincableType') + calib_struct['maxcableType'] = ConfigReadDouble( + filename, 'cableType to calibration section link', 'maxcableType') + calib_struct['sectionType'] = ConfigReadDouble( + filename, 'cableType to calibration section link', 'sectionType') + except Exception: + return {} + + if calib_struct['calibrationoff'] is None or ( + isinstance(calib_struct['calibrationoff'], (list, np.ndarray)) and + len(calib_struct['calibrationoff']) == 0): + return {} + + calib_struct['err'] = 0 + + try: + secType_len = len(calib_struct['sectionType']) if hasattr(calib_struct['sectionType'], '__len__') else 1 + minc_len = len(calib_struct['mincableType']) if hasattr(calib_struct['mincableType'], '__len__') else 1 + maxc_len = len(calib_struct['maxcableType']) if hasattr(calib_struct['maxcableType'], '__len__') else 1 + + if not (secType_len == minc_len == maxc_len): + calib_struct['err'] = lengthconflict + except Exception: + calib_struct['err'] = lengthconflict + + if calib_struct['err'] != 0: + return calib_struct + + try: + secType = np.atleast_1d(np.asarray(calib_struct['sectionType'], dtype=np.int32)).ravel() + minc = np.atleast_1d(np.asarray(calib_struct['mincableType'], dtype=np.float64)).ravel() + maxc = np.atleast_1d(np.asarray(calib_struct['maxcableType'], dtype=np.float64)).ravel() + + sort_idx = np.argsort(secType) + secType = secType[sort_idx] + minc = minc[sort_idx] + maxc = maxc[sort_idx] + + calib_struct['sectionType'] = secType + calib_struct['mincableType'] = minc + calib_struct['maxcableType'] = maxc + except Exception: + pass + + calib_struct['sect'] = {} + + try: + max_sec = int(np.max(calib_struct['sectionType'])) + except Exception: + return calib_struct + + for ii in range(1, max_sec + 1): + calib_struct['sect'][ii] = {} + + try: + nom = ConfigReadDouble(filename, f'section{ii}: Diameter calibration', 'Nominal') + act = ConfigReadDouble(filename, f'section{ii}: Diameter calibration', 'Actual') + calib_struct = _chkvek(calib_struct, f'sect.{ii}.diam.', nom, act, lengthconflict) + except Exception: + calib_struct[f'sect.{ii}.diam.nom'] = np.array([]) + calib_struct[f'sect.{ii}.diam.act'] = np.array([]) + calib_struct[f'sect.{ii}.diam.err'] = 0 + + try: + nom = ConfigReadDouble(filename, f'section{ii}: Wall thickness calibration', 'Nominal') + act = ConfigReadDouble(filename, f'section{ii}: Wall thickness calibration', 'Actual') + calib_struct = _chkvek(calib_struct, f'sect.{ii}.wall.', nom, act, lengthconflict) + except Exception: + calib_struct[f'sect.{ii}.wall.nom'] = np.array([]) + calib_struct[f'sect.{ii}.wall.act'] = np.array([]) + calib_struct[f'sect.{ii}.wall.err'] = 0 + + try: + nom = ConfigReadDouble(filename, f'section{ii}: Outer Layer thickness calibration', 'Nominal') + act = ConfigReadDouble(filename, f'section{ii}: Outer Layer thickness calibration', 'Actual') + calib_struct = _chkvek(calib_struct, f'sect.{ii}.lay1.', nom, act, lengthconflict) + except Exception: + calib_struct[f'sect.{ii}.lay1.nom'] = np.array([]) + calib_struct[f'sect.{ii}.lay1.act'] = np.array([]) + calib_struct[f'sect.{ii}.lay1.err'] = 0 + + try: + nom = ConfigReadDouble(filename, f'section{ii}: Second Layer thickness calibration', 'Nominal') + act = ConfigReadDouble(filename, f'section{ii}: Second Layer thickness calibration', 'Actual') + calib_struct = _chkvek(calib_struct, f'sect.{ii}.lay2.', nom, act, lengthconflict) + except Exception: + calib_struct[f'sect.{ii}.lay2.nom'] = np.array([]) + calib_struct[f'sect.{ii}.lay2.act'] = np.array([]) + calib_struct[f'sect.{ii}.lay2.err'] = 0 + + try: + nom = ConfigReadDouble(filename, f'section{ii}: Third Layer thickness calibration', 'Nominal') + act = ConfigReadDouble(filename, f'section{ii}: Third Layer thickness calibration', 'Actual') + calib_struct = _chkvek(calib_struct, f'sect.{ii}.lay3.', nom, act, lengthconflict) + except Exception: + calib_struct[f'sect.{ii}.lay3.nom'] = np.array([]) + calib_struct[f'sect.{ii}.lay3.act'] = np.array([]) + calib_struct[f'sect.{ii}.lay3.err'] = 0 + + length1 = len(np.atleast_1d(calib_struct.get(f'sect.{ii}.lay1.nom', np.array([])))) + length2 = len(np.atleast_1d(calib_struct.get(f'sect.{ii}.lay2.nom', np.array([])))) + length3 = len(np.atleast_1d(calib_struct.get(f'sect.{ii}.lay3.nom', np.array([])))) + + if length1 > 0 and length2 > 0 and length3 > 0: + calib_struct[f'sect.{ii}.lay3.err'] = doubledefined + if calib_struct.get('err', 0) == 0: + calib_struct['err'] = doubledefined + + return calib_struct diff --git a/algorithm/config_reader.py b/algorithm/config_reader.py new file mode 100644 index 0000000..32394e9 --- /dev/null +++ b/algorithm/config_reader.py @@ -0,0 +1,57 @@ +import numpy as np +import os +import re + + +def config_read_double(filepath, section, key): + """ + 从配置文件中读取指定节和键对应的浮点数值。 + + 对应 Matlab 的 ConfigReadDouble 函数。 + + 参数: + filepath: 配置文件路径 + section: 节名 (例如 'Data storing', 'section2: Diameter calibration') + key: 键名 (例如 'makeSave', 'Nominal') + + 返回: + numpy.ndarray: 读取到的浮点数值数组;如果找不到或为空,返回空数组 + """ + if not os.path.exists(filepath): + return np.array([]) + + try: + with open(filepath, 'r', encoding='utf-8', errors='ignore') as f: + lines = f.readlines() + except Exception: + return np.array([]) + + in_target_section = False + section_pattern = re.compile(r'^\s*\[\s*(.*?)\s*\]\s*$') + key_pattern = re.compile(r'^\s*' + re.escape(key) + r'\s*=\s*(.*?)\s*$', re.IGNORECASE) + + for line in lines: + line_stripped = line.strip() + + if not line_stripped or line_stripped.startswith('%'): + continue + + section_match = section_pattern.match(line_stripped) + if section_match: + current_section = section_match.group(1).strip() + in_target_section = (current_section.lower() == section.lower()) + continue + + if in_target_section: + key_match = key_pattern.match(line_stripped) + if key_match: + value_str = key_match.group(1).strip() + if not value_str: + return np.array([]) + try: + values = [float(v) for v in value_str.split()] + return np.array(values) + except ValueError: + return np.array([]) + + return np.array([]) diff --git a/algorithm/conv2dsp_utils.py b/algorithm/conv2dsp_utils.py new file mode 100644 index 0000000..944077f --- /dev/null +++ b/algorithm/conv2dsp_utils.py @@ -0,0 +1,1149 @@ +import numpy as np +from thickness_utils import warnlogic, updateMinMaxWTH, updateMinMaxWTHall + + +def avgfunc(xL, sxL, xR, sxR, StOK, StWait, StNoteavg, reduceavgon): + xWt = 0.0 + sxWt = 255.0 + avgwarnxWt = 0.0 + + if sxL == StWait: + sxWt = sxL + xWt = xL + avgwarnxWt = 0 + elif sxR == StWait: + sxWt = sxR + xWt = xR + avgwarnxWt = 0 + elif (sxL == StOK) and (sxR != StOK): + if reduceavgon: + sxWt = 0 + xWt = xL + avgwarnxWt = StNoteavg + else: + sxWt = sxR + xWt = 0 + avgwarnxWt = 0 + elif (sxL != StOK) and (sxR == StOK): + if reduceavgon: + sxWt = 0 + xWt = xR + avgwarnxWt = StNoteavg + else: + sxWt = sxL + xWt = 0 + avgwarnxWt = 0 + elif (sxL != StOK) and (sxR != StOK): + sxWt = sxL + xWt = 0 + avgwarnxWt = 0 + else: + sxWt = sxL + xWt = (xL + xR) / 2 + avgwarnxWt = 0 + + return xWt, sxWt, avgwarnxWt + + +def avgfuncDM(xL, sxL, xR, sxR, StOK, StWait, StNoteavg, reduceavgon): + xWt = 0.0 + sxWt = 255.0 + avgwarnxWt = 0.0 + + if (sxL == StWait) and (reduceavgon <= 1): + sxWt = sxL + xWt = xL + avgwarnxWt = 0 + elif (sxR == StWait) and (reduceavgon <= 1): + sxWt = sxR + xWt = xR + avgwarnxWt = 0 + elif (sxL == StOK) and (sxR != StOK): + if reduceavgon: + sxWt = 0 + xWt = xL + avgwarnxWt = StNoteavg + else: + sxWt = sxR + xWt = 0 + avgwarnxWt = 0 + elif (sxL != StOK) and (sxR == StOK): + if reduceavgon: + sxWt = 0 + xWt = xR + avgwarnxWt = StNoteavg + else: + sxWt = sxL + xWt = 0 + avgwarnxWt = 0 + elif (sxL != StOK) and (sxR != StOK): + sxWt = sxL + xWt = 0 + avgwarnxWt = 0 + else: + sxWt = sxL + xWt = (xL + xR) / 2 + avgwarnxWt = 0 + + return xWt, sxWt, avgwarnxWt + + +def avg4func(xL, sxL, xR, sxR, yL, syL, yR, syR, StOK, StWait, StNoteavg, reduceavgon): + Wt = 0.0 + sWt = 255.0 + avgwarnWt = 0.0 + + values = np.array([xL, xR, yL, yR], dtype=np.float64) + status = np.array([sxL, sxR, syL, syR], dtype=np.float64) + + waitind = np.where(status == StWait)[0] + okind = np.where(status == StOK)[0] + errind = np.where(status != StOK)[0] + + if len(waitind) > 0 and (reduceavgon <= 1): + sWt = status[waitind[0]] + Wt = values[waitind[0]] + avgwarnWt = 0 + elif len(okind) == 4: + sWt = 0 + Wt = np.mean(values[okind]) + avgwarnWt = 0 + elif len(okind) > 0: + if reduceavgon: + sWt = 0 + Wt = np.mean(values[okind]) + avgwarnWt = StNoteavg + else: + sWt = status[errind[0]] + Wt = 0 + avgwarnWt = 0 + else: + sWt = status[errind[0]] + Wt = 0 + avgwarnWt = 0 + + return Wt, sWt, avgwarnWt + + +def calc4modul(left, right, bRotateXDir, StOK, StWait, factMinWt, mm2inch, + calcecc, StNovalue, StNoteavg, reduceavgon, devicetype, cableType, NXT): + left = np.asarray(left, dtype=np.float64) + right = np.asarray(right, dtype=np.float64) + + anzColWt = 2 + MinMaxAng = np.zeros((3, anzColWt), dtype=np.float64) + MinMaxAng[1, :] = StNovalue + MinMaxAng[2, :] = 0 + + syL = left[1, 0] + if syL == StWait: + yL = left[0, 0] + else: + yL = left[0, 0] * mm2inch + + sxL = left[1, 1] + if sxL == StWait: + xL = left[0, 1] + else: + xL = left[0, 1] * mm2inch + + syR = right[1, 0] + if syR == StWait: + yR = right[0, 0] + else: + yR = right[0, 0] * mm2inch + + sxR = right[1, 1] + if sxR == StWait: + xR = right[0, 1] + else: + xR = right[0, 1] * mm2inch + + warnvek = np.array([left[2, 1], right[2, 1], left[2, 0], right[2, 0]], dtype=np.float64) + + anzColWt = 13 + Layer = np.zeros((3, anzColWt), dtype=np.float64) + Layer[1, :] = 255 + Layer[2, :] = 0 + + if bRotateXDir > 0: + if ((devicetype == 8000) or (devicetype == 8100) or + ((devicetype == 8001) and not NXT) or ((devicetype == 8101) and not NXT)): + h = xL; xL = yL; yL = h + h = sxL; sxL = syL; syL = h + h = xR; xR = yR; yR = h + h = sxR; sxR = syR; syR = h + warnvek = np.array([warnvek[1], warnvek[0], warnvek[3], warnvek[2]], dtype=np.float64) + elif ((devicetype == 8001) and NXT) or ((devicetype == 8101) and NXT): + h = yL; yL = yR; yR = h + h = syL; syL = syR; syR = h + warnvek = np.array([warnvek[1], warnvek[0], warnvek[2], warnvek[3]], dtype=np.float64) + else: + h = xL; xL = xR; xR = h + h = sxL; sxL = sxR; sxR = h + warnvek = np.array([warnvek[1], warnvek[0], warnvek[2], warnvek[3]], dtype=np.float64) + + warnall, warnx, warny = warnlogic(warnvek) + + xWt, sxWt, warnxWt = avgfunc(xL, sxL, xR, sxR, StOK, StWait, StNoteavg, reduceavgon) + yWt, syWt, warnyWt = avgfunc(yL, syL, yR, syR, StOK, StWait, StNoteavg, reduceavgon) + Wt, sWt, warnWt = avg4func(xL, sxL, xR, sxR, yL, syL, yR, syR, StOK, StWait, StNoteavg, reduceavgon) + + if not warnWt: + warnWt = warnall + if not warnxWt: + warnxWt = warnx + if not warnyWt: + warnyWt = warny + + xECC = 0.0 + sxECC = StNovalue + yECC = 0.0 + syECC = StNovalue + + if calcecc: + if sxL != StOK: + xECC = 0 + sxECC = sxL + elif sxR != StOK: + xECC = 0 + sxECC = sxR + else: + xECC = (xL - xR) / 2 + sxECC = 0 + + if syL != StOK: + yECC = 0 + syECC = syL + elif syR != StOK: + yECC = 0 + syECC = syR + else: + yECC = (yL - yR) / 2 + syECC = 0 + + Ecc = 0.0 + sEcc = 0.0 + if sxECC != StOK: + sEcc = sxECC + elif syECC != StOK: + sEcc = syECC + Ang = 0.0 + sAng = sEcc + + if sEcc == StOK: + Ecc = np.sqrt(xECC * xECC + yECC * yECC) + Ang = np.arctan2(xECC, -yECC) * 180 / np.pi + if Ang < 0: + Ang = 360 + Ang + + WtMin = 0.0 + sWtMin = 255.0 + status_arr = np.array([sxL, sxR, syL, syR], dtype=np.float64) + errind = np.where(status_arr != StOK)[0] + + if len(errind) == 0: + vals = np.array([yL, xR, yR, xL], dtype=np.float64) + IndMin = np.argmin(vals) + WtMin = vals[IndMin] + MinMaxAng[0, 0] = 90 * IndMin + MinMaxAng[1, 0] = StOK + sWtMin = 0 + else: + MinMaxAng[0, 0] = 0 + MinMaxAng[1, 0] = StNovalue + sWtMin = status_arr[errind[0]] + + WtMax = 0.0 + sWtMax = 255.0 + + if len(errind) == 0: + vals = np.array([yL, xR, yR, xL], dtype=np.float64) + IndMax = np.argmax(vals) + WtMax = vals[IndMax] + MinMaxAng[0, 1] = 90 * IndMax + MinMaxAng[1, 1] = StOK + sWtMax = 0 + else: + MinMaxAng[0, 1] = 0 + MinMaxAng[1, 1] = StNovalue + sWtMax = status_arr[errind[0]] + + MinMaxAng[2, :] = warnall + + if cableType == 62 or cableType == 63: + if sWt == 249 and sxWt == 0: + Layer[0, 0] = xWt; Layer[1, 0] = sxWt; Layer[2, 0] = warnxWt + Layer[0, 1] = xWt; Layer[1, 1] = sxWt; Layer[2, 1] = warnxWt + Layer[0, 7] = xWt; Layer[1, 7] = sxWt; Layer[2, 7] = warnxWt + else: + Layer[0, 0] = Wt; Layer[1, 0] = sWt; Layer[2, 0] = warnWt + Layer[0, 1] = Wt; Layer[1, 1] = sWt; Layer[2, 1] = warnWt + Layer[0, 7] = Wt; Layer[1, 7] = sWt; Layer[2, 7] = warnWt + if sWt == 249 and syWt == 0: + Layer[0, 2] = yWt; Layer[1, 2] = syWt; Layer[2, 2] = warnyWt + Layer[0, 3] = yWt; Layer[1, 3] = syWt; Layer[2, 3] = warnyWt + Layer[0, 8] = yWt; Layer[1, 8] = syWt; Layer[2, 8] = warnyWt + else: + Layer[0, 2] = Wt; Layer[1, 2] = sWt; Layer[2, 2] = warnWt + Layer[0, 3] = Wt; Layer[1, 3] = sWt; Layer[2, 3] = warnWt + Layer[0, 8] = Wt; Layer[1, 8] = sWt; Layer[2, 8] = warnWt + Layer[0, 4] = Wt; Layer[1, 4] = sWt; Layer[2, 4] = warnWt + Layer[0, 5] = Wt; Layer[1, 5] = sWt; Layer[2, 5] = warnWt + Layer[0, 6] = Wt; Layer[1, 6] = sWt; Layer[2, 6] = warnWt + Layer[0, 9] = 0; Layer[1, 9] = sWt; Layer[2, 9] = warnWt + Layer[0, 10] = 0; Layer[1, 10] = sWt; Layer[2, 10] = warnWt + Layer[0, 11] = 0; Layer[1, 11] = sWt; Layer[2, 11] = warnWt + Layer[0, 12] = 0; Layer[1, 12] = sWt; Layer[2, 12] = warnWt + else: + Layer[0, 0] = xL; Layer[1, 0] = sxL; Layer[2, 0] = warnvek[0] + Layer[0, 1] = xR; Layer[1, 1] = sxR; Layer[2, 1] = warnvek[1] + Layer[0, 2] = yL; Layer[1, 2] = syL; Layer[2, 2] = warnvek[2] + Layer[0, 3] = yR; Layer[1, 3] = syR; Layer[2, 3] = warnvek[3] + Layer[0, 4] = Wt; Layer[1, 4] = sWt; Layer[2, 4] = warnWt + Layer[0, 5] = WtMin; Layer[1, 5] = sWtMin; Layer[2, 5] = warnall + Layer[0, 6] = WtMax; Layer[1, 6] = sWtMax; Layer[2, 6] = warnall + Layer[0, 7] = xWt; Layer[1, 7] = sxWt; Layer[2, 7] = warnxWt + Layer[0, 8] = yWt; Layer[1, 8] = syWt; Layer[2, 8] = warnyWt + Layer[0, 9] = Ecc; Layer[1, 9] = sEcc; Layer[2, 9] = warnall + Layer[0, 10] = Ang; Layer[1, 10] = sAng; Layer[2, 10] = warnall + Layer[0, 11] = xECC; Layer[1, 11] = sxECC; Layer[2, 11] = warnx + Layer[0, 12] = yECC; Layer[1, 12] = syECC; Layer[2, 12] = warny + + if ((devicetype == 8000) and NXT) or ((devicetype == 8100) and NXT): + Layer[0, 10] = (Layer[0, 10] + 45) % 360 + elif ((devicetype == 8001) and NXT) or ((devicetype == 8101) and NXT): + Layer[0, 10] = (Layer[0, 10] + 90) % 360 + + return Layer, MinMaxAng + + +def _safe_get(obj, *keys, default=None): + current = obj + for key in keys: + if isinstance(current, dict): + current = current.get(key) + else: + return default + if current is None: + return default + return current + + +def _safe_arr_get(arr, idx1, idx2, default=0.0): + try: + a = np.asarray(arr, dtype=np.float64) + if a.ndim >= 2: + return float(a[idx1, idx2]) + elif a.ndim == 1: + return float(a[idx1]) + except (IndexError, TypeError, ValueError): + pass + return float(default) + + +def calctwist2(avgresults, layeruse, angle): + TWIST_CALC_ERROR = 91 + + if isinstance(layeruse, np.ndarray): + layeruse = layeruse.ravel() + layeruse = np.asarray(layeruse, dtype=np.float64).ravel() + if len(layeruse) < 3: + layeruse = np.pad(layeruse, (0, 3 - len(layeruse)), mode='constant') + + left_osc = np.asarray(avgresults['left']['osc'], dtype=np.float64).copy() + right_osc = np.asarray(avgresults['right']['osc'], dtype=np.float64).copy() + left_iso = np.asarray(avgresults['left']['iso'], dtype=np.float64).copy() + right_iso = np.asarray(avgresults['right']['iso'], dtype=np.float64).copy() + left_isc = np.asarray(avgresults['left']['isc'], dtype=np.float64).copy() + right_isc = np.asarray(avgresults['right']['isc'], dtype=np.float64).copy() + left_wth = np.asarray(avgresults['left']['wth'], dtype=np.float64).copy() + right_wth = np.asarray(avgresults['right']['wth'], dtype=np.float64).copy() + dmOut = np.asarray(avgresults['dmOut'], dtype=np.float64).copy() + coreDm = np.asarray(avgresults['coreDm'], dtype=np.float64).copy() + + faillayer = np.zeros(3, dtype=bool) + faillayer[0] = not (layeruse[0] and (np.all(left_osc[1, :] == 0) and np.all(right_osc[1, :] == 0))) + faillayer[1] = not (layeruse[1] and (np.all(left_iso[1, :] == 0) and np.all(right_iso[1, :] == 0))) + faillayer[2] = not (layeruse[2] and (np.all(left_isc[1, :] == 0) and np.all(right_isc[1, :] == 0))) + + all_ok = (np.all(dmOut[1, :] == 0) and np.all(coreDm[1, :] == 0) and + np.all(left_wth[1, :] == 0) and np.all(right_wth[1, :] == 0)) + + if all_ok: + xy0 = np.zeros((5, 2)) + xy0[4, :] = np.diff(np.vstack([left_wth[0, :], right_wth[0, :]]), axis=0) / 2 + xy0[3, :] = xy0[4, :] + xy0[2, :] = np.diff(np.vstack([left_wth[0, :] - left_isc[0, :], right_wth[0, :] - right_isc[0, :]]), axis=0) / 2 + xy0[1, :] = np.diff(np.vstack([left_wth[0, :] - left_isc[0, :] - left_iso[0, :], right_wth[0, :] - right_isc[0, :] - right_iso[0, :]]), axis=0) / 2 + xy0[0, :] = [0, 0] + xy0[:, 0] = -xy0[:, 0] + + ab = np.zeros((5, 2)) + ab[4, :] = coreDm[0, :] / 2 + ab[3, :] = ab[4, :] + ab[2, :] = ab[3, :] + (left_isc[0, :] + right_isc[0, :]) / 2 + ab[1, :] = ab[2, :] + (left_iso[0, :] + right_iso[0, :]) / 2 + ab[0, :] = dmOut[0, :] / 2 + + with np.errstate(invalid='ignore', divide='ignore'): + t_n = np.arctan(np.sqrt((xy0[:, 0]**2 - ab[:, 0]**2) / (xy0[:, 1]**2 - ab[:, 1]**2)) * (xy0[:, 1] / ab[:, 0])) + ab_n = np.column_stack([ab[:, 0] / np.cos(t_n), xy0[:, 1] / np.sin(t_n)]) + + angle = 2 * np.pi - angle + phi = np.mod(angle + np.array([0, 3 * np.pi / 2]), 2 * np.pi) + + for i in range(len(phi)): + t = np.arctan(ab[0, 0] / ab[0, 1] * np.tan(phi[i])) + + xrl = np.array([[ab[0, 0] * np.cos(t), -ab[0, 0] * np.cos(t)]]) + yrl = np.array([[ab[0, 1] * np.sin(t), -ab[0, 1] * np.sin(t)]]) + + p = xrl[0, 0] * (xrl[0, 0] * xy0[:, 0] * ab_n[:, 1]**2 + yrl[0, 0] * xy0[:, 1] * ab_n[:, 0]**2) / ((xrl[0, 0] * ab_n[:, 1])**2 + (yrl[0, 0] * ab_n[:, 0])**2) + q = xrl[0, 0]**2 * ((xy0[:, 0] * ab_n[:, 1])**2 + (xy0[:, 1] * ab_n[:, 0])**2 - (ab_n[:, 0] * ab_n[:, 1])**2) / ((xrl[0, 0] * ab_n[:, 1])**2 + (yrl[0, 0] * ab_n[:, 0])**2) + + xi = np.column_stack([p + np.sqrt(p**2 - q), p - np.sqrt(p**2 - q)]) + lu_mask = np.concatenate([[1], layeruse, [1]]) + xi = xi * lu_mask[:, np.newaxis] + xrl = np.vstack([xrl, xi[1:, :]]) + yi = yrl[0, 0] / xrl[0, 0] * xi + yrl = np.vstack([yrl, yi[1:, :]]) + + if (phi[i] > np.pi / 2) and (phi[i] <= 3 * np.pi / 2): + xrl = np.fliplr(xrl) + yrl = np.fliplr(yrl) + + if np.allclose(layeruse, [1, 0, 0]): + pass + elif np.allclose(layeruse, [0, 1, 0]): + xrl[1, :] = xrl[0, :] + yrl[1, :] = yrl[0, :] + elif np.allclose(layeruse, [0, 0, 1]): + xrl[2, :] = xrl[0, :] + yrl[2, :] = yrl[0, :] + elif np.allclose(layeruse, [1, 1, 0]): + pass + elif np.allclose(layeruse, [0, 1, 1]): + xrl[1, :] = xrl[0, :] + yrl[1, :] = yrl[0, :] + elif np.allclose(layeruse, [1, 0, 1]): + xrl[2, :] = xrl[1, :] + yrl[2, :] = yrl[1, :] + elif np.allclose(layeruse, [1, 1, 1]): + pass + + dmOut[0, i] = np.sqrt(xrl[0, 0]**2 + yrl[0, 0]**2) + np.sqrt(xrl[0, 1]**2 + yrl[0, 1]**2) + coreDm[0, i] = np.sqrt(xrl[4, 0]**2 + yrl[4, 0]**2) + np.sqrt(xrl[4, 1]**2 + yrl[4, 1]**2) + left_wth[0, i] = np.sqrt((xrl[0, 1] - xrl[4, 1])**2 + (yrl[0, 1] - yrl[4, 1])**2) + right_wth[0, i] = np.sqrt((xrl[0, 0] - xrl[4, 0])**2 + (yrl[0, 0] - yrl[4, 0])**2) + + if not faillayer[0]: + left_osc[0, i] = np.sqrt((xrl[0, 1] - xrl[1, 1])**2 + (yrl[0, 1] - yrl[1, 1])**2) * layeruse[0] + right_osc[0, i] = np.sqrt((xrl[0, 0] - xrl[1, 0])**2 + (yrl[0, 0] - yrl[1, 0])**2) * layeruse[0] + else: + if left_osc[1, i] == 0: + left_osc[1, i] = TWIST_CALC_ERROR + if right_osc[1, i] == 0: + right_osc[1, i] = TWIST_CALC_ERROR + + if not faillayer[1]: + left_iso[0, i] = np.sqrt((xrl[1, 1] - xrl[2, 1])**2 + (yrl[1, 1] - yrl[2, 1])**2) * layeruse[1] + right_iso[0, i] = np.sqrt((xrl[1, 0] - xrl[2, 0])**2 + (yrl[1, 0] - yrl[2, 0])**2) * layeruse[1] + else: + if left_iso[1, i] == 0: + left_iso[1, i] = TWIST_CALC_ERROR + if right_iso[1, i] == 0: + right_iso[1, i] = TWIST_CALC_ERROR + + if not faillayer[2]: + left_isc[0, i] = np.sqrt((xrl[2, 1] - xrl[3, 1])**2 + (yrl[2, 1] - yrl[3, 1])**2) * layeruse[2] + right_isc[0, i] = np.sqrt((xrl[2, 0] - xrl[3, 0])**2 + (yrl[2, 0] - yrl[3, 0])**2) * layeruse[2] + else: + if left_isc[1, i] == 0: + left_isc[1, i] = TWIST_CALC_ERROR + if right_isc[1, i] == 0: + right_isc[1, i] = TWIST_CALC_ERROR + else: + dmOut[1, dmOut[1, :] == 0] = TWIST_CALC_ERROR + left_osc[1, left_osc[1, :] == 0] = TWIST_CALC_ERROR + right_osc[1, right_osc[1, :] == 0] = TWIST_CALC_ERROR + left_iso[1, left_iso[1, :] == 0] = TWIST_CALC_ERROR + right_iso[1, right_iso[1, :] == 0] = TWIST_CALC_ERROR + left_isc[1, left_isc[1, :] == 0] = TWIST_CALC_ERROR + right_isc[1, right_isc[1, :] == 0] = TWIST_CALC_ERROR + coreDm[1, coreDm[1, :] == 0] = TWIST_CALC_ERROR + left_wth[1, left_wth[1, :] == 0] = TWIST_CALC_ERROR + right_wth[1, right_wth[1, :] == 0] = TWIST_CALC_ERROR + + result = { + 'left': { + 'osc': left_osc, + 'iso': left_iso, + 'isc': left_isc, + 'wth': left_wth, + }, + 'right': { + 'osc': right_osc, + 'iso': right_iso, + 'isc': right_isc, + 'wth': right_wth, + }, + 'dmOut': dmOut, + 'coreDm': coreDm, + } + return result + + +def conv2dsp(avgresults, bRotateXDir, factMinWt, unit, layeruse, cableType, eightpoint, + reduceavgon, angle, settings, devicetype, sectorAna, NXT): + StOK = 0 + StWait = 249 + StDefault = 255 + StNovalue = 45 + StNoteavg = 73 + anzColDm = 3 + + if unit == 0: + mm2inch = 1 + else: + mm2inch = 1 / 25.4 + + if (cableType in (51, 52, 53) or sectorAna or cableType in (62, 63)): + calcecc = 0 + else: + calcecc = 1 + + if eightpoint is not None and not sectorAna: + EPFlag = eightpoint + else: + EPFlag = 0 + + if reduceavgon is None or (isinstance(reduceavgon, np.ndarray) and reduceavgon.size == 0): + reduceavgon = 0 + elif isinstance(reduceavgon, (int, float)): + pass + else: + reduceavgon = float(np.asarray(reduceavgon).ravel()[0]) if np.asarray(reduceavgon).size > 0 else 0 + + anzColWt = 8 + MinMaxAng = StDefault * np.ones((3, anzColWt), dtype=np.float64) + MinMaxAng[2, :] = 0 + + # 获取 avgresults 的嵌套结构 + avgresults_left = _safe_get(avgresults, 'left', default={}) + avgresults_right = _safe_get(avgresults, 'right', default={}) + avgresults_coreDm = np.asarray(_safe_get(avgresults, 'coreDm', default=np.zeros((3, 2))), dtype=np.float64) + avgresults_dmOut = np.asarray(_safe_get(avgresults, 'dmOut', default=np.zeros((3, 2))), dtype=np.float64) + avgresults_eightPT = _safe_get(avgresults, 'eightPT', default={}) + + # eightPT 子结构 + eightPT_left = _safe_get(avgresults_eightPT, 'left', default={}) + eightPT_right = _safe_get(avgresults_eightPT, 'right', default={}) + eightPT_coreDm = np.asarray(_safe_get(avgresults_eightPT, 'coreDm', default=np.zeros((3, 2))), dtype=np.float64) + eightPT_dmOut = np.asarray(_safe_get(avgresults_eightPT, 'dmOut', default=np.zeros((3, 2))), dtype=np.float64) + + if isinstance(eightPT_left, dict): + if 'osc' in eightPT_left: + osc_arr = np.asarray(eightPT_left['osc']) + + # 确保 layeruse 是正确的格式 + if isinstance(layeruse, np.ndarray): + layeruse = layeruse.ravel() + elif isinstance(layeruse, (list, tuple)): + layeruse = np.asarray(layeruse, dtype=np.float64).ravel() + else: + layeruse = np.asarray([layeruse], dtype=np.float64).ravel() + + if len(layeruse) < 3: + layeruse = np.pad(layeruse, (0, 3 - len(layeruse)), mode='constant') + + # 调用 calc4modul 计算各层 + OSC, MinMaxAng[:, 0:2] = calc4modul( + _safe_get(avgresults_left, 'osc', default=np.zeros((3, 2))), + _safe_get(avgresults_right, 'osc', default=np.zeros((3, 2))), + bRotateXDir, StOK, StWait, 1, mm2inch, + calcecc, StNovalue, StNoteavg, reduceavgon, devicetype, cableType, NXT + ) + + ISO, MinMaxAng[:, 2:4] = calc4modul( + _safe_get(avgresults_left, 'iso', default=np.zeros((3, 2))), + _safe_get(avgresults_right, 'iso', default=np.zeros((3, 2))), + bRotateXDir, StOK, StWait, 1, mm2inch, + calcecc, StNovalue, StNoteavg, reduceavgon, devicetype, cableType, NXT + ) + + ISC, MinMaxAng[:, 4:6] = calc4modul( + _safe_get(avgresults_left, 'isc', default=np.zeros((3, 2))), + _safe_get(avgresults_right, 'isc', default=np.zeros((3, 2))), + bRotateXDir, StOK, StWait, 1, mm2inch, + calcecc, StNovalue, StNoteavg, reduceavgon, devicetype, cableType, NXT + ) + + WTH, MinMaxAng[:, 6:8] = calc4modul( + _safe_get(avgresults_left, 'wth', default=np.zeros((3, 2))), + _safe_get(avgresults_right, 'wth', default=np.zeros((3, 2))), + bRotateXDir, StOK, StWait, factMinWt, mm2inch, + calcecc, StNovalue, StNoteavg, reduceavgon, devicetype, cableType, NXT + ) + + WTH_8pt, _ = calc4modul( + _safe_get(eightPT_left, 'wth', default=np.zeros((3, 2))), + _safe_get(eightPT_right, 'wth', default=np.zeros((3, 2))), + bRotateXDir, StOK, StWait, factMinWt, mm2inch, + calcecc, StNovalue, StNoteavg, reduceavgon, devicetype, cableType, NXT + ) + + # ==================== DMCore 计算 ==================== + DMCore = StDefault * np.ones((3, anzColDm), dtype=np.float64) + DMCore[2, :] = 0 + DMCore_8pt = StDefault * np.ones((3, anzColDm), dtype=np.float64) + DMCore_8pt[2, :] = 0 + + is_8k_device = ((devicetype == 8000) or (devicetype == 8100) or + ((devicetype == 8001) and not NXT) or ((devicetype == 8101) and not NXT)) + + if is_8k_device: + if bRotateXDir == 1: + syDm = _safe_arr_get(avgresults_coreDm, 1, 1) + if syDm == StWait: + dmy = _safe_arr_get(avgresults_coreDm, 0, 1) + else: + dmy = _safe_arr_get(avgresults_coreDm, 0, 1) * mm2inch + sxDm = _safe_arr_get(avgresults_coreDm, 1, 0) + if sxDm == StWait: + dmx = _safe_arr_get(avgresults_coreDm, 0, 0) + else: + dmx = _safe_arr_get(avgresults_coreDm, 0, 0) * mm2inch + warnvek = np.array([_safe_arr_get(avgresults_coreDm, 2, 0), 0, + _safe_arr_get(avgresults_coreDm, 2, 1), 0], dtype=np.float64) + + syDm_8pt = _safe_arr_get(eightPT_coreDm, 1, 1) + if syDm_8pt == StWait: + dmy_8pt = _safe_arr_get(eightPT_coreDm, 0, 1) + else: + dmy_8pt = _safe_arr_get(eightPT_coreDm, 0, 1) * mm2inch + sxDm_8pt = _safe_arr_get(eightPT_coreDm, 1, 0) + if sxDm_8pt == StWait: + dmx_8pt = _safe_arr_get(eightPT_coreDm, 0, 0) + else: + dmx_8pt = _safe_arr_get(eightPT_coreDm, 0, 0) * mm2inch + warnvek_8pt = np.array([_safe_arr_get(eightPT_coreDm, 2, 0), 0, + _safe_arr_get(eightPT_coreDm, 2, 1), 0], dtype=np.float64) + else: + syDm = _safe_arr_get(avgresults_coreDm, 1, 0) + if syDm == StWait: + dmy = _safe_arr_get(avgresults_coreDm, 0, 0) + else: + dmy = _safe_arr_get(avgresults_coreDm, 0, 0) * mm2inch + sxDm = _safe_arr_get(avgresults_coreDm, 1, 1) + if sxDm == StWait: + dmx = _safe_arr_get(avgresults_coreDm, 0, 1) + else: + dmx = _safe_arr_get(avgresults_coreDm, 0, 1) * mm2inch + warnvek = np.array([_safe_arr_get(avgresults_coreDm, 2, 1), 0, + _safe_arr_get(avgresults_coreDm, 2, 0), 0], dtype=np.float64) + + syDm_8pt = _safe_arr_get(eightPT_coreDm, 1, 0) + if syDm_8pt == StWait: + dmy_8pt = _safe_arr_get(eightPT_coreDm, 0, 0) + else: + dmy_8pt = _safe_arr_get(eightPT_coreDm, 0, 0) * mm2inch + sxDm_8pt = _safe_arr_get(eightPT_coreDm, 1, 1) + if sxDm_8pt == StWait: + dmx_8pt = _safe_arr_get(eightPT_coreDm, 0, 1) + else: + dmx_8pt = _safe_arr_get(eightPT_coreDm, 0, 1) * mm2inch + warnvek_8pt = np.array([_safe_arr_get(eightPT_coreDm, 2, 1), 0, + _safe_arr_get(eightPT_coreDm, 2, 0), 0], dtype=np.float64) + else: + syDm = _safe_arr_get(avgresults_coreDm, 1, 0) + if syDm == StWait: + dmy = _safe_arr_get(avgresults_coreDm, 0, 0) + else: + dmy = _safe_arr_get(avgresults_coreDm, 0, 0) * mm2inch + sxDm = _safe_arr_get(avgresults_coreDm, 1, 1) + if sxDm == StWait: + dmx = _safe_arr_get(avgresults_coreDm, 0, 1) + else: + dmx = _safe_arr_get(avgresults_coreDm, 0, 1) * mm2inch + warnvek = np.array([_safe_arr_get(avgresults_coreDm, 2, 1), 0, + _safe_arr_get(avgresults_coreDm, 2, 0), 0], dtype=np.float64) + + syDm_8pt = _safe_arr_get(eightPT_coreDm, 1, 0) + if syDm_8pt == StWait: + dmy_8pt = _safe_arr_get(eightPT_coreDm, 0, 0) + else: + dmy_8pt = _safe_arr_get(eightPT_coreDm, 0, 0) * mm2inch + sxDm_8pt = _safe_arr_get(eightPT_coreDm, 1, 1) + if sxDm_8pt == StWait: + dmx_8pt = _safe_arr_get(eightPT_coreDm, 0, 1) + else: + dmx_8pt = _safe_arr_get(eightPT_coreDm, 0, 1) * mm2inch + warnvek_8pt = np.array([_safe_arr_get(eightPT_coreDm, 2, 1), 0, + _safe_arr_get(eightPT_coreDm, 2, 0), 0], dtype=np.float64) + + warnall, warnx, warny = warnlogic(warnvek) + warnall_8pt, warnx_8pt, warny_8pt = warnlogic(warnvek_8pt) + + dm, sDm, warnavgdm = avgfuncDM(dmx, sxDm, dmy, syDm, StOK, StWait, StNoteavg, reduceavgon) + dm_8pt, sDm_8pt, warnavgdm_8pt = avgfuncDM(dmx_8pt, sxDm_8pt, dmy_8pt, syDm_8pt, StOK, StWait, StNoteavg, reduceavgon) + + if not warnavgdm: + warnavgdm = warnall + if not warnavgdm_8pt: + warnavgdm_8pt = warnall_8pt + + if cableType in (1, 2) and sectorAna: + DMCore[0, :] = 0 + DMCore[1, :] = StNovalue + DMCore_8pt[0, :] = 0 + DMCore_8pt[1, :] = StNovalue + else: + DMCore[0, 0] = dm; DMCore[1, 0] = sDm; DMCore[2, 0] = warnavgdm + DMCore[0, 1] = dmx; DMCore[1, 1] = sxDm; DMCore[2, 1] = warnx + DMCore[0, 2] = dmy; DMCore[1, 2] = syDm; DMCore[2, 2] = warny + + DMCore_8pt[0, 0] = dm_8pt; DMCore_8pt[1, 0] = sDm_8pt; DMCore_8pt[2, 0] = warnavgdm_8pt + DMCore_8pt[0, 1] = dmx_8pt; DMCore_8pt[1, 1] = sxDm_8pt; DMCore_8pt[2, 1] = warnx_8pt + DMCore_8pt[0, 2] = dmy_8pt; DMCore_8pt[1, 2] = syDm_8pt; DMCore_8pt[2, 2] = warny_8pt + + # ==================== DMTotal 计算 ==================== + DMTotal = StDefault * np.ones((3, anzColDm), dtype=np.float64) + DMTotal[2, :] = 0 + DMTotal_8pt = StDefault * np.ones((3, anzColDm), dtype=np.float64) + DMTotal_8pt[2, :] = 0 + + if is_8k_device: + if bRotateXDir == 1: + syDm = _safe_arr_get(avgresults_dmOut, 1, 1) + if syDm == StWait: + dmy = _safe_arr_get(avgresults_dmOut, 0, 1) + else: + dmy = _safe_arr_get(avgresults_dmOut, 0, 1) * mm2inch + sxDm = _safe_arr_get(avgresults_dmOut, 1, 0) + if sxDm == StWait: + dmx = _safe_arr_get(avgresults_dmOut, 0, 0) + else: + dmx = _safe_arr_get(avgresults_dmOut, 0, 0) * mm2inch + warnvek = np.array([_safe_arr_get(avgresults_dmOut, 2, 0), 0, + _safe_arr_get(avgresults_dmOut, 2, 1), 0], dtype=np.float64) + + syDm_8pt = _safe_arr_get(eightPT_dmOut, 1, 1) + if syDm_8pt == StWait: + dmy_8pt = _safe_arr_get(eightPT_dmOut, 0, 1) + else: + dmy_8pt = _safe_arr_get(eightPT_dmOut, 0, 1) * mm2inch + sxDm_8pt = _safe_arr_get(eightPT_dmOut, 1, 0) + if sxDm_8pt == StWait: + dmx_8pt = _safe_arr_get(eightPT_dmOut, 0, 0) + else: + dmx_8pt = _safe_arr_get(eightPT_dmOut, 0, 0) * mm2inch + warnvek_8pt = np.array([_safe_arr_get(eightPT_dmOut, 2, 0), 0, + _safe_arr_get(eightPT_dmOut, 2, 1), 0], dtype=np.float64) + else: + syDm = _safe_arr_get(avgresults_dmOut, 1, 0) + if syDm == StWait: + dmy = _safe_arr_get(avgresults_dmOut, 0, 0) + else: + dmy = _safe_arr_get(avgresults_dmOut, 0, 0) * mm2inch + sxDm = _safe_arr_get(avgresults_dmOut, 1, 1) + if sxDm == StWait: + dmx = _safe_arr_get(avgresults_dmOut, 0, 1) + else: + dmx = _safe_arr_get(avgresults_dmOut, 0, 1) * mm2inch + warnvek = np.array([_safe_arr_get(avgresults_dmOut, 2, 1), 0, + _safe_arr_get(avgresults_dmOut, 2, 0), 0], dtype=np.float64) + + syDm_8pt = _safe_arr_get(eightPT_dmOut, 1, 0) + if syDm_8pt == StWait: + dmy_8pt = _safe_arr_get(eightPT_dmOut, 0, 0) + else: + dmy_8pt = _safe_arr_get(eightPT_dmOut, 0, 0) * mm2inch + sxDm_8pt = _safe_arr_get(eightPT_dmOut, 1, 1) + if sxDm_8pt == StWait: + dmx_8pt = _safe_arr_get(eightPT_dmOut, 0, 1) + else: + dmx_8pt = _safe_arr_get(eightPT_dmOut, 0, 1) * mm2inch + warnvek_8pt = np.array([_safe_arr_get(eightPT_dmOut, 2, 1), 0, + _safe_arr_get(eightPT_dmOut, 2, 0), 0], dtype=np.float64) + else: + syDm = _safe_arr_get(avgresults_dmOut, 1, 0) + if syDm == StWait: + dmy = _safe_arr_get(avgresults_dmOut, 0, 0) + else: + dmy = _safe_arr_get(avgresults_dmOut, 0, 0) * mm2inch + sxDm = _safe_arr_get(avgresults_dmOut, 1, 1) + if sxDm == StWait: + dmx = _safe_arr_get(avgresults_dmOut, 0, 1) + else: + dmx = _safe_arr_get(avgresults_dmOut, 0, 1) * mm2inch + warnvek = np.array([_safe_arr_get(avgresults_dmOut, 2, 1), 0, + _safe_arr_get(avgresults_dmOut, 2, 0), 0], dtype=np.float64) + + syDm_8pt = _safe_arr_get(eightPT_dmOut, 1, 0) + if syDm_8pt == StWait: + dmy_8pt = _safe_arr_get(eightPT_dmOut, 0, 0) + else: + dmy_8pt = _safe_arr_get(eightPT_dmOut, 0, 0) * mm2inch + sxDm_8pt = _safe_arr_get(eightPT_dmOut, 1, 1) + if sxDm_8pt == StWait: + dmx_8pt = _safe_arr_get(eightPT_dmOut, 0, 1) + else: + dmx_8pt = _safe_arr_get(eightPT_dmOut, 0, 1) * mm2inch + warnvek_8pt = np.array([_safe_arr_get(eightPT_dmOut, 2, 1), 0, + _safe_arr_get(eightPT_dmOut, 2, 0), 0], dtype=np.float64) + + warnall, warnx, warny = warnlogic(warnvek) + warnall_8pt, warnx_8pt, warny_8pt = warnlogic(warnvek_8pt) + + dm, sDm, warnavgdm = avgfuncDM(dmx, sxDm, dmy, syDm, StOK, StWait, StNoteavg, reduceavgon) + dm_8pt, sDm_8pt, warnavgdm_8pt = avgfuncDM(dmx_8pt, sxDm_8pt, dmy_8pt, syDm_8pt, StOK, StWait, StNoteavg, reduceavgon) + + if (warnavgdm == 73) and (cableType == 53): + warnavgdm = 0 + if (warnavgdm_8pt == 73) and (cableType == 53): + warnavgdm_8pt = 0 + + if not warnavgdm: + warnavgdm = warnall + if not warnavgdm_8pt: + warnavgdm_8pt = warnall_8pt + + if cableType in (1, 2) and sectorAna: + DMTotal[0, :] = 0 + DMTotal[1, :] = StNovalue + DMTotal_8pt[0, :] = 0 + DMTotal_8pt[1, :] = StNovalue + else: + DMTotal[0, 0] = dm; DMTotal[1, 0] = sDm; DMTotal[2, 0] = warnavgdm + DMTotal[0, 1] = dmx; DMTotal[1, 1] = sxDm; DMTotal[2, 1] = warnx + DMTotal[0, 2] = dmy; DMTotal[1, 2] = syDm; DMTotal[2, 2] = warny + + DMTotal_8pt[0, 0] = dm_8pt; DMTotal_8pt[1, 0] = sDm_8pt; DMTotal_8pt[2, 0] = warnavgdm_8pt + DMTotal_8pt[0, 1] = dmx_8pt; DMTotal_8pt[1, 1] = sxDm_8pt; DMTotal_8pt[2, 1] = warnx_8pt + DMTotal_8pt[0, 2] = dmy_8pt; DMTotal_8pt[1, 2] = syDm_8pt; DMTotal_8pt[2, 2] = warny_8pt + + # ==================== DMISO 计算 ==================== + DMISO = np.zeros((3, 3), dtype=np.float64) + DMISO[1, :] = StDefault + + def _status_ok(s): + return s in (StOK, StWait) + + if np.allclose(layeruse[:3], [0, 1, 0]) or np.allclose(layeruse[:3], [0, 1, 1]): + DMISO = DMTotal_8pt.copy() + elif np.allclose(layeruse[:3], [1, 1, 0]) or np.allclose(layeruse[:3], [1, 1, 1]): + if _status_ok(DMTotal_8pt[1, 1]) and _status_ok(OSC[1, 0]) and _status_ok(OSC[1, 1]): + DMISO[0, 1] = DMTotal_8pt[0, 1] - OSC[0, 0] - OSC[0, 1] + DMISO[1, 1] = 0 + if _status_ok(DMTotal_8pt[1, 2]) and _status_ok(OSC[1, 2]) and _status_ok(OSC[1, 3]): + DMISO[0, 2] = DMTotal_8pt[0, 2] - OSC[0, 2] - OSC[0, 3] + DMISO[1, 2] = 0 + if not (DMISO[1, 1] or DMISO[1, 2]): + DMISO[0, 0] = 0.5 * (DMISO[0, 1] + DMISO[0, 2]) + DMISO[1, 0] = 0 + elif not DMISO[1, 1] and (reduceavgon > 1): + DMISO[0, 0] = DMISO[0, 1] + DMISO[1, 0] = 0 + DMISO[2, 0] = StNoteavg + elif not DMISO[1, 2] and (reduceavgon > 1): + DMISO[0, 0] = DMISO[0, 2] + DMISO[1, 0] = 0 + DMISO[2, 0] = StNoteavg + + warnvek = np.array([DMTotal_8pt[2, 1], OSC[2, 7], DMTotal_8pt[2, 2], OSC[2, 8]], dtype=np.float64) + warnall, warnx, warny = warnlogic(warnvek) + DMISO[2, 1] = warnx + DMISO[2, 2] = warny + DMISO[2, 0] = warnall + else: + DMISO[1, :] = StNovalue + + # ==================== DMISC 计算 ==================== + DMISC = np.zeros((3, 3), dtype=np.float64) + DMISC[1, :] = StDefault + + if np.allclose(layeruse[:3], [0, 0, 1]): + DMISC = DMTotal_8pt.copy() + elif (np.allclose(layeruse[:3], [1, 0, 1]) or + np.allclose(layeruse[:3], [0, 1, 1]) or + np.allclose(layeruse[:3], [1, 1, 1])): + if _status_ok(DMCore_8pt[1, 1]) and _status_ok(ISC[1, 0]) and _status_ok(ISC[1, 1]): + DMISC[0, 1] = DMCore_8pt[0, 1] + ISC[0, 0] + ISC[0, 1] + DMISC[1, 1] = 0 + if _status_ok(DMCore_8pt[1, 2]) and _status_ok(ISC[1, 2]) and _status_ok(ISC[1, 3]): + DMISC[0, 2] = DMCore_8pt[0, 2] + ISC[0, 2] + ISC[0, 3] + DMISC[1, 2] = 0 + if not (DMISC[1, 1] or DMISC[1, 2]): + DMISC[0, 0] = 0.5 * (DMISC[0, 1] + DMISC[0, 2]) + DMISC[1, 0] = 0 + elif not DMISC[1, 1] and (reduceavgon > 1): + DMISC[0, 0] = DMISC[0, 1] + DMISC[1, 0] = 0 + DMISC[2, 0] = StNoteavg + elif not DMISC[1, 2] and (reduceavgon > 1): + DMISC[0, 0] = DMISC[0, 2] + DMISC[1, 0] = 0 + DMISC[2, 0] = StNoteavg + + warnvek = np.array([DMCore_8pt[2, 1], ISC[2, 7], DMCore_8pt[2, 2], ISC[2, 8]], dtype=np.float64) + warnall, warnx, warny = warnlogic(warnvek) + DMISC[2, 1] = warnx + DMISC[2, 2] = warny + DMISC[2, 0] = warnall + else: + DMISC[1, :] = StNovalue + + TAMode = 0 + EPMode = 0 + WTHMode = 0 + + # ==================== BisecWTH 计算 ==================== + anzColWt = 16 + BisecWTH = np.zeros((3, anzColWt), dtype=np.float64) + BisecWTH[1, :] = StDefault + BisecWTH[2, :] = 0 + + if EPFlag == 1: + if cableType not in (51, 52, 53, 62, 63): + if not TAMode: + Bisec_avgresults = calctwist2(avgresults_eightPT, layeruse, angle - np.pi / 4) + + if bRotateXDir: + tmp = Bisec_avgresults + is_8k = (devicetype in (8000, 8100) or + (devicetype == 8001 and not NXT) or + (devicetype == 8101 and not NXT)) + if is_8k: + for k in ('osc', 'iso', 'isc', 'wth'): + Bisec_avgresults['left'][k][:, 0] = tmp['right'][k][:, 0].copy() + Bisec_avgresults['right'][k][:, 0] = tmp['left'][k][:, 0].copy() + else: + for k in ('osc', 'iso', 'isc', 'wth'): + Bisec_avgresults['left'][k] = np.fliplr(tmp['right'][k]).copy() + Bisec_avgresults['right'][k] = np.fliplr(tmp['left'][k]).copy() + + bl = Bisec_avgresults['left'] + br = Bisec_avgresults['right'] + + BisecWTH[0, :] = np.concatenate([ + [bl['osc'][0, 0]], np.fliplr(br['osc'][0:1, :])[0], [bl['osc'][0, 1]], + [bl['iso'][0, 0]], np.fliplr(br['iso'][0:1, :])[0], [bl['iso'][0, 1]], + [bl['isc'][0, 0]], np.fliplr(br['isc'][0:1, :])[0], [bl['isc'][0, 1]], + [bl['wth'][0, 0]], np.fliplr(br['wth'][0:1, :])[0], [bl['wth'][0, 1]], + ]) * mm2inch + BisecWTH[1, :] = np.concatenate([ + [bl['osc'][1, 0]], np.fliplr(br['osc'][1:2, :])[0], [bl['osc'][1, 1]], + [bl['iso'][1, 0]], np.fliplr(br['iso'][1:2, :])[0], [bl['iso'][1, 1]], + [bl['isc'][1, 0]], np.fliplr(br['isc'][1:2, :])[0], [bl['isc'][1, 1]], + [bl['wth'][1, 0]], np.fliplr(br['wth'][1:2, :])[0], [bl['wth'][1, 1]], + ]) + BisecWTH[2, :] = np.concatenate([ + [bl['osc'][2, 0]], np.fliplr(br['osc'][2:3, :])[0], [bl['osc'][2, 1]], + [bl['iso'][2, 0]], np.fliplr(br['iso'][2:3, :])[0], [bl['iso'][2, 1]], + [bl['isc'][2, 0]], np.fliplr(br['isc'][2:3, :])[0], [bl['isc'][2, 1]], + [bl['wth'][2, 0]], np.fliplr(br['wth'][2:3, :])[0], [bl['wth'][2, 1]], + ]) + + if np.allclose(layeruse[:3], [1, 0, 0]): + if EPMode: + pass + else: + OSC, BisecWTH[:, 0:4], MinMaxAng[:, 0:2] = updateMinMaxWTH( + OSC, DMTotal_8pt, DMCore_8pt, BisecWTH[:, 0:4], StOK, StDefault, StNovalue, reduceavgon + ) + BisecWTH[0, 4:8] = 0; BisecWTH[1, 4:8] = StNovalue + BisecWTH[0, 8:12] = 0; BisecWTH[1, 8:12] = StNovalue + MinMaxAng[0, 2:4] = 0; MinMaxAng[1, 2:4] = StNovalue + MinMaxAng[0, 4:6] = 0; MinMaxAng[1, 4:6] = StNovalue + elif np.allclose(layeruse[:3], [0, 1, 0]): + if EPMode: + pass + else: + ISO, BisecWTH[:, 4:8], MinMaxAng[:, 2:4] = updateMinMaxWTH( + ISO, DMTotal_8pt, DMCore_8pt, BisecWTH[:, 4:8], StOK, StDefault, StNovalue, reduceavgon + ) + BisecWTH[0, 0:4] = 0; BisecWTH[1, 0:4] = StNovalue + BisecWTH[0, 8:12] = 0; BisecWTH[1, 8:12] = StNovalue + MinMaxAng[0, 0:2] = 0; MinMaxAng[1, 0:2] = StNovalue + MinMaxAng[0, 4:6] = 0; MinMaxAng[1, 4:6] = StNovalue + elif np.allclose(layeruse[:3], [0, 0, 1]): + if EPMode: + pass + else: + ISC, BisecWTH[:, 8:12], MinMaxAng[:, 4:6] = updateMinMaxWTH( + ISC, DMTotal_8pt, DMCore_8pt, BisecWTH[:, 8:12], StOK, StDefault, StNovalue, reduceavgon + ) + BisecWTH[0, 0:4] = 0; BisecWTH[1, 0:4] = StNovalue + BisecWTH[0, 4:8] = 0; BisecWTH[1, 4:8] = StNovalue + MinMaxAng[0, 0:2] = 0; MinMaxAng[1, 0:2] = StNovalue + MinMaxAng[0, 2:4] = 0; MinMaxAng[1, 2:4] = StNovalue + elif np.allclose(layeruse[:3], [1, 1, 0]): + if EPMode: + pass + else: + OSC, BisecWTH[:, 0:4], MinMaxAng[:, 0:2] = updateMinMaxWTH( + OSC, DMTotal_8pt, DMISO, BisecWTH[:, 0:4], StOK, StDefault, StNovalue, reduceavgon + ) + ISO, BisecWTH[:, 4:8], MinMaxAng[:, 2:4] = updateMinMaxWTH( + ISO, DMISO, DMCore_8pt, BisecWTH[:, 4:8], StOK, StDefault, StNovalue, reduceavgon + ) + BisecWTH[0, 8:12] = 0; BisecWTH[1, 8:12] = StNovalue + MinMaxAng[0, 4:6] = 0; MinMaxAng[1, 4:6] = StNovalue + elif np.allclose(layeruse[:3], [0, 1, 1]): + if EPMode: + pass + else: + ISO, BisecWTH[:, 4:8], MinMaxAng[:, 2:4] = updateMinMaxWTH( + ISO, DMTotal_8pt, DMISC, BisecWTH[:, 4:8], StOK, StDefault, StNovalue, reduceavgon + ) + ISC, BisecWTH[:, 8:12], MinMaxAng[:, 4:6] = updateMinMaxWTH( + ISC, DMISC, DMCore_8pt, BisecWTH[:, 8:12], StOK, StDefault, StNovalue, reduceavgon + ) + BisecWTH[0, 0:4] = 0; BisecWTH[1, 0:4] = StNovalue + MinMaxAng[0, 0:2] = 0; MinMaxAng[1, 0:2] = StNovalue + elif np.allclose(layeruse[:3], [1, 0, 1]): + if EPMode: + pass + else: + OSC, BisecWTH[:, 0:4], MinMaxAng[:, 0:2] = updateMinMaxWTH( + OSC, DMTotal_8pt, DMISO, BisecWTH[:, 0:4], StOK, StDefault, StNovalue, reduceavgon + ) + ISC, BisecWTH[:, 8:12], MinMaxAng[:, 4:6] = updateMinMaxWTH( + ISC, DMISC, DMCore_8pt, BisecWTH[:, 8:12], StOK, StDefault, StNovalue, reduceavgon + ) + BisecWTH[0, 4:8] = 0; BisecWTH[1, 4:8] = StNovalue + MinMaxAng[0, 2:4] = 0; MinMaxAng[1, 2:4] = StNovalue + elif np.allclose(layeruse[:3], [1, 1, 1]): + if EPMode: + pass + else: + OSC, BisecWTH[:, 0:4], MinMaxAng[:, 0:2] = updateMinMaxWTH( + OSC, DMTotal_8pt, DMISO, BisecWTH[:, 0:4], StOK, StDefault, StNovalue, reduceavgon + ) + ISO, BisecWTH[:, 4:8], MinMaxAng[:, 2:4] = updateMinMaxWTH( + ISO, DMISO, DMISC, BisecWTH[:, 4:8], StOK, StDefault, StNovalue, reduceavgon + ) + ISC, BisecWTH[:, 8:12], MinMaxAng[:, 4:6] = updateMinMaxWTH( + ISC, DMISC, DMCore_8pt, BisecWTH[:, 8:12], StOK, StDefault, StNovalue, reduceavgon + ) + + if EPMode: + pass + else: + WTH, BisecWTH[:, 12:16], MinMaxAng[:, 6:8] = updateMinMaxWTH( + WTH_8pt, DMTotal_8pt, DMCore_8pt, BisecWTH[:, 12:16], StOK, StDefault, StNovalue, reduceavgon + ) + + confData = np.asarray(settings.get('confData', np.array([])), dtype=np.float64) if isinstance(settings, dict) else np.array([]) + WTHall = None + WTHallErr = None + addangle_arr = np.array([]) + + if not WTHMode: + if len(confData) > 197: + c198 = confData[197] + else: + c198 = 16 + nangle = int(2 ** np.floor(np.log2(max(16, c198)))) + dangle = 360.0 / nangle + addangle = np.arange(dangle, 89.999, dangle) + if EPFlag: + addangle = addangle[addangle % 45 != 0] + addangle_arr = addangle / 180 * np.pi + n_add = len(addangle_arr) + WTHall = np.zeros((n_add, 16), dtype=np.float64) + WTHallErr = np.zeros((n_add, 16), dtype=np.float64) + + for i in range(n_add): + tmp = calctwist2(avgresults, layeruse, angle - addangle_arr[i]) + if bRotateXDir: + for k in ('osc', 'iso', 'isc', 'wth'): + tmp['left'][k] = np.fliplr(tmp['left'][k]) + tmp['right'][k] = np.fliplr(tmp['right'][k]) + + tl = tmp['left'] + tr = tmp['right'] + WTHall[i, :] = np.concatenate([ + [tl['osc'][0, 0]], np.fliplr(tr['osc'][0:1, :])[0], [tl['osc'][0, 1]], + [tl['iso'][0, 0]], np.fliplr(tr['iso'][0:1, :])[0], [tl['iso'][0, 1]], + [tl['isc'][0, 0]], np.fliplr(tr['isc'][0:1, :])[0], [tl['isc'][0, 1]], + [tl['wth'][0, 0]], np.fliplr(tr['wth'][0:1, :])[0], [tl['wth'][0, 1]], + ]) * mm2inch + WTHallErr[i, :] = np.concatenate([ + [tl['osc'][1, 0]], np.fliplr(tr['osc'][1:2, :])[0], [tl['osc'][1, 1]], + [tl['iso'][1, 0]], np.fliplr(tr['iso'][1:2, :])[0], [tl['iso'][1, 1]], + [tl['isc'][1, 0]], np.fliplr(tr['isc'][1:2, :])[0], [tl['isc'][1, 1]], + [tl['wth'][1, 0]], np.fliplr(tr['wth'][1:2, :])[0], [tl['wth'][1, 1]], + ]) + + if layeruse[0] and np.all(np.concatenate([OSC[1, 0:4], OSC[1, 10:13], DMTotal[1, 1:3], MinMaxAng[1, 0:2]]) == 0): + if not WTHMode and WTHall is not None: + OSC, MinMaxAng[0:2, 0:2] = updateMinMaxWTHall( + OSC, WTHall[:, 0:4], MinMaxAng[0:2, 0:2], confData, addangle_arr, WTHallErr[:, 0:4] + ) + + if layeruse[1] and np.all(np.concatenate([ISO[1, 0:4], ISO[1, 10:13], DMISO[1, 1:3], MinMaxAng[1, 2:4]]) == 0): + if not WTHMode and WTHall is not None: + ISO, MinMaxAng[0:2, 2:4] = updateMinMaxWTHall( + ISO, WTHall[:, 4:8], MinMaxAng[0:2, 2:4], confData, addangle_arr, WTHallErr[:, 4:8] + ) + + if layeruse[2] and np.all(np.concatenate([ISC[1, 0:4], ISC[1, 10:13], DMISC[1, 1:3], MinMaxAng[1, 4:6]]) == 0): + if not WTHMode and WTHall is not None: + ISC, MinMaxAng[0:2, 4:6] = updateMinMaxWTHall( + ISC, WTHall[:, 8:12], MinMaxAng[0:2, 4:6], confData, addangle_arr, WTHallErr[:, 8:12] + ) + + if np.all(np.concatenate([WTH[1, 0:4], WTH[1, 10:13], DMTotal[1, 1:3], MinMaxAng[1, 6:8]]) == 0): + if not WTHMode and WTHall is not None: + WTH, MinMaxAng[0:2, 6:8] = updateMinMaxWTHall( + WTH, WTHall[:, 12:16], MinMaxAng[0:2, 6:8], confData, addangle_arr, WTHallErr[:, 12:16] + ) + + # ==================== 后处理:NaN 和范围检查 ==================== + def _post_process(arr): + a = arr.copy() + # NaN 检查 + nan_mask = np.isnan(a[0, :]) + a[1, nan_mask] = 255 + # 范围检查 (仅前 9 列对于 Layer) + ncols = min(a.shape[1], 9) + if ncols > 0: + range_mask = (a[0, :ncols] < 0) | (a[0, :ncols] > 9999) + a[1, :ncols][range_mask] = 255 + return a + + OSC = _post_process(OSC) + ISO = _post_process(ISO) + ISC = _post_process(ISC) + WTH = _post_process(WTH) + + # DMCore, DMTotal, DMISO, DMISC 范围检查 + def _post_process_dm(arr): + a = arr.copy() + nan_mask = np.isnan(a[0, :]) + a[1, nan_mask] = 255 + range_mask = (a[0, :] < 0) | (a[0, :] > 9999) + a[1, range_mask] = 255 + return a + + DMTotal = _post_process_dm(DMTotal) + DMCore = _post_process_dm(DMCore) + DMISO = _post_process_dm(DMISO) + DMISC = _post_process_dm(DMISC) + + # BisecWTH 和 MinMaxAng + def _post_process_other(arr): + a = arr.copy() + nan_mask = np.isnan(a[0, :]) + a[1, nan_mask] = 255 + range_mask = (a[0, :] < 0) | (a[0, :] > 9999) + a[1, range_mask] = 255 + return a + + BisecWTH = _post_process_other(BisecWTH) + MinMaxAng = _post_process_other(MinMaxAng) + + + return OSC, ISO, ISC, WTH, DMTotal, DMCore, DMISO, DMISC, BisecWTH, MinMaxAng diff --git a/algorithm/curve_fit_utils.py b/algorithm/curve_fit_utils.py new file mode 100644 index 0000000..867a18a --- /dev/null +++ b/algorithm/curve_fit_utils.py @@ -0,0 +1,1488 @@ +import numpy as np +from scipy.optimize import least_squares + +try: + from .math_utils import ind, polyfit2 + from .geometry_utils import strng2 + from .signal_utils import filter2k3 +except ImportError: + from math_utils import ind, polyfit2 + from geometry_utils import strng2 + from signal_utils import filter2k3 + + +def _simple_lm(fun, x0, ftol=1e-6, xtol=1e-6, max_nfev=400): + x = np.asarray(x0, dtype=np.float64).copy() + n = len(x) + lambd = 1e-3 + nu = 2.0 + + residuals = fun(x) + cost = np.sum(residuals ** 2) + + nfev = 1 + success = False + + while nfev < max_nfev: + eps = 1e-8 + J = np.zeros((len(residuals), n)) + for j in range(n): + dx_eps = np.zeros(n) + dx_eps[j] = eps * max(1.0, abs(x[j])) + residuals_plus = fun(x + dx_eps) + J[:, j] = (residuals_plus - residuals) / dx_eps[j] + nfev += 1 + if nfev >= max_nfev: + break + + if nfev >= max_nfev: + break + + JtJ = J.T @ J + Jtr = J.T @ residuals + + for _ in range(10): + diag = np.diag(JtJ) + lambd + A = JtJ + lambd * np.eye(n) + try: + delta = np.linalg.solve(A, Jtr) + except np.linalg.LinAlgError: + delta = np.linalg.lstsq(A, Jtr, rcond=None)[0] + + x_new = x - delta + residuals_new = fun(x_new) + cost_new = np.sum(residuals_new ** 2) + nfev += 1 + + if cost_new < cost: + rho = (cost - cost_new) / (delta @ (lambd * delta + Jtr) + 1e-10) + if rho > 0.75: + lambd = lambd / 3.0 + elif rho < 0.25: + lambd = lambd * 2.0 + + if np.max(np.abs(delta)) < xtol: + success = True + x = x_new + residuals = residuals_new + cost = cost_new + break + + if abs(cost - cost_new) < ftol: + success = True + x = x_new + residuals = residuals_new + cost = cost_new + break + + x = x_new + residuals = residuals_new + cost = cost_new + break + else: + lambd = lambd * nu + nu = nu * 2.0 + + else: + break + + return x, cost, success, nfev + + +def attcalcx0(x, y, x0, x0r, right): + att0 = 0.0 + x = np.asarray(x, dtype=np.float64) + y = np.asarray(y, dtype=np.float64) + y = np.where(y <= 0, 1e-6, y) + + N = len(x) + if N > 4: + dx = (x[N - 1] - x[0]) / (N - 1) + + if not right: + xleft = x0 + xright = x[N - 1] + else: + xleft = x[0] + xright = x0r + + if (xright - xleft) > dx: + ll = int(ind(xleft, dx, x[0], N)) + rr = int(ind(xright, dx, x[0], N)) + xt = x[ll - 1:rr] + yt = y[ll - 1:rr] + s0 = strng2(xt, x0, x0r) + min_s0 = 0.01 * (x0r - x0) if (x0r - x0) > 0 else 0.01 + indvek = np.where(s0 > min_s0)[0] + if len(indvek) > 0: + att0 = -np.mean(np.log(yt[indvek]) / s0[indvek]) + if np.isnan(att0) or np.isinf(att0): + att0 = 0.0 + + return att0 + + +def attcalcx1(x, y, x0, x0r, x1, x1r, right): + att0 = 0.0 + att1 = 0.0 + x = np.asarray(x, dtype=np.float64) + y = np.asarray(y, dtype=np.float64).copy() + + y[y <= 0] = 1e-6 + + N = len(x) + if N > 4: + dx = (x[N - 1] - x[0]) / (N - 1) + + if not right: + xleft = x[0] + xright = x1 + else: + xleft = x1r + xright = x[N - 1] + + if (xright - xleft) > dx: + ll = int(ind(xleft, dx, x[0], N)) + rr = int(ind(xright, dx, x[0], N)) + xt = x[ll - 1:rr] + yt = y[ll - 1:rr] + s0 = strng2(xt, x0, x0r) + min_s0 = 0.01 * (x0r - x0) if (x0r - x0) > 0 else 0.01 + indvek = np.where(s0 > min_s0)[0] + if len(indvek) > 0: + att0 = -np.mean(np.log(yt[indvek]) / s0[indvek]) + if np.isnan(att0) or np.isinf(att0): + att0 = 0.0 + + if not right: + xleft = x1 + dx + xright = x[N - 1] + else: + xleft = x[0] + xright = x1r - dx + + if (((xright - xleft) > dx) and (xright > x1) and (xright < x1r) and + (xleft > x1) and (xleft < x1r) and (att0 > 0)): + ll = int(ind(xleft, dx, x[0], N)) + rr = int(ind(xright, dx, x[0], N)) + xt = x[ll - 1:rr] + yt = y[ll - 1:rr] + s0 = strng2(xt, x0, x0r) + s1 = strng2(xt, x1, x1r) + min_s1 = 0.01 * (x1r - x1) if (x1r - x1) > 0 else 0.01 + indvek = np.where(s1 > min_s1)[0] + if len(indvek) > 0: + att1 = np.mean((-np.log(yt[indvek]) - att0 * (s0[indvek] - s1[indvek])) / s1[indvek]) + if np.isnan(att1) or np.isinf(att1): + att1 = 0.0 + + return att0, att1 + + +def resfail(resnorm, lyt, meanyt): + return np.sqrt(resnorm / lyt) / meanyt + + +def edge_error2(calcval, exitflag, resnorm, avgval, startalpha0, minxt, maxxt, + minalpha0, maxalpha0, mincontr, maxcontr, contrsign, resmax, + diffxt1, diffxt2, lengthxt): + errorl = np.zeros(2, dtype=np.float64) + + if exitflag < 0: + errorl[0] = 51 + else: + if (calcval['x'] < (minxt + diffxt1)) or (calcval['x'] > (maxxt - diffxt1)): + errorl[1] = 47 + if (calcval['x'] < (minxt + diffxt2)) or (calcval['x'] > (maxxt - diffxt2)): + errorl[0] = 47 + if calcval['alpha0'] < minalpha0: + errorl[0] = 52 + if calcval['alpha0'] > maxalpha0: + errorl[0] = 53 + if abs(calcval['alpha1'] - calcval['alpha0']) < mincontr: + errorl[0] = 54 + if (((calcval['alpha1'] - calcval['alpha0']) < 0) and (contrsign == 1)) or \ + (((calcval['alpha1'] - calcval['alpha0']) > 0) and (contrsign == -1)): + errorl[0] = 56 + + relfail = resfail(resnorm, lengthxt, avgval) + if relfail > resmax: + errorl[0] = 57 + if (calcval['x'] < minxt) or (calcval['x'] > maxxt): + errorl[0] = 46 + + return errorl + + +def x0fun(para_dyn, para_static, x, yactual=None): + x = np.asarray(x, dtype=np.float64) + + x0 = para_dyn[0] + x0r = para_dyn[1] + alpha0 = para_dyn[2] + + x3 = None + x3r = None + alpha1 = None + beta1 = None + if para_static.get('xlr41det', 0) == 1: + x3 = para_dyn[3] + x3r = para_dyn[4] + elif para_static.get('xlr41det', 0) == 2: + x3 = para_dyn[3] + x3r = para_dyn[4] + alpha1 = para_dyn[5] + beta1 = para_static.get('beta1', 0) + + filtactive = para_static.get('filtactive', 0) + # 读取原始mm值,避免引用传递导致的重复转换 + filtlength = para_static.get('filtlength_mm', para_static.get('filtlength', 0)) + + xout = None + + if yactual is not None: + yactual = np.asarray(yactual, dtype=np.float64) + minx = np.min(x) + maxx = np.max(x) + dx = (maxx - minx) / (len(x) - 1) + if (x0 > minx) and (x0 < maxx): + stopind = int(ind((x0 - 2 * filtlength), dx, x[0], len(x))) + I0 = np.mean(yactual[0:stopind]) + elif (x0r > minx) and (x0r < maxx): + startind = int(ind((x0r + 2 * filtlength), dx, x[0], len(x))) + I0 = np.mean(yactual[startind - 1:]) + else: + I0 = 1.0 + + minI0 = 0.93 + maxI0 = 1.07 + if I0 > maxI0: + I0 = maxI0 + elif I0 < minI0: + I0 = minI0 + else: + I0 = para_static.get('I0', 1.0) + + xlr41det = para_static.get('xlr41det', 0) + if xlr41det == 0: + s1 = strng2(x, x0, x0r, 1) + y = I0 * np.exp(-(alpha0 * s1)) + elif xlr41det == 1: + s1 = strng2(x, x0, x0r, 1) + s3 = strng2(x, x3, x3r, 1) + y = I0 * np.exp(-(alpha0 * (s1 - s3))) + elif xlr41det == 2: + s1 = strng2(x, x0, x0r, 1) + s3 = strng2(x, x3, x3r, 1) + y = I0 * np.exp(-(alpha0 * (s1 - s3) + beta1 * ((s1 - s3) ** 2) + alpha1 * s3)) + else: + y = np.zeros_like(x) + + N2 = 0 + if filtactive: + if para_static.get('unsharpness', 0) == 1: + from .filtering_utils import smooth + filtvek = smooth(para_static.get('a1', 1), para_static.get('a2', 1), + para_static.get('a3', 1), para_static.get('filtkoff', 1)) + y, N2 = filter2k3(filtvek, y, 1) + else: + dx = x[1] - x[0] + filtlen = int(np.round(filtlength / dx)) + if filtlen % 2 == 0: + filtlen = filtlen + 1 + y, N2 = filter2k3((1.0 / filtlen) * np.ones(filtlen), y) + + startind = N2 + stopind = len(x) - N2 + + if para_static.get('lsqn', 0) == 1: + if yactual is not None: + y = y[startind:stopind] - yactual[startind:stopind] + else: + xout = x[startind:stopind] + y = y[startind:stopind] + + return y, I0, xout, N2 + + +def x1fun3setup(para_static, alpha0, alpha1): + mode = para_static.get('mode', 0) + + if mode == 0: + para_dyn = np.array([alpha0, para_static['x1'], para_static['x1r'], alpha1], dtype=np.float64) + elif mode == 1: + para_dyn = np.array([alpha0, para_static['x1'], para_static['x1r']], dtype=np.float64) + elif mode == 2: + para_dyn = np.array([alpha0, para_static['x1'], alpha1], dtype=np.float64) + elif mode == 3: + para_dyn = np.array([alpha0, para_static['x1r'], alpha1], dtype=np.float64) + elif mode == 4: + para_dyn = np.array([alpha0, para_static['x1'], para_static['x1r'], + para_static['x0r'] - para_static['x0']], dtype=np.float64) + elif mode == 5 or mode == 6: + para_dyn = np.array([para_static['x1'], para_static['x1r']], dtype=np.float64) + elif mode == 7: + para_dyn = np.array([alpha0, para_static['x1'], para_static['x1r'], alpha1, + para_static.get('x2', 0), para_static.get('x2r', 0), 0.0], dtype=np.float64) + else: + para_dyn = np.array([alpha0, para_static['x1'], para_static['x1r'], alpha1], dtype=np.float64) + + return para_dyn + + +def x1fun3out(calcpara, para_static): + mode = para_static.get('mode', 0) + dataout = {} + + if mode == 0: + dataout['alpha0'] = calcpara[0] + dataout['x1'] = calcpara[1] + dataout['x1r'] = calcpara[2] + dataout['alpha1'] = calcpara[3] + elif mode == 1: + dataout['alpha0'] = calcpara[0] + dataout['x1'] = calcpara[1] + dataout['x1r'] = calcpara[2] + dataout['alpha1'] = 0.0 + elif mode == 2: + dataout['alpha0'] = calcpara[0] + dataout['x1'] = calcpara[1] + dataout['alpha1'] = calcpara[2] + dataout['x1r'] = para_static.get('x1r', 0) + elif mode == 3: + dataout['alpha0'] = calcpara[0] + dataout['x1r'] = calcpara[1] + dataout['alpha1'] = calcpara[2] + dataout['x1'] = para_static.get('x1', 0) + elif mode == 4: + dataout['alpha0'] = calcpara[0] + dataout['x1'] = calcpara[1] + dataout['x1r'] = calcpara[2] + dataout['alpha1'] = 0.0 + elif mode == 5: + reg_sub = para_static.get('reg_sub', {}) + dataout['alpha0'] = reg_sub.get('alpha0', 0) + dataout['x1'] = calcpara[0] + dataout['x1r'] = calcpara[1] + dataout['alpha1'] = 0.0 + elif mode == 6: + reg_sub = para_static.get('reg_sub', {}) + dataout['alpha0'] = reg_sub.get('alpha0', 0) + dataout['x1'] = calcpara[0] + dataout['x1r'] = calcpara[1] + dataout['alpha1'] = reg_sub.get('alpha1', 0) + elif mode == 7: + dataout['alpha0'] = calcpara[0] + dataout['x1'] = calcpara[1] + dataout['x1r'] = calcpara[2] + dataout['alpha1'] = calcpara[3] + else: + dataout['alpha0'] = 0.0 + dataout['x1'] = 0.0 + dataout['x1r'] = 0.0 + dataout['alpha1'] = 0.0 + + return dataout + + +def x0_x0r_reg_sub(x, IN, klevel=0, Anzpara=0): + x = np.asarray(x, dtype=np.float64) + IN = np.asarray(IN, dtype=np.float64) + + trueind = np.where(IN < 1)[0] + x = x[trueind] + IN = IN[trueind] + x0 = 0.0 + x0r = 0.0 + alpha0 = 0.0 + errorl = np.zeros(2, dtype=np.float64) + P = np.zeros(3, dtype=np.float64) + + if len(IN) > 3: + IN2 = (np.log(IN)) ** 2 + P = polyfit2(x, IN2, 2) + + A = P[1] / P[0] + B = (P[1] ** 2 / (4 * P[0] ** 2)) - (P[2] / P[0]) + if (B > 0) and (-P[0] > 0): + x0 = -0.5 * A - np.sqrt(B) + alpha0 = 0.5 * np.sqrt(-P[0]) + x0r = -(x0 + A) + if alpha0 < klevel: + errorl[0] = 11 + else: + errorl[0] = 58 + else: + errorl[0] = 58 + + return x0, x0r, alpha0, errorl, P + + +def x1fun3(para_dyn, para_static, x, yactual=None): + x = np.asarray(x, dtype=np.float64) + + regsubres = {} + xout = None + + mode = para_static.get('mode', 0) + + if mode == 0: + alpha0 = para_dyn[0] + x1 = para_dyn[1] + x1r = para_dyn[2] + alpha1 = para_dyn[3] + x0 = para_static['x0'] + x0r = para_static['x0r'] + elif mode == 1: + alpha0 = para_dyn[0] + x1 = para_dyn[1] + x1r = para_dyn[2] + x0 = para_static['x0'] + x0r = para_static['x0r'] + alpha1 = 0.0 + elif mode == 2: + alpha0 = para_dyn[0] + x1 = para_dyn[1] + alpha1 = para_dyn[2] + x1r = para_static['x1r'] + x0 = para_static['x0'] + x0r = para_static['x0r'] + elif mode == 3: + alpha0 = para_dyn[0] + x1r = para_dyn[1] + alpha1 = para_dyn[2] + x1 = para_static['x1'] + x0 = para_static['x0'] + x0r = para_static['x0r'] + elif mode == 4: + alpha0 = para_dyn[0] + x1 = para_dyn[1] + x1r = para_dyn[2] + d0 = para_dyn[3] + x0 = 0.5 * (para_static['x0'] + para_static['x0r']) - 0.5 * d0 + x0r = x0 + d0 + alpha1 = 0.0 + elif mode == 5: + x1 = para_dyn[0] + x1r = para_dyn[1] + alpha1 = 0.0 + + if yactual is not None: + yactual = np.asarray(yactual, dtype=np.float64) + minx = np.min(x) + maxx = np.max(x) + dx = (maxx - minx) / (len(x) - 1) + xmitt = 0.5 * (para_static['x0'] + para_static['x0r']) + if (x1 > minx) and (x1 <= maxx): + startind = 0 + stopind = int(ind((x1 - 0.5 * para_static.get('filtlength', 0)), dx, x[0], len(x))) + xright = x[stopind - 1] + 2 * (xmitt - x[stopind - 1]) + xreg = np.concatenate([x[startind:stopind], [xright]]) + yreg = np.concatenate([yactual[startind:stopind], [yactual[stopind - 1]]]) + rangeerr = 0 + elif (x1r > minx) and (x1r <= maxx): + startind = int(ind((x1r + 0.5 * para_static.get('filtlength', 0)), dx, x[0], len(x))) + stopind = len(x) + xleft = x[startind - 1] - 2 * (x[startind - 1] - xmitt) + xreg = np.concatenate([[xleft], x[startind - 1:stopind]]) + yreg = np.concatenate([[yactual[startind - 1]], yactual[startind - 1:stopind]]) + rangeerr = 0 + else: + rangeerr = 1 + xreg = np.array([]) + yreg = np.array([]) + + if not rangeerr: + x0, x0r, alpha0, _, _ = x0_x0r_reg_sub(xreg, yreg, 0, 0) + else: + x0 = 0.0 + x0r = 0.0 + alpha0 = 0.0 + + if (x0 == 0) or rangeerr: + x0 = para_static['x0'] + x0r = para_static['x0r'] + alpha0 = 0.0 + + regsubres['x0'] = x0 + regsubres['x0r'] = x0r + regsubres['alpha0'] = alpha0 + else: + x0 = para_static.get('reg_sub', {}).get('x0', para_static['x0']) + x0r = para_static.get('reg_sub', {}).get('x0r', para_static['x0r']) + alpha0 = para_static.get('reg_sub', {}).get('alpha0', 0.0) + + elif mode == 6: + x1 = para_dyn[0] + x1r = para_dyn[1] + + if yactual is not None: + yactual = np.asarray(yactual, dtype=np.float64) + minx = np.min(x) + maxx = np.max(x) + dx = (maxx - minx) / (len(x) - 1) + xmitt = 0.5 * (para_static['x0'] + para_static['x0r']) + if (x1 > minx) and (x1 <= maxx): + startind = 0 + stopind = int(ind((x1 - 0.5 * para_static.get('filtlength', 0)), dx, x[0], len(x))) + xright = x[stopind - 1] + 2 * (xmitt - x[stopind - 1]) + xreg = np.concatenate([x[startind:stopind], [xright]]) + yreg = np.concatenate([yactual[startind:stopind], [yactual[stopind - 1]]]) + rangeerr = 0 + x1_inRange = 1 + elif (x1r > minx) and (x1r <= maxx): + startind = int(ind((x1r + 0.5 * para_static.get('filtlength', 0)), dx, x[0], len(x))) + stopind = len(x) + xleft = x[startind - 1] - 2 * (x[startind - 1] - xmitt) + xreg = np.concatenate([[xleft], x[startind - 1:stopind]]) + yreg = np.concatenate([[yactual[startind - 1]], yactual[startind - 1:stopind]]) + rangeerr = 0 + x1_inRange = 0 + else: + rangeerr = 1 + x1_inRange = 0 + xreg = np.array([]) + yreg = np.array([]) + + if not rangeerr: + x0, x0r, alpha0, _, _ = x0_x0r_reg_sub(xreg, yreg, 0, 0) + else: + x0 = 0.0 + x0r = 0.0 + alpha0 = 0.0 + + alpha1 = 0.0 + if (not rangeerr) and not (x0 == 0): + if x1_inRange: + startind = int(ind((x1 + 2 * dx + 0.5 * para_static.get('filtlength', 0)), dx, x[0], len(x))) + stopx = min([maxx, (x1r - dx)]) + stopind = int(ind(stopx, dx, x[0], len(x))) + else: + startx = max([minx, (x1 + dx)]) + startind = int(ind(startx, dx, x[0], len(x))) + stopind = int(ind((x1r - 2 * dx - 0.5 * para_static.get('filtlength', 0)), dx, x[0], len(x))) + + xreg2 = x[startind - 1:stopind] + yreg2 = yactual[startind - 1:stopind] + if len(xreg2) > 0: + s1 = strng2(xreg2, x0, x0r, 1) + s2 = strng2(xreg2, x1, x1r, 1) + if (x1r > x1): + alpha1vek = -(np.log(yreg2) + alpha0 * (s1 - s2)) / s2 + valid = ~np.isinf(alpha1vek) + if np.any(valid): + alpha1 = np.mean(alpha1vek[valid]) + rangeerr2 = 0 + else: + alpha1 = 0.0 + rangeerr2 = 1 + else: + rangeerr2 = 1 + else: + rangeerr2 = 1 + + if (x0 == 0) or rangeerr: + x0 = para_static['x0'] + x0r = para_static['x0r'] + alpha0 = 0.0 + alpha1 = 0.0 + elif rangeerr2: + alpha1 = 0.0 + + regsubres['x0'] = x0 + regsubres['x0r'] = x0r + regsubres['alpha0'] = alpha0 + regsubres['alpha1'] = alpha1 + else: + x0 = para_static.get('reg_sub', {}).get('x0', para_static['x0']) + x0r = para_static.get('reg_sub', {}).get('x0r', para_static['x0r']) + alpha0 = para_static.get('reg_sub', {}).get('alpha0', 0.0) + alpha1 = para_static.get('reg_sub', {}).get('alpha1', 0.0) + + elif mode == 7: + alpha0 = para_dyn[0] + x1 = para_dyn[1] + x1r = para_dyn[2] + alpha1 = para_dyn[3] + x2 = para_dyn[4] + x2r = para_dyn[5] + alpha2 = para_dyn[6] + x0 = para_static['x0'] + x0r = para_static['x0r'] + else: + alpha0 = 0.0 + x1 = 0.0 + x1r = 0.0 + alpha1 = 0.0 + x0 = para_static.get('x0', 0) + x0r = para_static.get('x0r', 0) + + s1 = strng2(x, x0, x0r, 1) + s2 = strng2(x, x1, x1r, 1) + if mode in [1, 4, 5]: + y = np.exp(-(alpha0 * (s1 - s2))) + elif mode == 7: + s3 = strng2(x, x2, x2r, 1) + y = np.exp(-(alpha0 * (s1 - s2) + alpha1 * (s2 - s3) + alpha2 * s3)) + else: + y = np.exp(-(alpha0 * (s1 - s2) + alpha1 * s2)) + + N2 = 0 + if para_static.get('filtactive', 0): + dx = x[1] - x[0] + # 从para_static获取原始filtlength(mm),每次都重新转换为像素 + # 匹配MATLAB值传递语义:每次调用filtlength都是原始mm值 + filtlen_orig = para_static.get('filtlength_mm', para_static.get('filtlength', 0)) + filtlen = int(np.round(filtlen_orig / dx)) + if filtlen % 2 == 0: + filtlen = filtlen + 1 + y, N2 = filter2k3((1.0 / filtlen) * np.ones(filtlen), y) + + startind = N2 + stopind = len(x) - N2 + + if para_static.get('lsqn', 0) == 1: + if yactual is not None: + yactual = np.asarray(yactual, dtype=np.float64) + y = y[startind:stopind] - yactual[startind:stopind] + else: + xout = x[startind:stopind] + y = y[startind:stopind] + + return y, regsubres, xout + + +def x0_x0r_curvefit2(x, y, fun_startpara, fun_para_static, modul_para): + x = np.asarray(x, dtype=np.float64) + y = np.asarray(y, dtype=np.float64) + + # 保存原始filtlength(mm),避免Python引用传递导致的重复转换问题 + if 'filtlength_mm' not in fun_para_static: + fun_para_static['filtlength_mm'] = fun_para_static.get('filtlength', 0) + + dataout = { + 'left': { + 'pos': {'result': np.nan, 'start': np.nan, + 'limit': {'left': np.nan, 'right': np.nan}}, + 'att': {'outer': np.nan, 'inner': np.nan}, + 'error': np.array([np.nan, np.nan]) + }, + 'right': { + 'pos': {'result': np.nan, 'start': np.nan, + 'limit': {'left': np.nan, 'right': np.nan}}, + 'att': {'outer': np.nan, 'inner': np.nan}, + 'error': np.array([np.nan, np.nan]) + } + } + + errorlevel = np.zeros((2, 2), dtype=np.float64) + calcpara = np.zeros(6, dtype=np.float64) + calcpara1 = np.zeros(6, dtype=np.float64) + calcpara2 = np.zeros(6, dtype=np.float64) + + dx = x[1] - x[0] + diffxt1 = 0.2 + diffxt2 = 0.10 + + tol_fun = modul_para.get('TolFun', 1e-6) + tol_x = modul_para.get('TolX', 1e-6) + max_iter = int(modul_para.get('MaxFunEvals', 400)) + + if 'xlr41det' not in fun_para_static: + fun_para_static['xlr41det'] = 0 + if len(fun_startpara) < 5: + fun_para_static['xlr41det'] = 0 + + N = len(x) + + leftcut = fun_startpara[0] - modul_para['range_outer'] - fun_para_static['filtlength'] + if leftcut < (modul_para['x0limit_l'] - fun_para_static['filtlength']): + leftcut = modul_para['x0limit_l'] - fun_para_static['filtlength'] + + if fun_para_static['xlr41det']: + rightcut = fun_startpara[3] + modul_para['range_inner'] + fun_para_static['filtlength'] + else: + rightcut = fun_startpara[0] + modul_para['range_inner'] + fun_para_static['filtlength'] + if rightcut > (modul_para['x0limit_r'] + fun_para_static['filtlength']): + rightcut = modul_para['x0limit_r'] + fun_para_static['filtlength'] + + ll = int(ind(leftcut, dx, 0, N)) + rr = int(ind(rightcut, dx, 0, N)) + xt = x[ll - 1:rr] + yt = y[ll - 1:rr] + + if len(xt) > 10: + if fun_para_static['xlr41det'] != 2: + fun_startpara[2] = attcalcx0(xt, yt, fun_startpara[0], fun_startpara[1], 0) + + fun_para_static['lsqn'] = 1 + + try: + result = least_squares(lambda p: x0fun(p, fun_para_static, xt, yt)[0], + fun_startpara, method='lm', + ftol=tol_fun, xtol=tol_x, max_nfev=max_iter) + calcpara1 = result.x + resnorm = np.sum(result.fun ** 2) + exitflag = 1 if result.success else -1 + except Exception as e: + import traceback + traceback.print_exc() + calcpara1 = fun_startpara + resnorm = 1e10 + exitflag = -1 + + calcval = {'alpha0': 0, 'alpha1': calcpara1[2], 'x': calcpara1[0]} + dataout['left']['pos']['result'] = calcval['x'] + dataout['left']['att']['outer'] = calcval['alpha0'] + dataout['left']['att']['inner'] = calcval['alpha1'] + + minxt = np.min(xt) + maxxt = np.max(xt) + errorlevel[:, 0] = edge_error2(calcval, exitflag, resnorm, np.mean(yt), 0, + minxt, maxxt, modul_para['minatt1'], modul_para['maxatt1'], + modul_para['mincontr'], modul_para['maxcontr'], 1, + modul_para['resmax'], diffxt1, diffxt2, len(yt)) + else: + errorlevel[0, 0] = 50 + + if fun_para_static['xlr41det'] == 1: + leftcut = fun_startpara[4] - modul_para['range_inner'] - fun_para_static['filtlength'] + else: + leftcut = fun_startpara[1] - modul_para['range_inner'] - fun_para_static['filtlength'] + if leftcut < (modul_para['x0rlimit_l'] - fun_para_static['filtlength']): + leftcut = modul_para['x0rlimit_l'] - fun_para_static['filtlength'] + + rightcut = fun_startpara[1] + modul_para['range_outer'] + fun_para_static['filtlength'] + if rightcut > (modul_para['x0rlimit_r'] + fun_para_static['filtlength']): + rightcut = modul_para['x0rlimit_r'] + fun_para_static['filtlength'] + + ll = int(ind(leftcut, dx, 0, N)) + rr = int(ind(rightcut, dx, 0, N)) + xt = x[ll - 1:rr] + yt = y[ll - 1:rr] + + + if len(xt) > 10: + if fun_para_static['xlr41det'] != 2: + fun_startpara[2] = attcalcx0(xt, yt, fun_startpara[0], fun_startpara[1], 1) + + fun_para_static['lsqn'] = 1 + try: + result = least_squares(lambda p: x0fun(p, fun_para_static, xt, yt)[0], + fun_startpara, method='lm', + ftol=tol_fun, xtol=tol_x, max_nfev=max_iter) + calcpara2 = result.x + resnorm = np.sum(result.fun ** 2) + exitflag = 1 if result.success else -1 + except Exception as e: + import traceback + traceback.print_exc() + calcpara2 = fun_startpara + resnorm = 1e10 + exitflag = -1 + + calcval = {'alpha0': 0, 'alpha1': calcpara2[2], 'x': calcpara2[1]} + dataout['right']['pos']['result'] = calcval['x'] + dataout['right']['att']['outer'] = calcval['alpha0'] + dataout['right']['att']['inner'] = calcval['alpha1'] + + minxt = np.min(xt) + maxxt = np.max(xt) + errorlevel[:, 1] = edge_error2(calcval, exitflag, resnorm, np.mean(yt), 0, + minxt, maxxt, modul_para['minatt1'], modul_para['maxatt1'], + modul_para['mincontr'], modul_para['maxcontr'], 1, + modul_para['resmax'], diffxt1, diffxt2, len(yt)) + else: + errorlevel[0, 1] = 50 + + if (errorlevel[0, 0] == 0) and (errorlevel[0, 1] == 0): + calcpara[0] = calcpara1[0] + calcpara[1] = calcpara2[1] + calcpara[2] = 0.5 * (calcpara1[2] + calcpara2[2]) + elif errorlevel[0, 0] == 0: + calcpara[0] = calcpara1[0] + calcpara[2] = calcpara1[2] + elif errorlevel[0, 1] == 0: + calcpara[1] = calcpara2[1] + calcpara[2] = calcpara2[2] + + if fun_para_static['xlr41det'] == 1: + calcpara = np.resize(calcpara, 6) + calcpara[3] = calcpara1[3] + calcpara[4] = calcpara2[4] + elif fun_para_static['xlr41det'] == 2: + calcpara = np.resize(calcpara, 6) + calcpara[3] = calcpara1[3] + calcpara[4] = calcpara2[4] + if len(calcpara1) > 5 and len(calcpara2) > 5: + calcpara[5] = 0.5 * (calcpara1[5] + calcpara2[5]) + + return calcpara, errorlevel, dataout + + +def x1_x1r_curvefit3(x, y, fun_para_static, modul_para): + x = np.asarray(x, dtype=np.float64) + y = np.asarray(y, dtype=np.float64) + + # 保存原始filtlength(mm),避免Python引用传递导致的重复转换问题 + if 'filtlength_mm' not in fun_para_static: + fun_para_static['filtlength_mm'] = fun_para_static.get('filtlength', 0) + + errorlevel = np.zeros((2, 2), dtype=np.float64) + calcpara = np.zeros(4, dtype=np.float64) + dataout = { + 'alpha0': 0, 'x1': 0, 'x1r': 0, 'alpha1': 0, + 'left': { + 'pos': {'result': np.nan, 'start': np.nan, + 'limit': {'left': np.nan, 'right': np.nan}}, + 'att': {'outer': np.nan, 'inner': np.nan}, + 'error': np.array([np.nan, np.nan]) + }, + 'right': { + 'pos': {'result': np.nan, 'start': np.nan, + 'limit': {'left': np.nan, 'right': np.nan}}, + 'att': {'outer': np.nan, 'inner': np.nan}, + 'error': np.array([np.nan, np.nan]) + } + } + + dx = x[1] - x[0] + N = len(x) + + tol_fun = modul_para.get('TolFun', 1e-6) + tol_x = modul_para.get('TolX', 1e-6) + max_iter = int(modul_para.get('MaxFunEvals', 400)) + contrsign = modul_para.get('contrsign', 0) + + leftcut = fun_para_static['x1'] - modul_para['range_outer'] - fun_para_static['filtlength'] + if leftcut < (modul_para['x1limit_l'] - fun_para_static['filtlength']): + leftcut = modul_para['x1limit_l'] - fun_para_static['filtlength'] + rightcut = fun_para_static['x1'] + modul_para['range_inner'] + fun_para_static['filtlength'] + if rightcut > modul_para['x1limit_r'] + fun_para_static['filtlength']: + rightcut = modul_para['x1limit_r'] + fun_para_static['filtlength'] + + + ll = int(ind(leftcut, dx, 0, N)) + rr = int(ind(rightcut, dx, 0, N)) + xt = x[ll - 1:rr] + yt = y[ll - 1:rr] + + dataoutleft = None + if len(xt) > 10: + att0, att1 = attcalcx1(xt, yt, fun_para_static['x0'], fun_para_static['x0r'], + fun_para_static['x1'], fun_para_static['x1r'], 0) + + fun_startpara = x1fun3setup(fun_para_static, att0, att1) + + fun_para_static['lsqn'] = 1 + + try: + result = least_squares(lambda p: x1fun3(p, fun_para_static, xt, yt)[0], + fun_startpara, method='lm', + ftol=tol_fun, xtol=tol_x, max_nfev=max_iter) + calcpara_left = result.x + resnorm = np.sum(result.fun ** 2) + exitflag = 1 if result.success else -1 + except Exception: + calcpara_left = fun_startpara + resnorm = 1e10 + exitflag = -1 + + _, fun_para_static['reg_sub'], _ = x1fun3(calcpara_left, fun_para_static, xt, yt) + + dataoutleft = x1fun3out(calcpara_left, fun_para_static) + + calcval = {'alpha0': dataoutleft['alpha0'], 'alpha1': dataoutleft['alpha1'], + 'x': dataoutleft['x1']} + dataout['left']['pos']['result'] = calcval['x'] + dataout['left']['att']['inner'] = calcval['alpha1'] + dataout['left']['att']['outer'] = calcval['alpha0'] + + minxt = np.min(xt) + maxxt = np.max(xt) + errorlevel[:, 0] = edge_error2(calcval, exitflag, resnorm, np.mean(yt), att0, + minxt, maxxt, modul_para['minatt1'], modul_para['maxatt1'], + modul_para['mincontr'], modul_para['maxcontr'], contrsign, + modul_para['resmax'], 0.1 * (maxxt - minxt), + 0.05 * (maxxt - minxt), len(yt)) + else: + errorlevel[0, 0] = 50 + + if fun_para_static.get('mode', 0) == 2: + fun_para_static['mode'] = 3 + + leftcut = fun_para_static['x1r'] - modul_para['range_inner'] - fun_para_static['filtlength'] + if leftcut < (modul_para['x1rlimit_l'] - fun_para_static['filtlength']): + leftcut = modul_para['x1rlimit_l'] - fun_para_static['filtlength'] + rightcut = fun_para_static['x1r'] + modul_para['range_outer'] + fun_para_static['filtlength'] + if rightcut > modul_para['x1rlimit_r'] + fun_para_static['filtlength']: + rightcut = modul_para['x1rlimit_r'] + fun_para_static['filtlength'] + + + ll = int(ind(leftcut, dx, 0, N)) + rr = int(ind(rightcut, dx, 0, N)) + xt = x[ll - 1:rr] + yt = y[ll - 1:rr] + + dataoutright = None + if len(xt) > 10: + att0, att1 = attcalcx1(xt, yt, fun_para_static['x0'], fun_para_static['x0r'], + fun_para_static['x1'], fun_para_static['x1r'], 1) + + fun_startpara = x1fun3setup(fun_para_static, att0, att1) + + fun_para_static['lsqn'] = 1 + try: + result = least_squares(lambda p: x1fun3(p, fun_para_static, xt, yt)[0], + fun_startpara, method='lm', + ftol=tol_fun, xtol=tol_x, max_nfev=max_iter) + calcpara_right = result.x + resnorm = np.sum(result.fun ** 2) + exitflag = 1 if result.success else -1 + except Exception: + calcpara_right = fun_startpara + resnorm = 1e10 + exitflag = -1 + + _, fun_para_static['reg_sub'], _ = x1fun3(calcpara_right, fun_para_static, xt, yt) + + dataoutright = x1fun3out(calcpara_right, fun_para_static) + + calcval = {'alpha0': dataoutright['alpha0'], 'alpha1': dataoutright['alpha1'], + 'x': dataoutright['x1r']} + dataout['right']['pos']['result'] = calcval['x'] + dataout['right']['att']['inner'] = calcval['alpha1'] + dataout['right']['att']['outer'] = calcval['alpha0'] + + minxt = np.min(xt) + maxxt = np.max(xt) + errorlevel[:, 1] = edge_error2(calcval, exitflag, resnorm, np.mean(yt), att0, + minxt, maxxt, modul_para['minatt1'], modul_para['maxatt1'], + modul_para['mincontr'], modul_para['maxcontr'], contrsign, + modul_para['resmax'], 0.1 * (maxxt - minxt), + 0.05 * (maxxt - minxt), len(yt)) + else: + errorlevel[0, 1] = 50 + + if (errorlevel[0, 0] == 0) and (errorlevel[0, 1] == 0): + dataout['alpha0'] = 0.5 * (dataoutleft['alpha0'] + dataoutright['alpha0']) + dataout['x1'] = dataoutleft['x1'] + dataout['x1r'] = dataoutright['x1r'] + dataout['alpha1'] = 0.5 * (dataoutleft['alpha1'] + dataoutright['alpha1']) + elif errorlevel[0, 0] == 0: + dataout['alpha0'] = dataoutleft['alpha0'] + dataout['x1'] = dataoutleft['x1'] + dataout['x1r'] = 0 + dataout['alpha1'] = dataoutleft['alpha1'] + elif errorlevel[0, 1] == 0: + dataout['alpha0'] = dataoutright['alpha0'] + dataout['x1'] = 0 + dataout['x1r'] = dataoutright['x1r'] + dataout['alpha1'] = dataoutright['alpha1'] + + return dataout, errorlevel + + +def circlepos(d, strng): + dist = 0.0 + if strng <= d: + dist = 0.5 * d + np.sqrt(0.25 * d ** 2 - (strng ** 2 / 4)) + dist = d - dist + return dist + + +def linreg(IN, Dl, Dr, dx, alles, xshift=0): + IN = np.asarray(IN, dtype=np.float64) + + ll = int(ind(Dl, dx, xshift)) + rr = int(ind(Dr, dx, xshift)) + rechtsx = (ll - 1) * dx + xshift + N = 2 * int(np.floor((rr - ll + 1) / 2)) + + Indiffv = np.zeros(N, dtype=np.float64) + x = np.zeros(N, dtype=np.float64) + Indiffv[0:N] = IN[np.arange(N) + ll - 1] + x[0:N] = np.arange(N) * dx + + A = polyfit2(x, Indiffv, 1) + + reg = np.zeros(N, dtype=np.float64) + Indiff = np.zeros(N, dtype=np.float64) + reg[0:N] = A[1] + A[0] * dx * np.arange(N) + Indiff[0:N] = Indiffv[0:N] - reg[0:N] + + Ref = Indiffv[int(N / 2)] + + return Indiff, rechtsx, Ref + + +def qcheck(Indiff, dx, Ref, klevel, Anzpara): + Indiff = np.asarray(Indiff, dtype=np.float64) + + errorlevel = np.zeros(2, dtype=np.float64) + N = len(Indiff) + + x = np.arange(N) * dx + A = polyfit2(x, Indiff, 2) + + Scheitelx = -A[1] / (2 * A[0]) + if Scheitelx > N * dx: + errorlevel[1] = 11 + if Scheitelx < 0: + errorlevel[1] = 11 + + if abs(A[0]) > 0: + Scheitely = A[2] - ((A[1] ** 2) / (4 * A[0])) + diff1 = abs(np.polyval(A, 0) - Scheitely) + diff2 = abs(np.polyval(A, N * dx) - Scheitely) + diff = (diff1 + diff2) / 2 + Kontrast = diff * 1 / (N * dx) + if Kontrast < klevel: + errorlevel[0] = 11 + else: + errorlevel[0] = 11 + + Maximum = (A[0] < 0) + + return errorlevel, Maximum + + +def _lfilter_fifi(b, a, x, zi): + b = np.asarray(b, dtype=np.float64) + a = np.asarray(a, dtype=np.float64) + x = np.asarray(x, dtype=np.float64) + y = np.zeros_like(x) + m = len(b) + n = len(a) + nfilt = max(m, n) + z = np.asarray(zi, dtype=np.float64).copy() + if len(z) < nfilt - 1: + z = np.pad(z, (0, nfilt - 1 - len(z))) + + for i in range(len(x)): + y[i] = b[0] * x[i] + z[0] + for j in range(1, nfilt): + bj = b[j] if j < m else 0.0 + aj = a[j] if j < n else 0.0 + if j < nfilt - 1: + z[j - 1] = bj * x[i] + z[j] - aj * y[i] + else: + z[j - 1] = bj * x[i] - aj * y[i] + + return y + + +def fifi(b, a, x): + b = np.asarray(b, dtype=np.float64).ravel() + a = np.asarray(a, dtype=np.float64).ravel() + x = np.asarray(x, dtype=np.float64) + + if len(b) == 0 or len(a) == 0 or len(x) == 0: + return np.array([]) + + orig_shape = x.shape + if x.ndim > 1: + x = x.ravel() + + len_x = len(x) + nb = len(b) + na = len(a) + nfilt = max(nb, na) + nfact = 3 * (nfilt - 1) + + if nb < nfilt: + b = np.pad(b, (0, nfilt - nb)) + if na < nfilt: + a = np.pad(a, (0, nfilt - na)) + + if nfilt > 1: + A_mat = np.eye(nfilt - 1) + col = -a[1:nfilt] + B_mat = np.zeros((nfilt - 1, nfilt - 1)) + B_mat[0, :] = col + if nfilt > 2: + B_mat[1:, :-1] = np.eye(nfilt - 2) + zi = np.linalg.solve(A_mat - B_mat, b[1:nfilt] - a[1:nfilt] * b[0]) + else: + zi = np.array([]) + + y_pad = np.concatenate([ + 2 * x[0] - x[nfact:0:-1], + x, + 2 * x[-1] - x[-2:-nfact - 2:-1] + ]) + + y1 = _lfilter_fifi(b, a, y_pad, zi * y_pad[0]) + y1 = y1[::-1] + y2 = _lfilter_fifi(b, a, y1, zi * y1[0]) + y2 = y2[::-1] + + y_out = y2[nfact:len_x + nfact] + + if len(orig_shape) > 1: + y_out = y_out.reshape(orig_shape) + + return y_out + + +def minmaxall(x): + x = np.asarray(x, dtype=np.float64).ravel() + + Nt = len(x) + inan = np.where(np.isnan(x))[0] + indx = np.arange(Nt) + if len(inan) > 0: + indx = np.delete(indx, inan) + x = np.delete(x, inan) + Nt = len(x) + + dx = np.diff(x) + b = (dx > 0).astype(int) + db = np.diff(b) + Ind_max = np.where(db == -1)[0] + 1 + Ind_min = np.where(db == 1)[0] + 1 + Val_max = x[Ind_max] + Val_min = x[Ind_min] + + Ind_max = Ind_max[np.argsort(-Ind_max)] + Val_max = Val_max[np.argsort(-Ind_max)] + Ind_min = Ind_min[np.argsort(-Ind_min)] + Val_min = Val_min[np.argsort(-Ind_min)] + + return Val_max, Ind_max, Val_min, Ind_min + + +def errfunc(errorl, errorlevel): + errorl = np.asarray(errorl, dtype=np.float64).ravel() + errorlevel = np.asarray(errorlevel, dtype=np.float64).ravel() + + if (errorlevel[0] == 0) and (errorl[0] > 0): + errorlevel[0] = errorl[0] + if len(errorlevel) > 1 and len(errorl) > 1: + if (errorlevel[1] == 0) and (errorl[1] > 0): + errorlevel[1] = errorl[1] + + return errorlevel + + +def lincorn(IN, conf): + IN = np.asarray(IN, dtype=np.float64) + conf = np.asarray(conf, dtype=np.float64) + + x = 0.0 + errorlevel = np.zeros(2, dtype=np.float64) + + Dl = conf[0] + Dr = conf[1] + Limitl = conf[2] + Limitr = conf[3] + fg1 = conf[4] + sym = conf[5] + Centerdiff = conf[6] + Itermax = conf[7] + dx = conf[8] + klevel = conf[9] + alles = conf[10] + fakfg = conf[11] + Maximumc = conf[12] + + right = None + if len(conf) >= 14: + right = conf[13] + + errorl = np.zeros(2, dtype=np.float64) + stop = 0 + loop = 0 + xalt = Dl + (Dr - Dl) / 2 + + fg = fg1 * fakfg + fgn = 2 * fg * dx + try: + from .filtering_utils import buttmat + except ImportError: + from filtering_utils import buttmat + BFilt1, AFilt1, _ = buttmat(fgn) + + fgn = 2 * fg1 * dx + BFilt2, AFilt2, _ = buttmat(fgn) + + ind_Dl = int(ind(Dl, dx, 0, len(IN))) + ind_Dr = int(ind(Dr, dx, 0, len(IN))) + range_ind = ind_Dr - ind_Dl + if range_ind > 5: + while stop == 0: + loop = loop + 1 + + Indiff, rechtsx, Ref = linreg(IN, Dl, Dr, dx, alles) + + err_q, Maximumq = qcheck(Indiff, dx, Ref, klevel, alles) + errorlevel[0] = err_q[0] + errorlevel[1] = err_q[1] + + if Maximumc == 2: + Maximum = Maximumq + else: + Maximum = Maximumc + + if loop == 1: + Maximumloop1 = Maximum + + if Maximumloop1 != Maximum: + errorl[0] = 13 + + if loop == 1: + AFilt = AFilt1 + BFilt = BFilt1 + else: + AFilt = AFilt2 + BFilt = BFilt2 + + fourindiff = fifi(BFilt, AFilt, Indiff) + + if right is not None: + Val_max, Ind_max, Val_min, Ind_min = minmaxall(fourindiff) + if len(Ind_max) > 0: + if right: + x = Ind_max[-1] + else: + x = Ind_max[0] + else: + try: + from .extremum_utils import minmax + except ImportError: + from extremum_utils import minmax + mwert, x = minmax(fourindiff, Maximum) + else: + try: + from .extremum_utils import minmax + except ImportError: + from extremum_utils import minmax + mwert, x = minmax(fourindiff, Maximum) + + x = (x - 1) * dx + rechtsx + + symnew = sym + if ((x - Limitl) < symnew): + symnew = x - Limitl + if ((Limitr - x) < symnew): + symnew = Limitr - x + + Dl = x - symnew + Dr = x + symnew + + if ((loop == Itermax) or ((abs(x - xalt) < Centerdiff) and (loop > 1))): + stop = 1 + if Maximumq != Maximum: + errorl[0] = 13 + + if (int(ind(Dr, dx, 0, len(IN))) - int(ind(Dl, dx, 0, len(IN)))) < 7: + stop = 1 + errorl[0] = 12 + + errorlevel = errfunc(errorl, errorlevel) + xalt = x + else: + errorlevel[0] = 12 + + return x, errorlevel + + +def x1_x1r_curvefit4(x, y, fun_para_static, modul_para): + x = np.asarray(x, dtype=np.float64) + y = np.asarray(y, dtype=np.float64) + + # 保存原始filtlength(mm),避免Python引用传递导致的重复转换问题 + if 'filtlength_mm' not in fun_para_static: + fun_para_static['filtlength_mm'] = fun_para_static.get('filtlength', 0) + + errorlevel = np.zeros((2, 2), dtype=np.float64) + calcpara = np.zeros(4, dtype=np.float64) + dataout = { + 'alpha0': 0, 'x1': 0, 'x1r': 0, 'alpha1': 0, + 'left': { + 'pos': {'result': np.nan, 'start': np.nan, + 'limit': {'left': np.nan, 'right': np.nan}}, + 'att': {'outer': np.nan, 'inner': np.nan}, + 'error': np.array([np.nan, np.nan]) + }, + 'right': { + 'pos': {'result': np.nan, 'start': np.nan, + 'limit': {'left': np.nan, 'right': np.nan}}, + 'att': {'outer': np.nan, 'inner': np.nan}, + 'error': np.array([np.nan, np.nan]) + } + } + resnorm = np.ones(2, dtype=np.float64) + + dx = x[1] - x[0] + N = len(x) + + tol_fun = modul_para.get('TolFun', 1e-6) + tol_x = modul_para.get('TolX', 1e-6) + max_iter = int(modul_para.get('MaxFunEvals', 400)) + contrsign = modul_para.get('contrsign', 0) + + leftcut = fun_para_static['x1'] - modul_para['range_outer'] - fun_para_static['filtlength'] + if leftcut < (modul_para['x1limit_l'] - fun_para_static['filtlength']): + leftcut = modul_para['x1limit_l'] - fun_para_static['filtlength'] + rightcut = fun_para_static['x1'] + modul_para['range_inner'] + fun_para_static['filtlength'] + if rightcut > modul_para['x1limit_r'] + fun_para_static['filtlength']: + rightcut = modul_para['x1limit_r'] + fun_para_static['filtlength'] + + + ll = int(ind(leftcut, dx, 0, N)) + rr = int(ind(rightcut, dx, 0, N)) + xt = x[ll - 1:rr] + yt = y[ll - 1:rr] + + dataoutleft = None + if len(xt) > 10: + att0, att1 = attcalcx1(xt, yt, fun_para_static['x0'], fun_para_static['x0r'], + fun_para_static['x1'], fun_para_static['x1r'], 0) + + fun_startpara = x1fun3setup(fun_para_static, att0, att1) + + fun_para_static['lsqn'] = 1 + + use_lm = (modul_para.get('LevenbergMarquardt', 0) or + fun_para_static.get('mode', 0) in (5, 6)) + opt_method = 'lm' if use_lm else 'trf' + + try: + result = least_squares(lambda p: x1fun3(p, fun_para_static, xt, yt)[0], + fun_startpara, method=opt_method, + ftol=tol_fun, xtol=tol_x, max_nfev=max_iter) + calcpara_left = result.x + resnorm[0] = np.sum(result.fun ** 2) + exitflag = 1 if result.success else -1 + except Exception as e: + calcpara_left = fun_startpara + resnorm[0] = 1e10 + exitflag = -1 + + _, fun_para_static['reg_sub'], _ = x1fun3(calcpara_left, fun_para_static, xt, yt) + + dataoutleft = x1fun3out(calcpara_left, fun_para_static) + + calcval = {'alpha0': dataoutleft['alpha0'], 'alpha1': dataoutleft['alpha1'], + 'x': dataoutleft['x1']} + dataout['left']['pos']['result'] = calcval['x'] + dataout['left']['att']['inner'] = calcval['alpha1'] + dataout['left']['att']['outer'] = calcval['alpha0'] + + minxt = np.min(xt) + maxxt = np.max(xt) + contrsign = modul_para.get('contrsign', 0) + errorlevel[:, 0] = edge_error2(calcval, exitflag, resnorm[0], np.mean(yt), att0, + minxt, maxxt, modul_para['minatt1'], modul_para['maxatt1'], + modul_para['mincontr'], modul_para['maxcontr'], contrsign, + modul_para['resmax'], 0.1 * (maxxt - minxt), + 0.05 * (maxxt - minxt), len(yt)) + + # 将左侧拟合得到的x1(即x2左侧)传递给右侧拟合作为固定值 + # 虽然MATLAB原代码未显式更新,但从物理意义和拟合精度考虑需要传递 + if errorlevel[0, 0] == 0 and 'x1' in dataoutleft and np.isfinite(dataoutleft['x1']): + fun_para_static['x1'] = dataoutleft['x1'] + else: + errorlevel[0, 0] = 50 + + if fun_para_static.get('mode', 0) == 2: + fun_para_static['mode'] = 3 + + leftcut = fun_para_static['x1r'] - modul_para['range_inner'] - fun_para_static['filtlength'] + if leftcut < (modul_para['x1rlimit_l'] - fun_para_static['filtlength']): + leftcut = modul_para['x1rlimit_l'] - fun_para_static['filtlength'] + rightcut = fun_para_static['x1r'] + modul_para['range_outer'] + fun_para_static['filtlength'] + if rightcut > modul_para['x1rlimit_r'] + fun_para_static['filtlength']: + rightcut = modul_para['x1rlimit_r'] + fun_para_static['filtlength'] + + + ll = int(ind(leftcut, dx, 0, N)) + rr = int(ind(rightcut, dx, 0, N)) + xt = x[ll - 1:rr] + yt = y[ll - 1:rr] + + dataoutright = None + if len(xt) > 10: + att0, att1 = attcalcx1(xt, yt, fun_para_static['x0'], fun_para_static['x0r'], + fun_para_static['x1'], fun_para_static['x1r'], 1) + + fun_startpara = x1fun3setup(fun_para_static, att0, att1) + + fun_para_static['lsqn'] = 1 + + use_lm_r = (modul_para.get('LevenbergMarquardt', 0) or + fun_para_static.get('mode', 0) in (5, 6)) + opt_method_r = 'lm' if use_lm_r else 'trf' + + try: + result = least_squares(lambda p: x1fun3(p, fun_para_static, xt, yt)[0], + fun_startpara, method=opt_method_r, + ftol=tol_fun, xtol=tol_x, max_nfev=max_iter) + calcpara_right = result.x + resnorm[1] = np.sum(result.fun ** 2) + exitflag = 1 if result.success else -1 + except Exception as e: + calcpara_right = fun_startpara + resnorm[1] = 1e10 + exitflag = -1 + + _, fun_para_static['reg_sub'], _ = x1fun3(calcpara_right, fun_para_static, xt, yt) + + dataoutright = x1fun3out(calcpara_right, fun_para_static) + + calcval = {'alpha0': dataoutright['alpha0'], 'alpha1': dataoutright['alpha1'], + 'x': dataoutright['x1r']} + dataout['right']['pos']['result'] = calcval['x'] + dataout['right']['att']['inner'] = calcval['alpha1'] + dataout['right']['att']['outer'] = calcval['alpha0'] + + minxt = np.min(xt) + maxxt = np.max(xt) + errorlevel[:, 1] = edge_error2(calcval, exitflag, resnorm[1], np.mean(yt), att0, + minxt, maxxt, modul_para['minatt1'], modul_para['maxatt1'], + modul_para['mincontr'], modul_para['maxcontr'], contrsign, + modul_para['resmax'], 0.1 * (maxxt - minxt), + 0.05 * (maxxt - minxt), len(yt)) + else: + errorlevel[0, 1] = 50 + + if (errorlevel[0, 0] == 0) and (errorlevel[0, 1] == 0): + dataout['alpha0'] = 0.5 * (dataoutleft['alpha0'] + dataoutright['alpha0']) + dataout['x1'] = dataoutleft['x1'] + dataout['x1r'] = dataoutright['x1r'] + dataout['alpha1'] = 0.5 * (dataoutleft['alpha1'] + dataoutright['alpha1']) + elif errorlevel[0, 0] == 0: + dataout['alpha0'] = dataoutleft['alpha0'] + dataout['x1'] = dataoutleft['x1'] + dataout['x1r'] = 0 + dataout['alpha1'] = dataoutleft['alpha1'] + elif errorlevel[0, 1] == 0: + dataout['alpha0'] = dataoutright['alpha0'] + dataout['x1'] = 0 + dataout['x1r'] = dataoutright['x1r'] + dataout['alpha1'] = dataoutright['alpha1'] + + return dataout, errorlevel, resnorm + + +def x1RangeLimiter(x0, x0r, xl41, xr41, NOMOSCL, NOMOSCR, FactorOSC, + NOMISCL, NOMISCR, FactorINS, CableType): + try: + from .math_utils import equal + except ImportError: + from math_utils import equal + + if equal(CableType, 79): + NOMINSL = 0.5 * ((x0r - x0) - NOMOSCL - NOMOSCR) + NOMINSR = NOMINSL + else: + NOMINSL = (xl41 - x0) - NOMOSCL - NOMISCL + NOMINSR = (x0r - xr41) - NOMOSCR - NOMISCR + + x1Limitr = min(x0 + NOMOSCL * FactorOSC, x0 + NOMOSCL + (NOMINSL / FactorINS)) + x1rLimitl = max(x0r - NOMOSCR * FactorOSC, x0r - NOMOSCR - (NOMINSR / FactorINS)) + + return x1Limitr, x1rLimitl + + diff --git a/algorithm/curvefit_analysis.py b/algorithm/curvefit_analysis.py new file mode 100644 index 0000000..ecceafb --- /dev/null +++ b/algorithm/curvefit_analysis.py @@ -0,0 +1,1136 @@ +import numpy as np + + +def chk_transition(x0, errx0, x0r, errx0r): + """检查边缘转换,如果右侧边缘在左侧边缘左侧则标记错误""" + errx0 = np.atleast_1d(np.asarray(errx0, dtype=np.float64)).ravel() + errx0r = np.atleast_1d(np.asarray(errx0r, dtype=np.float64)).ravel() + + if len(errx0) < 2: + errx0_full = np.zeros(2) + errx0_full[:len(errx0)] = errx0 + errx0 = errx0_full + if len(errx0r) < 2: + errx0r_full = np.zeros(2) + errx0r_full[:len(errx0r)] = errx0r + errx0r = errx0r_full + + if errx0[0] == 0 and errx0r[0] == 0 and x0r < x0: + x0 = 0.0 + x0r = 0.0 + errx0[0] = 71 + errx0r[0] = 71 + + return x0, errx0, x0r, errx0r + + +def _err2stat(errmat, status, edges, column, edge_active): + """将错误矩阵转换为状态和边缘值""" + StNovalue = 45 + StDefault = 255 + + errmat = np.atleast_2d(np.asarray(errmat, dtype=np.float64)) + if errmat.shape[0] < 2: + errmat = np.pad(errmat, ((0, 2 - errmat.shape[0]), (0, 0))) + + if edge_active: + err_arr = errmat[0, :] + warn_arr = errmat[1, :] if errmat.shape[0] > 1 else np.zeros(errmat.shape[1]) + + errind = np.where(err_arr > 0)[0] + warnind = np.where(warn_arr > 0)[0] + + if len(errind) > 0: + if status.shape[0] > 0: + status[0, column] = err_arr[errind[0]] + edges[column] = 0 + + if len(warnind) > 0: + if status.shape[0] > 1: + status[1, column] = warn_arr[warnind[0]] + else: + edges[column] = 0 + if status.shape[0] > 0: + status[0, column] = StNovalue + + if edges[column] == 0 and status[0, column] == 0: + status[0, column] = StDefault + + return status, edges + + +def errlevel2stat(edgesleft_in, edgesright_in, errorlevel, layeruse, cableType, mode): + """将错误级别转换为边缘状态输出""" + edgesleft_out = np.array(edgesleft_in, dtype=np.float64).ravel().copy() + edgesright_out = np.array(edgesright_in, dtype=np.float64).ravel().copy() + + n_edges = max(len(edgesleft_out), 4) + if len(edgesleft_out) < n_edges: + edgesleft_out = np.pad(edgesleft_out, (0, n_edges - len(edgesleft_out))) + if len(edgesright_out) < n_edges: + edgesright_out = np.pad(edgesright_out, (0, n_edges - len(edgesright_out))) + + status = np.zeros((2, 1), dtype=np.float64) + statusL = np.zeros((2, n_edges), dtype=np.float64) + statusR = np.zeros((2, n_edges), dtype=np.float64) + + errorlevel = np.atleast_2d(np.asarray(errorlevel, dtype=np.float64)) + if errorlevel.shape[0] < 2: + errorlevel = np.pad(errorlevel, ((0, 2 - errorlevel.shape[0]), (0, 0))) + + diaind = np.array([11, 12, 13, 16, 17]) - 1 + column = 0 + edge_active = 1 + + dia_err = errorlevel[:, diaind] if diaind[-1] < errorlevel.shape[1] else np.zeros((2, 5)) + statusL, edgesleft_out = _err2stat(dia_err, statusL, edgesleft_out, column, edge_active) + statusR, edgesright_out = _err2stat(dia_err, statusR, edgesright_out, column, edge_active) + + column = 3 + if mode in ('anajack2',): + x3ind = np.concatenate([diaind, [18-1, 20-1, 22-1]]) + x3rind = np.concatenate([diaind, [19-1, 21-1, 23-1]]) + edge_active = np.all(layeruse) + elif mode in ('anajacksp', 'cfit_2l_tube_noyarn', 'cfit_2l_tube_yarn'): + x3ind = np.array([], dtype=int) + x3rind = np.array([], dtype=int) + edge_active = 0 + elif mode in ('cfit_Uponor', 'cfit_Uponor_107'): + x3ind = np.concatenate([diaind, np.arange(14-1, 22)]) + x3rind = np.concatenate([diaind, np.arange(14-1, 21), [23-1]]) + edge_active = np.all(layeruse) + elif mode in ('analy01', 'cfit_tube', 'riffle'): + x3ind = np.concatenate([diaind, [14-1, 15-1, 22-1]]) + x3rind = np.concatenate([diaind, [14-1, 15-1, 23-1]]) + edge_active = np.any(layeruse) + else: + x3ind = np.concatenate([diaind, [14-1, 15-1, 22-1]]) + x3rind = np.concatenate([diaind, [14-1, 15-1, 23-1]]) + edge_active = np.any(layeruse) + + def _safe_col(err, idx): + valid = idx[(idx >= 0) & (idx < err.shape[1])] + return err[:, valid] if len(valid) > 0 else np.zeros((2, 0)) + + x3_err = _safe_col(errorlevel, x3ind) + x3r_err = _safe_col(errorlevel, x3rind) + + column = 3 + statusL, edgesleft_out = _err2stat(x3_err, statusL, edgesleft_out, column, edge_active) + statusR, edgesright_out = _err2stat(x3r_err, statusR, edgesright_out, column, edge_active) + + column = 1 + if mode in ('anajacksp',): + x1ind = np.concatenate([diaind, [14-1, 15-1, 22-1, 23-1, 18-1]]) + x1rind = np.concatenate([diaind, [14-1, 15-1, 22-1, 23-1, 19-1]]) + edge_active_x1 = layeruse[0] if len(layeruse) > 0 else 0 + elif mode in ('cfit_2l_tube_noyarn',): + x1ind = np.concatenate([diaind, [29-1, 18-1]]) + x1rind = np.concatenate([diaind, [29-1, 19-1]]) + edge_active_x1 = layeruse[0] if len(layeruse) > 0 else 0 + elif mode in ('cfit_2l_tube_yarn',): + x1ind = np.concatenate([diaind, [29-1, 20-1, 21-1, 18-1]]) + x1rind = np.concatenate([diaind, [29-1, 20-1, 21-1, 19-1]]) + edge_active_x1 = layeruse[0] if len(layeruse) > 0 else 0 + elif mode in ('cfit_Uponor', 'cfit_Uponor_107'): + x1ind = np.concatenate([diaind, [14-1, 15-1, 18-1]]) + x1rind = np.concatenate([diaind, [14-1, 15-1, 19-1]]) + edge_active_x1 = layeruse[0] if len(layeruse) > 0 else 0 + elif mode in ('analy01', 'cfit_tube', 'anajack2', 'riffle'): + x1ind = np.concatenate([diaind, [18-1]]) + x1rind = np.concatenate([diaind, [19-1]]) + edge_active_x1 = layeruse[0] if len(layeruse) > 0 else 0 + else: + x1ind = np.concatenate([diaind, [18-1]]) + x1rind = np.concatenate([diaind, [19-1]]) + edge_active_x1 = layeruse[0] if len(layeruse) > 0 else 0 + + x1_err = _safe_col(errorlevel, x1ind) + x1r_err = _safe_col(errorlevel, x1rind) + statusL, edgesleft_out = _err2stat(x1_err, statusL, edgesleft_out, column, edge_active_x1) + statusR, edgesright_out = _err2stat(x1r_err, statusR, edgesright_out, column, edge_active_x1) + + column = 2 + if mode in ('cfit_tube',): + x2ind = np.concatenate([diaind, [18-1, 19-1], x3ind, [20-1]]) + x2rind = np.concatenate([diaind, [18-1, 19-1], x3rind, [21-1]]) + edge_active_x2 = layeruse[2] if len(layeruse) > 2 else 0 + elif mode in ('anajack2',): + x2ind = np.concatenate([diaind, [18-1, 20-1]]) + x2rind = np.concatenate([diaind, [19-1, 21-1]]) + edge_active_x2 = np.all(layeruse[:2]) if len(layeruse) >= 2 else 0 + elif mode in ('anajacksp', 'cfit_Uponor_107'): + x2ind = np.array([], dtype=int) + x2rind = np.array([], dtype=int) + edge_active_x2 = 0 + elif mode in ('cfit_2l_tube_noyarn', 'cfit_2l_tube_yarn'): + x2ind = np.concatenate([diaind, [29-1, 20-1]]) + x2rind = np.concatenate([diaind, [29-1, 21-1]]) + edge_active_x2 = np.all(layeruse[:2]) if len(layeruse) >= 2 else 0 + elif mode in ('cfit_Uponor',): + x2ind = np.concatenate([diaind, [14-1, 15-1, 18-1]]) + x2rind = np.concatenate([diaind, [14-1, 15-1, 19-1]]) + edge_active_x2 = np.all(layeruse[:2]) if len(layeruse) >= 2 else 0 + elif mode in ('analy01',): + x2ind = np.concatenate([diaind, [14-1, 15-1, 22-1, 23-1, 20-1]]) + x2rind = np.concatenate([diaind, [14-1, 15-1, 22-1, 23-1, 21-1]]) + edge_active_x2 = layeruse[2] if len(layeruse) > 2 else 0 + elif mode in ('riffle',): + x2ind = np.concatenate([diaind, [14-1, 15-1, 22-1, 23-1, 20-1, 21-1, 18-1, 19-1]]) + x2rind = np.concatenate([diaind, [14-1, 15-1, 22-1, 23-1, 20-1, 21-1, 18-1, 19-1]]) + edge_active_x2 = layeruse[2] if len(layeruse) > 2 else 0 + else: + x2ind = np.concatenate([diaind, [14-1, 15-1, 22-1, 23-1, 20-1]]) + x2rind = np.concatenate([diaind, [14-1, 15-1, 22-1, 23-1, 21-1]]) + edge_active_x2 = layeruse[2] if len(layeruse) > 2 else 0 + + x2_err = _safe_col(errorlevel, x2ind) + x2r_err = _safe_col(errorlevel, x2rind) + statusL, edgesleft_out = _err2stat(x2_err, statusL, edgesleft_out, column, edge_active_x2) + statusR, edgesright_out = _err2stat(x2r_err, statusR, edgesright_out, column, edge_active_x2) + + if mode in ('anajack2', 'anajacksp', 'cfit_2l_tube_noyarn', 'cfit_2l_tube_yarn') or cableType == 79: + if len(layeruse) >= 3 and np.all(layeruse == [1, 0, 0]): + edgesleft_out[3] = edgesleft_out[1] + edgesright_out[3] = edgesright_out[1] + statusL[:, 3] = statusL[:, 1] + statusR[:, 3] = statusR[:, 1] + elif len(layeruse) >= 2 and np.all(layeruse[:2] == [1, 1]): + edgesleft_out[3] = edgesleft_out[2] + edgesright_out[3] = edgesright_out[2] + statusL[:, 3] = statusL[:, 2] + statusR[:, 3] = statusR[:, 2] + + if mode in ('analy01', 'cfit_tube') and len(layeruse) >= 3 and np.all(layeruse == [1, 0, 0]): + edgesleft_out[1] = edgesleft_out[3] + edgesright_out[1] = edgesright_out[3] + statusL[:, 1] = statusL[:, 3] + statusR[:, 1] = statusR[:, 3] + + for row in range(2): + errindL = np.where(statusL[row, :] > 0)[0] + errindR = np.where(statusR[row, :] > 0)[0] + if len(errindL) > 0 and len(errindR) > 0: + if errindR[0] < errindL[0]: + status[row, 0] = statusR[row, errindR[0]] + else: + status[row, 0] = statusL[row, errindL[0]] + elif len(errindL) > 0: + status[row, 0] = statusL[row, errindL[0]] + elif len(errindR) > 0: + status[row, 0] = statusR[row, errindR[0]] + + return edgesleft_out, edgesright_out, status, statusL, statusR + + +def ana_curvefit_cable(I, conf, errorin, settings): + """XLPE电缆的曲线拟合分析(对应MATLAB ana_curvefit_cable.m)""" + from edge_detection_utils import i0detect, i0det2, x41det2 + from detection_utils import cxlr11 + from math_utils import ind, is_pe + from curve_fit_utils import ( + x0_x0r_curvefit2, x1_x1r_curvefit3, x1_x1r_curvefit4, lincorn, x1RangeLimiter + ) + from geometry_utils import strng2 + + I = np.asarray(I, dtype=np.float64).ravel() + conf = np.asarray(conf, dtype=np.float64).ravel() + errorin = np.asarray(errorin, dtype=np.float64).ravel() + if len(errorin) < 2: + errorin = np.zeros(2) + + detail = { + 'IN': np.nan, 'nominal': np.nan, + 'left': { + 'pos': {'result': np.nan, 'start': np.nan, + 'limit': {'left': np.nan, 'right': np.nan}}, + 'att': {'outer': np.nan, 'inner': np.nan}, + 'error': np.array([np.nan, np.nan]) + }, + 'att': {'min': np.nan, 'max': np.nan}, + 'contr': {'min': np.nan, 'max': np.nan, 'sign': np.nan}, + } + detail['right'] = { + 'pos': {'result': np.nan, 'start': np.nan, + 'limit': {'left': np.nan, 'right': np.nan}}, + 'att': {'outer': np.nan, 'inner': np.nan}, + 'error': np.array([np.nan, np.nan]) + } + + TAPE_TOO_LARGE = 93 + conf20 = conf[19] if len(conf) > 19 else 0 + dx = conf[91] if len(conf) > 91 else 0.048 + dx = float(dx) if dx is not None else 0.048 + if dx == 0: + dx = 0.048 + + NOMDIA = conf[0] if len(conf) > 0 else 0 + NOMCOND = conf[1] if len(conf) > 1 else 0 + NOMOSC = conf[2] if len(conf) > 2 else 0 + NOMISC = conf[3] if len(conf) > 3 else 0 + Riff = conf[5] if len(conf) > 5 else 0 + NOMTAPE = conf[4] if len(conf) > 4 else 0 + NOMTAPEl = NOMTAPE + NOMTAPEr = NOMTAPE + + offsetCORE = 0 + if abs(conf20 - 123) < 1e-6: + offsetCORE = conf[4] if len(conf) > 4 else 0 + + Maximumc = np.array([1, 1, -1, 1, 1], dtype=np.float64) + if abs(conf20 - 122) < 1e-6: + Maximumc = np.array([1, 1, -1, -1, 1], dtype=np.float64) + + confx0ind = 1179 + confx1ind = 1299 + confx2ind = 1319 + if abs(conf20 - 116) < 1e-6: + confx2ind = 1339 + + conddetoff = 0 + modevector = np.array([-1, 6, 2, -1], dtype=np.float64) + + if NOMISC <= 0.5: + if NOMTAPE > 0: + errorin[0] = TAPE_TOO_LARGE + elif NOMISC <= 1.0: + if NOMTAPE > (NOMISC - 0.5): + errorin[0] = TAPE_TOO_LARGE + else: + if NOMTAPE > 0.5 * NOMISC: + errorin[0] = TAPE_TOO_LARGE + + onlydiameterused = abs(conf20 - 70) < 1e-6 + layeruse = np.array([(NOMOSC > 0), 0, (NOMISC > 0)], dtype=np.float64) + + if onlydiameterused: + layeruse = np.array([0, 0, 0]) + elif layeruse[0] == 0 and layeruse[2] == 0: + layeruse = np.array([1, 0, 0]) + elif layeruse[0] == 0 and layeruse[2] == 1: + layeruse = np.array([0, 1, 1]) + elif layeruse[0] == 1 and layeruse[2] == 0: + layeruse = np.array([1, 1, 0]) + else: + layeruse = np.array([1, 1, 1]) + + DistI0 = conf[34] if len(conf) > 34 else 1000 + Dist01 = conf[35] if len(conf) > 35 else 0 + Lowrad = conf[36] if len(conf) > 36 else 20000 + + if is_pe(conf20): + Highpegel11 = conf[122] if len(conf) > 122 else 0 + else: + Highpegel11 = conf[39] if len(conf) > 39 else 0 + + Ab = conf[40] if len(conf) > 40 else 0 + Offpegel41 = conf[41] if len(conf) > 41 else 0 + Off41 = conf[42] if len(conf) > 42 else 0 + Minidiff = conf[43] if len(conf) > 43 else 0 + Schicht34 = conf[44] if len(conf) > 44 else 0 + Schicht01 = conf[45] if len(conf) > 45 else 0 + fg12 = conf[47] if len(conf) > 47 else 0 + fg23 = conf[48] if len(conf) > 48 else 0 + fakfg = conf[52] if len(conf) > 52 else 0 + sym01 = conf[56] if len(conf) > 56 else 0 + sym01riff = conf[58] if len(conf) > 58 else 0 + sym12 = conf[60] if len(conf) > 60 else 0 + Itermax = conf[61] if len(conf) > 61 else 0 + Centerdiff = conf[62] if len(conf) > 62 else 0 + klevel12 = conf[65] if len(conf) > 65 else 0 + Sehnlimit = conf[82] if len(conf) > 82 else 0 + klimit = conf[83] if len(conf) > 83 else 0 + Minpegel41 = conf[84] if len(conf) > 84 else 0 + Mindistadd = conf[165] if len(conf) > 165 else 0 + Maxdistadd = conf[166] if len(conf) > 166 else 0 + Ber = 2.0 + + errorlevel = np.zeros((2, 28), dtype=np.float64) + Anzpara = conf[10] if len(conf) > 10 else 0 + + if 0 < NOMOSC < 0.2: + NOMOSC = 0.2 + if 0 < NOMISC < 0.2: + NOMISC = 0.2 + if NOMDIA < (2 * NOMOSC + 2 * NOMISC + NOMCOND): + NOMDIA = 2 * NOMOSC + 2 * NOMISC + NOMCOND + + if abs(Riff - 1) < 1e-6: + sym01 = sym01riff + + count = len(I) + x = np.arange(1, count + 1, dtype=np.float64) + x = (x - 1) * dx + Ab = int(np.round(Ab / dx)) if dx > 0 else 0 + Highpegel11 = Highpegel11 / 100.0 + Offpegel41 = Offpegel41 / 100.0 + + if fg23 > (1 / (2 * dx)) and dx > 0: + fg23 = 1 / (2 * dx) + + xl11, xl00, xr11, xr00 = 0.0, 0.0, 0.0, 0.0 + xl41, xr41 = 0.0, 0.0 + x0, x0r, x1, x1r, x2, x2r, x3, x3r = 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 + + I0, errorlevel[0:2, 10] = i0detect(I, DistI0, dx, Lowrad, errorin) + if errorlevel[0, 10] == 0: + IN = I / I0 if I0 > 0 else I + else: + IN = I.copy() + detail['IN'] = IN + + if errorlevel[0, 10] == 0: + try: + xl11, xl00, errorlevel[0, 11], xr11, xr00, errorlevel[0, 12], \ + xl41_t, xr41_t, xlr41det = cxlr11(I, I0, Anzpara, conf) + xl41 = xl41_t + xr41 = xr41_t + except Exception as e: + errorlevel[0, 11] = 4 + errorlevel[0, 12] = 4 + + errordia = errorlevel[0, 10] + errorlevel[0, 11] + errorlevel[0, 12] + + if errordia == 0: + ll = int(ind(xl11 + (conf[130] if len(conf) > 130 else 0), dx, 0, count)) + rr = int(ind(xr11 - (conf[130] if len(conf) > 130 else 0), dx, 0, count)) + if rr > ll: + muell = np.where(I[ll:rr] > (I0 * Highpegel11))[0] + if len(muell) > 0: + errorlevel[0, 10] = 10 + if xl11 >= xr11: + errorlevel[0, 10] = 10 + + errordia = errorlevel[0, 10] + errorlevel[0, 11] + errorlevel[0, 12] + + if errordia == 0: + try: + I02, err_1d = i0det2(I, xl11, xr11, conf, errorlevel[:, 10]) + errorlevel[:, 10] = np.atleast_1d(err_1d).ravel()[:2] + if errorlevel.shape[0] < 2: + pass + except Exception: + pass + + errordia = np.any(errorlevel[0, 10:13]) + + NOMOSCNEW = NOMOSC + NOMISCNEW = NOMISC + + if errordia == 0: + if NOMOSC > ((xr11 - xl11) / 5): + NOMOSCNEW = (xr11 - xl11) / 5 + if NOMISC > ((xr11 - xl11) / 5): + NOMISCNEW = (xr11 - xl11) / 5 + + Sehnmax = np.sqrt(max(NOMDIA**2 - NOMCOND**2, 0)) + xk = xl11 + (NOMDIA - NOMCOND) / 4 + d0sch = xr11 - xl11 + sk_expr = (xk - xl11) * d0sch - (xk - xl11)**2 + sk = 2 * np.sqrt(max(sk_expr, 0)) + Indxk = int(ind(xk, dx)) + Indxk = max(0, min(count - 1, Indxk)) + + if sk > 0 and Indxk < len(IN) and IN[Indxk] > 0: + kmitt = -(np.log(IN[Indxk])) / sk + else: + kmitt = 0 + + if Sehnmax > Sehnlimit and kmitt > klimit: + errorlevel[0, 13] = 25 + + errorcond = errorlevel[0, 13] + (errorlevel[0, 14] if errorlevel.shape[1] > 14 else 0) + + if errordia == 0 and errorcond == 0 and conddetoff == 0: + if abs(conf[41] if len(conf) > 41 else 0) < 1e-6: + d0s = xr11 - xl11 + if is_pe(conf20): + att = 0.025 + else: + att = 0.15 + Offpegel41 = np.exp(-att * d0s) + + if abs(conf20 - 113) < 1e-6: + Distadd = 0.65 * (conf[8] if len(conf) > 8 else 0) + else: + Distadd = NOMOSCNEW + + if Mindistadd == 0: + Mindistadd = 0.15 + 0.0085 * (x0r - x0) if (x0r - x0) > 0 else 0.15 + + if Distadd < Mindistadd: + Distadd = Mindistadd + elif Distadd > Maxdistadd: + Distadd = Maxdistadd + + Dist41 = NOMOSCNEW + Distadd + + confi = np.zeros(17, dtype=np.float64) + confi[0:5] = [xl11, xr11, Dist41, I0, Offpegel41] + confi[5:10] = [Off41, Ab, Minpegel41, Minidiff, Ber] + confi[10:15] = [Anzpara, dx, Maximumc[0], conf20, 0] + confi[15:17] = [0, conf[194] if len(conf) > 194 else 0] + + try: + xl41, err_14 = x41det2(x, IN, confi) + errorlevel[:, 13] = np.atleast_1d(err_14).ravel()[:2] + except Exception: + xl41 = 0 + errorlevel[0, 13] = 7 + + if errorlevel[0, 13] != 0: + xl41 = 0 + + confi[14] = 1 + try: + xr41, err_15 = x41det2(x, IN, confi) + errorlevel[:, 14] = np.atleast_1d(err_15).ravel()[:2] + except Exception: + xr41 = 0 + errorlevel[0, 14] = 7 + + if errorlevel[0, 14] != 0: + xr41 = 0 + + errorcond = errorlevel[0, 13] + errorlevel[0, 14] + + if errordia == 0: + fun_para_static = {} + modul_para = {} + try: + fun_para_static['filtactive'] = conf[confx0ind + 9] if len(conf) > confx0ind + 9 else 0 + fun_para_static['filtlength'] = conf[confx0ind + 10] if len(conf) > confx0ind + 10 else 0 + modul_para['range_outer'] = conf[confx0ind + 11] if len(conf) > confx0ind + 11 else 0 + modul_para['range_inner'] = conf[confx0ind + 12] if len(conf) > confx0ind + 12 else 0 + modul_para['display'] = Anzpara + modul_para['x0limit_l'] = xl00 + x0limit = modul_para['range_inner'] + if NOMOSC > 0 and x0limit > 0.5 * NOMOSC: + x0limit = 0.5 * NOMOSC if 0.5 * NOMOSC > 0.3 else 0.3 + modul_para['x0limit_r'] = xl11 + x0limit - 0.5 * fun_para_static.get('filtlength', 0) + modul_para['x0rlimit_l'] = xr11 - x0limit + 0.5 * fun_para_static.get('filtlength', 0) + modul_para['x0rlimit_r'] = xr00 + modul_para['minatt1'] = conf[confx0ind] if len(conf) > confx0ind else 0 + modul_para['maxatt1'] = conf[confx0ind + 1] if len(conf) > confx0ind + 1 else 1 + modul_para['mincontr'] = conf[confx0ind + 2] if len(conf) > confx0ind + 2 else 0 + modul_para['maxcontr'] = conf[confx0ind + 3] if len(conf) > confx0ind + 3 else 100 + modul_para['resmax'] = conf[confx0ind + 4] if len(conf) > confx0ind + 4 else 1 + modul_para['TolFun'] = conf[confx0ind + 5] if len(conf) > confx0ind + 5 else 1e-6 + modul_para['TolX'] = conf[confx0ind + 6] if len(conf) > confx0ind + 6 else 1e-6 + modul_para['MaxFunEvals'] = conf[confx0ind + 7] if len(conf) > confx0ind + 7 else 400 + modul_para['LevenbergMarquardt'] = conf[confx0ind + 8] if len(conf) > confx0ind + 8 else 0 + fun_startpara = np.array([xl11, xr11, 0.0]) + fun_para_static['unsharpness'] = 0 + + calcpara, err_16_17, dataout = x0_x0r_curvefit2( + x, IN, fun_startpara, fun_para_static, modul_para + ) + x0 = calcpara[0] if isinstance(calcpara, np.ndarray) else calcpara.get('x0', xl11) + x0r = calcpara[1] if isinstance(calcpara, np.ndarray) else calcpara.get('x0r', xr11) + + if isinstance(err_16_17, np.ndarray) and err_16_17.shape[1] >= 2: + errorlevel[:, 15] = err_16_17[:, 0] + errorlevel[:, 16] = err_16_17[:, 1] + + x0, errorlevel[:, 15], x0r, errorlevel[:, 16] = chk_transition( + x0, errorlevel[:, 15], x0r, errorlevel[:, 16] + ) + + detail['nominal'] = NOMOSC + if isinstance(dataout, dict) and 'left' in dataout: + detail['left'] = dataout['left'] + detail['left']['pos']['start'] = fun_startpara[0] + detail['left']['pos']['limit']['left'] = modul_para.get('x0limit_l', 0) + detail['left']['pos']['limit']['right'] = modul_para.get('x0limit_r', 0) + detail['left']['error'] = errorlevel[:, 15].copy() + + if isinstance(dataout, dict) and 'right' in dataout: + detail['right'] = dataout['right'] + detail['right']['pos']['start'] = fun_startpara[1] + detail['right']['pos']['limit']['left'] = modul_para.get('x0rlimit_l', 0) + detail['right']['pos']['limit']['right'] = modul_para.get('x0rlimit_r', 0) + detail['right']['error'] = errorlevel[:, 16].copy() + + detail['att']['min'] = modul_para.get('minatt1', 0) + detail['att']['max'] = modul_para.get('maxatt1', 0) + detail['contr']['min'] = modul_para.get('mincontr', 0) + detail['contr']['max'] = modul_para.get('maxcontr', 0) + except Exception as e: + pass + + conf20_special = abs(conf20 - 121) >= 1e-6 + if (conf20_special and errordia == 0 and NOMOSC > 0 and + errorlevel[0, 15] == 0 and errorlevel[0, 16] == 0): + try: + modul_para['range_outer'] = conf[confx1ind + 11] if len(conf) > confx1ind + 11 else 0 + modul_para['range_inner'] = conf[confx1ind + 12] if len(conf) > confx1ind + 12 else 0 + fun_para_static['filtactive'] = conf[confx1ind + 9] if len(conf) > confx1ind + 9 else 0 + fun_para_static['filtlength'] = conf[confx1ind + 10] if len(conf) > confx1ind + 10 else 0 + modul_para['display'] = Anzpara + + filtlen = fun_para_static.get('filtlength', 0) + if (NOMOSCNEW - filtlen) > 0.5: + modul_para['x1limit_l'] = x0 + filtlen + modul_para['x1rlimit_r'] = x0r - filtlen + else: + modul_para['x1limit_l'] = x0 + 0.5 * filtlen + modul_para['x1rlimit_r'] = x0r - 0.5 * filtlen + + x1lim_r, x1rlim_l = 0, 0 + try: + from curve_fit_utils import x1RangeLimiter + x1lim_r, x1rlim_l = x1RangeLimiter( + x0, x0r, xl41, xr41, NOMOSC, NOMOSC, + 3.0, NOMISC, NOMISC, 1.5, conf20 + ) + except Exception: + x1lim_r = xl41 if xl41 > 0 else x0 + NOMOSC + x1rlim_l = xr41 if xr41 > 0 else x0r - NOMOSC + + modul_para['x1limit_r'] = x1lim_r + modul_para['x1rlimit_l'] = x1rlim_l + + modul_para['minatt1'] = conf[confx1ind] if len(conf) > confx1ind else 0 + modul_para['maxatt1'] = conf[confx1ind + 1] if len(conf) > confx1ind + 1 else 1 + modul_para['mincontr'] = conf[confx1ind + 2] if len(conf) > confx1ind + 2 else 0 + modul_para['maxcontr'] = conf[confx1ind + 3] if len(conf) > confx1ind + 3 else 100 + modul_para['contrsign'] = Maximumc[2] + modul_para['resmax'] = conf[confx1ind + 4] if len(conf) > confx1ind + 4 else 1 + modul_para['TolFun'] = conf[confx1ind + 5] if len(conf) > confx1ind + 5 else 1e-6 + modul_para['TolX'] = conf[confx1ind + 6] if len(conf) > confx1ind + 6 else 1e-6 + modul_para['MaxFunEvals'] = conf[confx1ind + 7] if len(conf) > confx1ind + 7 else 400 + modul_para['LevenbergMarquardt'] = conf[confx1ind + 8] if len(conf) > confx1ind + 8 else 0 + + fun_para_static['x0'] = x0 + fun_para_static['x0r'] = x0r + fun_para_static['mode'] = modevector[1] + + fun_para_static['x1'] = x0 + NOMOSCNEW + fun_para_static['x1r'] = x0r - NOMOSCNEW + fun_para_static['txt_left'] = '; x1= ' + fun_para_static['txt_right'] = '; x1r= ' + + calcpara_x1, err_18_19 = x1_x1r_curvefit3(x, IN, fun_para_static, modul_para) + + alpha0 = 0.0 + if isinstance(calcpara_x1, dict): + x1 = calcpara_x1.get('left', {}).get('pos', {}).get('result', np.nan) + x1r = calcpara_x1.get('right', {}).get('pos', {}).get('result', np.nan) + alpha0 = calcpara_x1.get('alpha0', 0.0) + if not np.isfinite(x1): + x1 = calcpara_x1.get('x1', x0 + NOMOSCNEW) + if not np.isfinite(x1r): + x1r = calcpara_x1.get('x1r', x0r - NOMOSCNEW) + else: + x1 = calcpara_x1[0] if len(calcpara_x1) > 0 else x0 + NOMOSCNEW + x1r = calcpara_x1[1] if len(calcpara_x1) > 1 else x0r - NOMOSCNEW + + if isinstance(err_18_19, np.ndarray) and err_18_19.shape[1] >= 2: + errorlevel[:, 17] = err_18_19[:, 0] + errorlevel[:, 18] = err_18_19[:, 1] + + x1, errorlevel[:, 17], x1r, errorlevel[:, 18] = chk_transition( + x1, errorlevel[:, 17], x1r, errorlevel[:, 18] + ) + + except Exception as e: + import traceback + traceback.print_exc() + pass + + if (errordia == 0 and (errorcond == 0 or conddetoff > 0) and + np.all(errorlevel[0, [15, 16]] == 0)): + + sym34 = conf[55] if len(conf) > 55 else 0 + Schicht4 = conf[46] if len(conf) > 46 else 0 + fg34 = conf[51] if len(conf) > 51 else 0 + klevel34 = conf[67] if len(conf) > 67 else 0 + + try: + Dl = xl41 - sym34 + Dr = xl41 + sym34 + Limitl = xl41 - sym34 + Limitr = xl41 + Schicht4 + Dl = max(Dl, Limitl) + Dr = min(Dr, Limitr) + + confi_x3 = np.zeros(14, dtype=np.float64) + confi_x3[0:5] = [Dl, Dr, Limitl, Limitr, fg34] + confi_x3[5:10] = [sym01, Centerdiff, Itermax, dx, klevel34] + confi_x3[10:14] = [Anzpara, fakfg, Maximumc[4], 0] + + x3, err_22 = lincorn(IN, confi_x3) + errorlevel[:, 21] = np.atleast_1d(err_22).ravel()[:2] + detail['left']['pos']['result'] = x3 + detail['left']['pos']['limit']['left'] = Limitl + detail['left']['pos']['limit']['right'] = Limitr + except Exception as e: + import traceback + traceback.print_exc() + x3 = 0 + + try: + Dl_r = xr41 - sym34 + Dr_r = xr41 + sym34 + Limitl_r = xr41 - Schicht4 + Limitr_r = xr41 + sym34 + Dl_r = max(Dl_r, Limitl_r) + Dr_r = min(Dr_r, Limitr_r) + + confi_x3r = np.zeros(14, dtype=np.float64) + confi_x3r[0:5] = [Dl_r, Dr_r, Limitl_r, Limitr_r, fg34] + confi_x3r[5:10] = [sym01, Centerdiff, Itermax, dx, klevel34] + confi_x3r[10:14] = [Anzpara, fakfg, Maximumc[4], 1] + + x3r, err_23 = lincorn(IN, confi_x3r) + errorlevel[:, 22] = np.atleast_1d(err_23).ravel()[:2] + detail['right']['pos']['result'] = x3r + detail['right']['pos']['limit']['left'] = Limitl_r + detail['right']['pos']['limit']['right'] = Limitr_r + except Exception: + x3r = 0 + + try: + x3_old = x3 + x3r_old = x3r + err21_old = errorlevel[:, 21].copy() + err22_old = errorlevel[:, 22].copy() + x3, errorlevel[:, 21], x3r, errorlevel[:, 22] = chk_transition( + x3, errorlevel[:, 21], x3r, errorlevel[:, 22] + ) + except Exception: + pass + + if (errordia == 0 and (errorcond == 0 or conddetoff > 0) and NOMISC > 0 and + np.all(errorlevel[0, [15, 16, 21, 22]] == 0)): + try: + from math_utils import ind + from geometry_utils import strng2 + from curve_fit_utils import x1_x1r_curvefit4 + + # ============ 1. INS信号:剥离OSC层衰减 ============ + if NOMOSC > 0 and np.all(errorlevel[0, [17, 18]] == 0) and abs(conf20 - 115) >= 1e-6: + s0_ins = strng2(x, x0, x0r, 1) + s1_ins = strng2(x, x1, x1r, 1) + INS = IN / np.exp(-1.0 * (alpha0 * (s0_ins - s1_ins))) + fun_para_static['x0'] = x1 + fun_para_static['x0r'] = x1r + modul_para['x1limit_l'] = x1 + fun_para_static.get('filtactive', 0) + modul_para['x1rlimit_r'] = x1r - fun_para_static.get('filtactive', 0) + else: + INS = IN.copy() + fun_para_static['x0'] = x0 + fun_para_static['x0r'] = x0r + modul_para['x1limit_l'] = x0 + 2 * NOMOSC + fun_para_static.get('filtactive', 0) + modul_para['x1rlimit_r'] = x0r - 2 * NOMOSC - fun_para_static.get('filtactive', 0) + + # ============ 2. 配置x2拟合参数 ============ + fun_para_static['filtactive'] = conf[confx2ind + 9] if len(conf) > confx2ind + 9 else 0 + fun_para_static['filtlength'] = conf[confx2ind + 10] if len(conf) > confx2ind + 10 else 0 + + modul_para['range_outer'] = conf[confx2ind + 11] if len(conf) > confx2ind + 11 else 0 + modul_para['range_inner'] = conf[confx2ind + 12] if len(conf) > confx2ind + 12 else 0 + modul_para['display'] = Anzpara + + filtlen_x2 = fun_para_static.get('filtlength', 0) + modul_para['x1limit_r'] = x3 - filtlen_x2 - NOMTAPEl + modul_para['x1rlimit_l'] = x3r + filtlen_x2 + NOMTAPEr + + modul_para['minatt1'] = conf[confx2ind] if len(conf) > confx2ind else 0 + modul_para['maxatt1'] = conf[confx2ind + 1] if len(conf) > confx2ind + 1 else 1 + + # ============ 3. mincontr动态校正(电压和路径长度影响) ============ + dalpha_min = conf[confx2ind + 17] if len(conf) > confx2ind + 17 else 0 + dalpha_max = conf[confx2ind + 2] if len(conf) > confx2ind + 2 else 0 + s1_x3 = (strng2(x3r, x0, x0r) + strng2(x3, x0, x0r)) / 2.0 + voltage = settings.get('voltage', 50) if isinstance(settings, dict) else 50 + conf_x2_18 = conf[confx2ind + 18] if len(conf) > confx2ind + 18 else 0 + conf_x2_19 = conf[confx2ind + 19] if len(conf) > confx2ind + 19 else 0 + mincontr_raw = dalpha_max + (voltage - 50) * conf_x2_19 + (s1_x3 - 10) * conf_x2_18 + mincontr = min(dalpha_max, max(dalpha_min, mincontr_raw)) + modul_para['mincontr'] = mincontr + + modul_para['maxcontr'] = conf[confx2ind + 3] if len(conf) > confx2ind + 3 else 100 + modul_para['contrsign'] = Maximumc[3] + modul_para['resmax'] = conf[confx2ind + 4] if len(conf) > confx2ind + 4 else 1 + modul_para['TolFun'] = conf[confx2ind + 5] if len(conf) > confx2ind + 5 else 1e-6 + modul_para['TolX'] = conf[confx2ind + 6] if len(conf) > confx2ind + 6 else 1e-6 + modul_para['MaxFunEvals'] = conf[confx2ind + 7] if len(conf) > confx2ind + 7 else 400 + modul_para['LevenbergMarquardt'] = conf[confx2ind + 8] if len(conf) > confx2ind + 8 else 0 + fun_para_static['mode'] = modevector[2] + + NOMISCl = NOMISC + NOMISCr = NOMISC + + resnorm_new = None + x2new = None + x2rnew = None + errorlevel_new = None + + # ============ 4. 多步拟合策略 ============ + ovrview = settings.get('ovrview', None) if isinstance(settings, dict) else None + if ovrview is not None: + # 4a. 基于k1衰减系数分布的初始值 + fun_para_static_new1 = dict(fun_para_static) + errorlevel_new1 = errorlevel.copy() + + Indx1_new = int(ind(fun_para_static_new1['x0'], dx, 0, len(x))) + Indx1r_new = int(ind(fun_para_static_new1['x0r'], dx, 0, len(x))) + Indx3_new = int(ind(x3, dx, 0, len(x))) + Indx3r_new = int(ind(x3r, dx, 0, len(x))) + IndOffset = int(np.floor(0.2 / dx)) if dx > 0 else 0 + + s1_k1 = strng2(x, fun_para_static_new1['x0'], fun_para_static_new1['x0r'], 1) + k1 = np.zeros(len(INS)) + valid_mask = (s1_k1 > 0) & (INS > 0) + k1[valid_mask] = -np.log(INS[valid_mask]) / s1_k1[valid_mask] + + left_start = min(Indx1_new + IndOffset, len(k1) - 1) + left_end = max(Indx3_new - IndOffset, 0) + right_start = min(Indx3r_new + IndOffset, len(k1) - 1) + right_end = max(Indx1r_new - IndOffset, 0) + + limitl = np.mean(k1[left_start:left_end]) if left_end > left_start else 0 + limitr = np.mean(k1[right_start:right_end]) if right_end > right_start else 0 + + # 找x2new: k1(1:Indx3) <= limitl 的最后一个位置 + k1_left = k1[:Indx3_new] + below_limitl = np.where(k1_left <= limitl)[0] + if len(below_limitl) > 0: + Indx2new = below_limitl[-1] + fun_para_static_new1['x1'] = x[Indx2new] + else: + fun_para_static_new1['x1'] = x3 - NOMISCl + + # 找x2rnew: k1(Indx3r:end) <= limitr 的第一个位置 + k1_right = k1[Indx3r_new:] + below_limitr = np.where(k1_right <= limitr)[0] + if len(below_limitr) > 0: + Indx2rnew = below_limitr[0] + Indx3r_new + fun_para_static_new1['x1r'] = x[Indx2rnew] + else: + fun_para_static_new1['x1r'] = x3r + NOMISCr + + NOMISCl_new1 = x3 - fun_para_static_new1['x1'] + NOMISCr_new1 = fun_para_static_new1['x1r'] - x3r + fun_para_static_new1['txt_left'] = '; x2new= ' + fun_para_static_new1['txt_right'] = '; x2rnew= ' + + + calcpara_new1, errorlevel_new1[:, 19:21], resnorm_new1 = x1_x1r_curvefit4( + x, INS, fun_para_static_new1, modul_para + ) + x2new1 = calcpara_new1.get('x1', fun_para_static_new1['x1']) if isinstance(calcpara_new1, dict) else fun_para_static_new1['x1'] + x2rnew1 = calcpara_new1.get('x1r', fun_para_static_new1['x1r']) if isinstance(calcpara_new1, dict) else fun_para_static_new1['x1r'] + x2new1, errorlevel_new1[0, 19], x2rnew1, errorlevel_new1[0, 20] = chk_transition( + x2new1, errorlevel_new1[:, 19], x2rnew1, errorlevel_new1[:, 20] + ) + + x2new = x2new1 + x2rnew = x2rnew1 + errorlevel_new = errorlevel_new1 + resnorm_new = resnorm_new1 + + # 4b. 基于ovrview.layer1的初始值(如果ovrview.status为0) + ovrview_status = ovrview.get('status', 1) if isinstance(ovrview, dict) else 1 + if ovrview_status == 0: + ovrview_axis = ovrview.get('axis', 0) if isinstance(ovrview, dict) else 0 + layer3 = ovrview.get('layer3', np.zeros(8)) if isinstance(ovrview, dict) else np.zeros(8) + layer3r = ovrview.get('layer3r', np.zeros(8)) if isinstance(ovrview, dict) else np.zeros(8) + NOMOSCl_new = layer3[ovrview_axis] if ovrview_axis < len(layer3) else NOMOSC + NOMOSCr_new = layer3r[ovrview_axis] if ovrview_axis < len(layer3r) else NOMOSC + if NOMOSCl_new > NOMOSCNEW * 1.5 or NOMOSCl_new < NOMOSCNEW * 0.5: + NOMOSCl_new = NOMOSCNEW + if NOMOSCr_new > NOMOSCNEW * 1.5 or NOMOSCr_new < NOMOSCNEW * 0.5: + NOMOSCr_new = NOMOSCNEW + + layer1 = ovrview.get('layer1', np.zeros(8)) if isinstance(ovrview, dict) else np.zeros(8) + layer1r = ovrview.get('layer1r', np.zeros(8)) if isinstance(ovrview, dict) else np.zeros(8) + NOMISCl_new2 = layer1[ovrview_axis] if ovrview_axis < len(layer1) else NOMISCl + NOMISCr_new2 = layer1r[ovrview_axis] if ovrview_axis < len(layer1r) else NOMISCr + + fun_para_static_new2 = dict(fun_para_static) + errorlevel_new2 = errorlevel.copy() + fun_para_static_new2['x1'] = x3 - NOMISCl_new2 + fun_para_static_new2['x1r'] = x3r + NOMISCr_new2 + fun_para_static_new2['txt_left'] = '; x2new2= ' + fun_para_static_new2['txt_right'] = '; x2rnew2= ' + + + calcpara_new2, errorlevel_new2[:, 19:21], resnorm_new2 = x1_x1r_curvefit4( + x, INS, fun_para_static_new2, modul_para + ) + x2new2 = calcpara_new2.get('x1', fun_para_static_new2['x1']) if isinstance(calcpara_new2, dict) else fun_para_static_new2['x1'] + x2rnew2 = calcpara_new2.get('x1r', fun_para_static_new2['x1r']) if isinstance(calcpara_new2, dict) else fun_para_static_new2['x1r'] + x2new2, errorlevel_new2[0, 19], x2rnew2, errorlevel_new2[0, 20] = chk_transition( + x2new2, errorlevel_new2[:, 19], x2rnew2, errorlevel_new2[:, 20] + ) + + # 4c. 对比NEW1和NEW2,选最优 + rn1_l = resnorm_new1[0] if isinstance(resnorm_new1, np.ndarray) else resnorm_new1 + rn2_l = resnorm_new2[0] if isinstance(resnorm_new2, np.ndarray) else resnorm_new2 + rn1_r = resnorm_new1[1] if isinstance(resnorm_new1, np.ndarray) and len(resnorm_new1) > 1 else resnorm_new1 + rn2_r = resnorm_new2[1] if isinstance(resnorm_new2, np.ndarray) and len(resnorm_new2) > 1 else resnorm_new2 + + err_new1_l = errorlevel_new1[0, 19] + err_new2_l = errorlevel_new2[0, 19] + err_new1_r = errorlevel_new1[0, 20] + err_new2_r = errorlevel_new2[0, 20] + + if (((rn1_l > rn2_l and err_new2_l == 0) or + (err_new1_l != 0 and err_new2_l == 0)) and + x2new2 < x3 - 0.3 and + (x2new2 > x3 - NOMISCl * 0.5 or x2new2 < x3 - NOMISCl * 1.5)): + x2new = x2new2 + errorlevel_new[:, 19] = errorlevel_new2[:, 19] + resnorm_new[0] = rn2_l + else: + pass + if (((rn1_r > rn2_r and err_new2_r == 0) or + (err_new1_r != 0 and err_new2_r == 0)) and + x2rnew2 > x3r + 0.3 and + (x2rnew2 < x3r + NOMISCr * 0.5 or x2rnew2 > x3r + NOMISCr * 1.5)): + x2rnew = x2rnew2 + errorlevel_new[:, 20] = errorlevel_new2[:, 20] + resnorm_new[1] = rn2_r + else: + pass + + # ============ 5. 标称值拟合 ============ + fun_para_static['x1'] = x3 - NOMISCl + fun_para_static['x1r'] = x3r + NOMISCr + fun_para_static['txt_left'] = '; x2= ' + fun_para_static['txt_right'] = '; x2r= ' + + x2_initial = x3 - NOMISCl + x2r_initial = x3r + NOMISCr + + + calcpara_x2, err_20_21, resnorm = x1_x1r_curvefit4(x, INS, fun_para_static, modul_para) + + if isinstance(calcpara_x2, dict): + x2 = calcpara_x2.get('left', {}).get('pos', {}).get('result', np.nan) + x2r = calcpara_x2.get('right', {}).get('pos', {}).get('result', np.nan) + if not np.isfinite(x2): + x2 = calcpara_x2.get('x1', x3 - NOMISCl) + if not np.isfinite(x2r): + x2r = calcpara_x2.get('x1r', x3r + NOMISCr) + else: + x2 = calcpara_x2[0] if len(calcpara_x2) > 0 else x3 - NOMISCl + x2r = calcpara_x2[1] if len(calcpara_x2) > 1 else x3r + NOMISCr + + if isinstance(err_20_21, np.ndarray) and err_20_21.shape[1] >= 2: + errorlevel[:, 19] = err_20_21[:, 0] + errorlevel[:, 20] = err_20_21[:, 1] + + x2, errorlevel[:, 19], x2r, errorlevel[:, 20] = chk_transition( + x2, errorlevel[:, 19], x2r, errorlevel[:, 20] + ) + + # ============ 6. 标称值结果与NEW结果对比选优 ============ + if resnorm_new is not None and x2new is not None: + rn_l = resnorm[0] if isinstance(resnorm, np.ndarray) else resnorm + rn_new_l = resnorm_new[0] if isinstance(resnorm_new, np.ndarray) else resnorm_new + rn_r = resnorm[1] if isinstance(resnorm, np.ndarray) and len(resnorm) > 1 else resnorm + rn_new_r = resnorm_new[1] if isinstance(resnorm_new, np.ndarray) and len(resnorm_new) > 1 else resnorm_new + + err_l = errorlevel[0, 19] + err_new_l = errorlevel_new[0, 19] + err_r = errorlevel[0, 20] + err_new_r = errorlevel_new[0, 20] + + if (((rn_l > rn_new_l and err_new_l == 0) or + (err_l != 0 and err_new_l == 0)) and + x2new < x3 - 0.3 and + (x2new > x3 - NOMISCl * 0.5 or x2new < x3 - NOMISCl * 1.5)): + x2 = x2new + errorlevel[:, 19] = errorlevel_new[:, 19] + + if (((rn_r > rn_new_r and err_new_r == 0) or + (err_r != 0 and err_new_r == 0)) and + x2rnew > x3r + 0.3 and + (x2rnew < x3r + NOMISCr * 0.5 or x2rnew > x3r + NOMISCr * 1.5)): + x2r = x2rnew + errorlevel[:, 20] = errorlevel_new[:, 20] + + + except Exception as e: + import traceback + traceback.print_exc() + x2, x2r = 0, 0 + + if errorlevel[0, 11] == 4 and errorlevel[0, 12] == 4: + errorlevel[0, 11] = 6 + errorlevel[0, 12] = 6 + + if abs(conf20 - 123) < 1e-6: + x3 = x3 + offsetCORE + x3r = x3r - offsetCORE + + mode_out = 'riffle' if abs(conf20 - 115) < 1e-6 else 'analy01' + + edgesleft = np.array([x0, x1, x2, x3], dtype=np.float64) + edgesright = np.array([x0r, x1r, x2r, x3r], dtype=np.float64) + + + edgesleft_out, edgesright_out, status, statusL, statusR = errlevel2stat( + edgesleft, edgesright, errorlevel, layeruse, conf20, mode_out + ) + + attL = np.zeros(3) + attR = np.zeros(3) + + return (edgesleft_out.reshape(1, -1), edgesright_out.reshape(1, -1), + status, statusL, statusR, attL, attR, errorlevel, layeruse, IN, detail) + + +def _base_analysis(I, conf, errorin, num_layers=3): + from edge_detection_utils import i0detect + from detection_utils import cxlr11 + from math_utils import ind + + conf = np.asarray(conf, dtype=np.float64).ravel() + errorin = np.asarray(errorin, dtype=np.float64).ravel() + if len(errorin) < 2: + errorin = np.zeros(2) + + dx = conf[91] if len(conf) > 91 else 0.048 + dx = float(dx) if dx is not None else 0.048 + if dx == 0: + dx = 0.048 + NOMDIA = conf[0] if len(conf) > 0 else 0 + NOMCOND = conf[1] if len(conf) > 1 else 0 + NOMOSC = conf[2] if len(conf) > 2 else 0 + NOMISC = conf[3] if len(conf) > 3 else 0 + TAPE = conf[4] if len(conf) > 4 else 0 + NOMINS = conf[8] if len(conf) > 8 else 0 + DistI0 = conf[34] if len(conf) > 34 else 1000 + Lowrad = conf[36] if len(conf) > 36 else 20000 + + I0, errorlevel = i0detect(I, DistI0, dx, Lowrad, errorin) + + onlydiameterused = (abs(conf[19] - 50) < 1e-6) if len(conf) > 19 else False + layeruse = np.array([(NOMOSC > 0), (NOMINS > 0), (NOMISC > 0)], dtype=np.float64) + + if onlydiameterused: + layeruse = np.array([0, 0, 0]) + elif layeruse[0] == 0 and layeruse[2] == 0 and layeruse[1] == 0: + layeruse = np.array([1, 0, 0]) + + xL = np.zeros((1, num_layers + 1)) + xR = np.zeros((1, num_layers + 1)) + status = np.zeros((1, num_layers + 1)) + statusL = np.zeros((1, num_layers + 1)) + statusR = np.zeros((1, num_layers + 1)) + attL = np.zeros(2) + attR = np.zeros(2) + + count = len(I) + + num_layers_to_detect = int(np.sum(layeruse)) + 1 + if num_layers_to_detect < 2: + num_layers_to_detect = 2 + + try: + xL11, xL00, errL, xR11, xR00, errR, xL41, xR41, xlr41det = cxlr11(I, I0, 0, conf) + + xL[0, 0] = xL11 + xR[0, 0] = xR11 + if num_layers >= 1: + xL[0, 1] = xL41 if xL41 > xL11 else xL11 + xR[0, 1] = xR41 if (xR41 > 0 and xR41 < xR11) else xR11 + statusL[0, 0] = errL + statusR[0, 0] = errR + + if num_layers_to_detect > 2: + cur_xL = xL11 + cur_xR = xR11 + + for layer_idx in range(1, num_layers_to_detect): + if layer_idx > num_layers: + break + + left_start_idx = int(round(cur_xL / dx)) + right_end_idx = int(round(cur_xR / dx)) + + left_start_idx = max(0, min(count - 1, left_start_idx)) + right_end_idx = max(0, min(count, right_end_idx)) + + if right_end_idx - left_start_idx < 20: + break + + I_inner = I[left_start_idx:right_end_idx].copy() + + if len(I_inner) < 20: + break + + try: + inner_xL11, inner_xL00, inner_errL, inner_xR11, inner_xR00, inner_errR, \ + inner_xL41, inner_xR41, inner_xlr41det = cxlr11(I_inner, I0, 0, conf) + + inner_xL = inner_xL11 + cur_xL + inner_xR = inner_xR11 + cur_xL + + if inner_xL > cur_xL + 0.5: + xL[0, layer_idx] = inner_xL + cur_xL = inner_xL + if inner_xR < cur_xR - 0.5 and inner_xR > cur_xL: + xR[0, layer_idx] = inner_xR + cur_xR = inner_xR + + statusL[0, layer_idx] = inner_errL + statusR[0, layer_idx] = inner_errR + + except Exception: + break + + except Exception: + pass + + IN = np.array(I) if I is not None else np.array([]) + + return xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN + + +def analy01(I, conf, errorin): + conf = np.asarray(conf, dtype=np.float64).ravel() + errorin = np.asarray(errorin, dtype=np.float64).ravel() + + if len(conf) > 19 and abs(conf[19] - 21) < 1e-6: + if len(conf) > 178: + conf[33] = conf[174] + conf[34] = conf[175] + conf[39] = conf[178] + + xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN = _base_analysis( + I, conf, errorin, num_layers=3 + ) + return xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN + + +def anajack2(I, conf, settings, ovrvwmem, errorin): + xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN = _base_analysis( + I, conf, errorin, num_layers=3 + ) + return xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, ovrvwmem, IN + + +def ana_curvefit_tube(I, conf, errorin): + xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN = _base_analysis( + I, conf, errorin, num_layers=3 + ) + return xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN + + +def ana_curvefit_Uponor(I, conf, errorin): + xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN = _base_analysis( + I, conf, errorin, num_layers=3 + ) + return xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN + + +def ana_curvefit_2l_tube(I, conf, errorin, ovrvwmem): + xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, IN = _base_analysis( + I, conf, errorin, num_layers=3 + ) + return xL, xR, status, statusL, statusR, attL, attR, errorlevel, layeruse, ovrvwmem, IN diff --git a/algorithm/detection_utils.py b/algorithm/detection_utils.py new file mode 100644 index 0000000..7ce5852 --- /dev/null +++ b/algorithm/detection_utils.py @@ -0,0 +1,805 @@ +import numpy as np +from scipy.optimize import least_squares + +try: + from .math_utils import ind, polyfit2 + from .geometry_utils import strng2 + from .signal_utils import filter2k3 + from .curve_fit_utils import ( + attcalcx0, attcalcx1, x1fun3, x1fun3setup, x1fun3out, + _simple_lm + ) + from .edge_detection_utils import i0detect +except ImportError: + from math_utils import ind, polyfit2 + from geometry_utils import strng2 + from signal_utils import filter2k3 + from curve_fit_utils import ( + attcalcx0, attcalcx1, x1fun3, x1fun3setup, x1fun3out, + _simple_lm + ) + from edge_detection_utils import i0detect + + +def gauss(s, k): + s = float(s) + k = int(k) + n = np.arange(-(k - 1) / 2, (k - 1) / 2 + 1) + g = np.exp(-n ** 2 / (2 * s ** 2)) + g = g / np.sum(g) + return g + + +def _resfail(resnorm, lengthxt, avgval): + if avgval > 0 and lengthxt > 0: + return resnorm / (lengthxt * avgval) + return 0.0 + + +def edge_error2(calcval, exitflag, resnorm, avgval, startalpha0, + minxt, maxxt, minalpha0, maxalpha0, + mincontr, maxcontr, contrsign, + resmax, diffxt1, diffxt2, lengthxt): + errorl = np.zeros(2, dtype=np.float64) + + if exitflag < 0: + errorl[0] = 51 + else: + if calcval.get('x', 0) < (minxt + diffxt1) or calcval.get('x', 0) > (maxxt - diffxt1): + errorl[1] = 47 + if calcval.get('x', 0) < (minxt + diffxt2) or calcval.get('x', 0) > (maxxt - diffxt2): + errorl[0] = 47 + if calcval.get('alpha0', 0) < minalpha0: + errorl[0] = 52 + if calcval.get('alpha0', 0) > maxalpha0: + errorl[0] = 53 + if abs(calcval.get('alpha1', 0) - calcval.get('alpha0', 0)) < mincontr: + errorl[0] = 54 + kontrast = calcval.get('alpha1', 0) - calcval.get('alpha0', 0) + if ((kontrast < 0 and contrsign == 1) or + (kontrast > 0 and contrsign == -1)): + errorl[0] = 56 + relfail = _resfail(resnorm, lengthxt, avgval) + if relfail > resmax: + errorl[0] = 57 + if calcval.get('x', 0) < minxt or calcval.get('x', 0) > maxxt: + errorl[0] = 46 + + return errorl + + +def mcoldef(errorl): + errorl = np.asarray(errorl, dtype=np.float64).ravel() + if errorl[0]: + return 'r-' + elif len(errorl) > 1 and errorl[1]: + return 'm-' + else: + return 'g-' + + +def attfacthres(k1, dx, ll, leftdetect, Anzpara=0): + k1 = np.asarray(k1, dtype=np.float64).ravel() + + leftindlimit = np.array([], dtype=np.int64) + + hdiffwidth = 0.1 + difflimit = 0.02 + diffoff = 0.4 + + klow2thresh1 = 1.6 + klow2thresh2 = 1.4 + klow2thresh3 = 1.3 + + hdiffwind = int(np.round(hdiffwidth / dx)) + if hdiffwind < 1: + hdiffwind = 1 + + filtpara = np.concatenate([ + -np.ones(hdiffwind), [0.0], np.ones(hdiffwind) + ]) / hdiffwind + filtpara = filtpara / ((hdiffwind + 1) * dx) + + k1diff, _ = filter2k3(filtpara, k1, 2) + + diffoffind = int(np.round(diffoff / dx)) + if diffoffind > len(k1diff): + diffoffind = len(k1diff) + + diffoffvek = np.ones(len(k1diff), dtype=np.float64) + if diffoffind > 0: + diffoffvek[:diffoffind] = 0.0 + + k1trueind = np.where( + (k1diff < difflimit) & (k1diff > -difflimit) & (diffoffvek > 0) + )[0] + + if len(k1trueind) > 0: + klow1 = np.cumsum(k1[k1trueind]) + klow1 = klow1 / np.arange(1, len(k1trueind) + 1) + + klow2 = np.full(len(k1), np.nan) + klow2[k1trueind] = klow1 + + oldvalue = np.nan + for ii in range(len(klow2)): + if np.isnan(klow2[ii]): + klow2[ii] = oldvalue + else: + oldvalue = klow2[ii] + + valid_mask = ~np.isnan(klow2) + if np.any(valid_mask): + idx1 = np.where(k1[valid_mask] >= klow2[valid_mask] * klow2thresh1)[0] + if len(idx1) > 0: + leftindlimit1 = np.where(valid_mask)[0][idx1[0]] + else: + return leftindlimit + + idx2 = np.where(k1[:leftindlimit1 + 1] < klow2[:leftindlimit1 + 1] * klow2thresh2)[0] + if len(idx2) > 0: + leftindlimit2 = idx2[-1] + else: + return leftindlimit + + leftindlimit3vek = np.where(k1[:leftindlimit2 + 1] >= klow2[:leftindlimit2 + 1] * klow2thresh2)[0] + + leftindlimit = np.array([leftindlimit2]) + + runwhile = True + searchind = 0 + while runwhile: + if searchind < len(leftindlimit3vek): + seg_start = leftindlimit3vek[searchind] + seg_end = leftindlimit2 + seg_mean = np.mean(k1[seg_start:seg_end + 1]) + thresh_mean = np.mean(klow2[seg_start:seg_end + 1] * klow2thresh3) + if seg_mean >= thresh_mean: + leftindlimit = np.array([leftindlimit3vek[searchind]]) + runwhile = False + else: + runwhile = False + searchind += 1 + + return leftindlimit + + +def x1_x1r_predetect(x, IN, x0, x0r, dx, Anzpara=0): + IN = np.asarray(IN, dtype=np.float64).ravel() + x = np.asarray(x, dtype=np.float64).ravel() + errorl = np.zeros((2, 2), dtype=np.float64) + prex1 = 0.0 + prex1r = 0.0 + + NN = len(IN) + + ll = int(ind(x0 + dx, dx, 0, NN)) + rr = int(ind(0.5 * (x0 + x0r), dx, 0, NN)) + if ll < rr and ll >= 0 and rr <= NN: + x_seg = x[ll:rr] + s1 = strng2(x_seg, x0, x0r, 1) + IN_seg = IN[ll:rr] + valid = (IN_seg > 0) & (s1 > 0) + if np.any(valid): + k1 = -(np.log(IN_seg[valid])) / s1[valid] + leftdetect = 1 + leftindlimit = attfacthres(k1, dx, ll, leftdetect, Anzpara) + if len(leftindlimit) > 0: + kvalid_idx = np.where(valid)[0] + if leftindlimit[0] < len(kvalid_idx): + prex1 = x_seg[kvalid_idx[leftindlimit[0]]] + else: + prex1 = 0.0 + errorl[0, 0] = 80 + else: + prex1 = 0.0 + errorl[0, 0] = 80 + else: + errorl[0, 0] = 80 + else: + errorl[0, 0] = 80 + + ll_r = int(ind(0.5 * (x0 + x0r), dx, 0, NN)) + rr_r = int(ind(x0r - dx, dx, 0, NN)) + if ll_r < rr_r and ll_r >= 0 and rr_r <= NN: + x_seg_r = x[ll_r:rr_r] + s1_r = strng2(x_seg_r, x0, x0r, 1) + IN_seg_r = IN[ll_r:rr_r] + valid_r = (IN_seg_r > 0) & (s1_r > 0) + if np.any(valid_r): + k1_r = -(np.log(IN_seg_r[valid_r])) / s1_r[valid_r] + k1_r_rev = k1_r[::-1] + leftdetect = 0 + rightindlimit = attfacthres(k1_r_rev, dx, ll_r, leftdetect, Anzpara) + if len(rightindlimit) > 0: + rightindlimit_orig = len(k1_r) - rightindlimit[0] + kvalid_idx_r = np.where(valid_r)[0] + if rightindlimit_orig >= 0 and rightindlimit_orig < len(kvalid_idx_r): + prex1r = x_seg_r[kvalid_idx_r[rightindlimit_orig]] + else: + prex1r = 0.0 + errorl[1, 1] = 80 + else: + prex1r = 0.0 + errorl[1, 1] = 80 + else: + errorl[1, 1] = 80 + else: + errorl[1, 1] = 80 + + return prex1, prex1r, errorl + + +def Autocxlr11(IN, I0, Anzpara, conf): + IN = np.asarray(IN, dtype=np.float64).ravel() + conf = np.asarray(conf, dtype=np.float64).ravel() + + TubePegel = 0.03 + CablePegel = 0.02 + TubeTol = 30 + CableTol = 15 + DistIndMin = 100 + IntDiff = 0.15 + IntRohr = 0.05 + + dx = conf[91] if len(conf) > 91 else 0.1 + dx = float(dx) if dx is not None else 0.1 + if dx == 0: + dx = 0.1 + xl01 = 0.0 + xr01 = 0.0 + xl11 = 0.0 + xr11 = 0.0 + xl41 = 0.0 + xr41 = 0.0 + xlr41det = 0 + errorl = 0 + errorr = 0 + count = len(IN) + Tube = 0 + + filtlength = 11 + rsigma = 0.7 + filtvek = gauss(rsigma * 0.5 * (filtlength - 1), filtlength) + INF, N2 = filter2k3(filtvek, IN) + + Imin, IndImin = np.min(INF), np.argmin(INF) + ObjInd = IndImin + ObjIndL = ObjInd + ObjIndR = ObjInd + + Imaxl = np.max(INF[:ObjIndL + 1]) if ObjIndL >= 0 else 0 + Imaxr = np.max(INF[ObjIndR:]) if ObjIndR < len(INF) else 0 + + Bandbr = 0.98 + DistI0 = conf[34] if len(conf) > 34 else 0 + dxZeile = conf[89] if len(conf) > 89 else dx + midcount = int(np.round(DistI0 / dxZeile)) if dxZeile > 0 else 0 + + Iindl = np.where(INF[:ObjIndL + 1] > Bandbr * Imaxl)[0] + Iindr = np.where(INF[ObjIndR:] > Bandbr * Imaxr)[0] + ObjIndR + + if len(Iindl) > midcount and len(Iindr) > midcount: + Il = np.mean(IN[Iindl]) + Ir = np.mean(IN[Iindr]) + elif len(Iindl) > midcount and len(Iindr) <= midcount: + Il = np.mean(IN[Iindl]) + Ir = Il + elif len(Iindl) <= midcount and len(Iindr) > midcount: + Ir = np.mean(IN[Iindr]) + Il = Ir + else: + errorl = 1 + errorr = 1 + return xl11, errorl, xr11, errorr, xl41, xr41, Tube + + def find_last_ge(arr, thresh, start, end): + seg = arr[start:end + 1] + idx = np.where(seg >= thresh)[0] + if len(idx) > 0: + return idx[-1] + start + return None + + def find_first_ge(arr, thresh, start, end): + seg = arr[start:end + 1] + idx = np.where(seg >= thresh)[0] + if len(idx) > 0: + return idx[0] + start + return None + + xl01_98 = find_last_ge(INF, 0.98 * Il, 0, ObjIndL) + xl01_98 = xl01_98 * dxZeile if xl01_98 is not None else 0 + + xr01_98 = find_first_ge(INF, 0.98 * Ir, ObjIndR, len(INF) - 1) + xr01_98 = xr01_98 * dxZeile if xr01_98 is not None else 0 + + xl01_96 = find_last_ge(INF, 0.96 * Il, 0, ObjIndL) + xl01_96 = xl01_96 * dxZeile if xl01_96 is not None else 0 + + xr01_96 = find_first_ge(INF, 0.96 * Ir, ObjIndR, len(INF) - 1) + xr01_96 = xr01_96 * dxZeile if xr01_96 is not None else 0 + + xl01_94 = find_last_ge(INF, 0.94 * Il, 0, ObjIndL) + xl01_94 = xl01_94 * dxZeile if xl01_94 is not None else 0 + + xr01_94 = find_first_ge(INF, 0.94 * Ir, ObjIndR, len(INF) - 1) + xr01_94 = xr01_94 * dxZeile if xr01_94 is not None else 0 + + xl01_90 = find_last_ge(INF, 0.90 * Il, 0, ObjIndL) + xl01_90 = xl01_90 * dxZeile if xl01_90 is not None else 0 + + xr01_90 = find_first_ge(INF, 0.90 * Ir, ObjIndR, len(INF) - 1) + xr01_90 = xr01_90 * dxZeile if xr01_90 is not None else 0 + + xl01_70 = find_last_ge(INF, 0.70 * Il, 0, ObjIndL) + xl01_70 = xl01_70 * dxZeile if xl01_70 is not None else 0 + + xr01_70 = find_first_ge(INF, 0.70 * Ir, ObjIndR, len(INF) - 1) + xr01_70 = xr01_70 * dxZeile if xr01_70 is not None else 0 + + xl01 = xl01_96 + xr01 = xr01_96 + + IntDiffl = xl01_70 - xl01_96 + IntDiffr = xr01_96 - xr01_70 + + if IntDiffl < IntDiff or IntDiffr < IntDiff: + if (Imin < TubePegel and abs(IntDiffl - IntDiffr) < IntRohr and + xl01_96 > TubeTol and xr01_96 > TubeTol): + Tube = 1 + + xl41 = xl01_98 + xr41 = xr01_98 + + xl11 = xl01 + xr11 = xr01 + + return xl11, errorl, xr11, errorr, xl41, xr41, Tube + + +def AutoDetect(I, conf, errorin, CableType): + I = np.asarray(I, dtype=np.float64).ravel() + conf = np.asarray(conf, dtype=np.float64).ravel() + + AnzPict = 10 + xlr11Offset = 30 + + FoamedPE = 0.014 + PE = 0.08 + PVC = 0.25 + + errorlevel = np.zeros((2, 1), dtype=np.float64) + errorl = 0 + errorr = 0 + DistI0 = conf[34] if len(conf) > 34 else 0 + Lowrad = conf[36] if len(conf) > 36 else 0 + dx = conf[91] if len(conf) > 91 else 0.1 + dx = float(dx) if dx is not None else 0.1 + if dx == 0: + dx = 0.1 + AnzPara = conf[10] if len(conf) > 10 else 0 + + I0, errorlevel_1d = i0detect(I, DistI0, dx, Lowrad, errorin) + errorlevel = np.atleast_2d(errorlevel_1d).reshape(-1, 1) + if errorlevel.shape[0] < 2: + errorlevel = np.pad(errorlevel, ((0, 2 - errorlevel.shape[0]), (0, 0))) + IN = I.copy() + + IN = I / I0 if I0 > 0 else I + xl11, errorl, xr11, errorr, xl41, xr41, Tube = Autocxlr11(IN, I0, AnzPara, conf) + if errorl != 0: + errorlevel[0, 0] = errorl + elif errorr != 0: + errorlevel[0, 0] = errorr + + if CableType.get('Counter', 0) == AnzPict: + CableType_Number = CableType.get('Number', np.zeros(4)) + temp, ID = np.max(CableType_Number), np.argmax(CableType_Number) + if ID == 0: + if temp == 0: + if Tube == 0: + CableType['Type'] = 50 + elif Tube >= 1: + CableType['Type'] = 139 + elif temp != 0: + CableType['Type'] = 7 + CableType['NOMOSC'] = 0 + CableType['NOMINS'] = 0 + CableType['NOMISC'] = 0 + elif ID == 1: + if temp == 0: + CableType['Type'] = 121 + CableType['NOMOSC'] = 0.4 + CableType['NOMINS'] = 0 + CableType['NOMISC'] = 0 + else: + CableType['Type'] = 7 + CableType['NOMOSC'] = 0 + CableType['NOMINS'] = 0 + CableType['NOMISC'] = 0 + elif ID == 2: + if temp == 0: + CableType['Type'] = 119 + CableType['NOMOSC'] = 0.5 + CableType['NOMINS'] = 0 + CableType['NOMISC'] = 0 + else: + CableType['Type'] = 7 + CableType['NOMOSC'] = 0 + CableType['NOMINS'] = 0 + CableType['NOMISC'] = 0 + elif ID == 3: + CableType['Type'] = 118 + CableType['NOMOSC'] = 0.6 + CableType['NOMINS'] = 0 + CableType['NOMISC'] = 0 + + CableType['Counter'] = 0 + + if CableType.get('Counter', 0) < AnzPict: + if errorlevel[0, 0] == 0: + xlr11 = abs(xr11 - xl11) + if xlr11 > 0: + xlr41 = abs(xr41 - xl41) + xlrdiff = xlr11 - xlr41 + if xlrdiff > CableTol: + if 'Number' not in CableType: + CableType['Number'] = np.zeros(4) + CableType['Number'][0] += 1 + elif xlr11Offset < xlr11 < 2 * xlr11Offset: + CableType.setdefault('Number', np.zeros(4)) + CableType['Number'][3] += 1 + else: + att = -np.log(max(Imin, 1e-6)) / max(xlr11, 1e-6) if xlr11 > 0 else 0 + Imin = np.min(IN) if errorlevel[0, 0] == 0 else 0 + if att < FoamedPE: + CableType.setdefault('Number', np.zeros(4)) + CableType['Number'][1] += 1 + elif att < PE: + CableType.setdefault('Number', np.zeros(4)) + CableType['Number'][0] += 1 + elif att < PVC: + CableType.setdefault('Number', np.zeros(4)) + CableType['Number'][2] += 1 + else: + CableType.setdefault('Number', np.zeros(4)) + CableType['Number'][0] += 1 + CableType['Counter'] = CableType.get('Counter', 0) + 1 + + return CableType, errorlevel + + +def x1_x1r_curvefit4(x, y, fun_para_static, modul_para): + x = np.asarray(x, dtype=np.float64).ravel() + y = np.asarray(y, dtype=np.float64).ravel() + + errorlevel = np.zeros((2, 2), dtype=np.float64) + calcpara = np.zeros(4, dtype=np.float64) + + dataout = {} + dataout['alpha0'] = 0.0 + dataout['x1'] = 0.0 + dataout['x1r'] = 0.0 + dataout['alpha1'] = 0.0 + resnorm = np.ones(2, dtype=np.float64) + + dataout['left'] = {'pos': {'result': np.nan}, + 'att': {'outer': np.nan, 'inner': np.nan}} + dataout['right'] = {'pos': {'result': np.nan}, + 'att': {'outer': np.nan, 'inner': np.nan}} + + if len(x) < 2: + return dataout, errorlevel, resnorm + + dx = x[1] - x[0] + N = len(x) + + tol_fun = modul_para.get('TolFun', 1e-6) + tol_x = modul_para.get('TolX', 1e-6) + max_iter = modul_para.get('MaxFunEvals', 400) + display = modul_para.get('display', 0) + + x1_val = fun_para_static.get('x1', 0) + x0_val = fun_para_static.get('x0', 0) + x0r_val = fun_para_static.get('x0r', 0) + filtlength = fun_para_static.get('filtlength', 0) + range_outer = modul_para.get('range_outer', 0) + range_inner = modul_para.get('range_inner', 0) + x1limit_l = modul_para.get('x1limit_l', 0) + x1limit_r = modul_para.get('x1limit_r', 0) + + leftcut = x1_val - range_outer - filtlength + if leftcut < (x1limit_l - filtlength): + leftcut = x1limit_l - filtlength + rightcut = x1_val + range_inner + filtlength + if rightcut > (x1limit_r + filtlength): + rightcut = x1limit_r + filtlength + + l_idx = int(ind(leftcut, dx, 0, N)) + r_idx = int(ind(rightcut, dx, 0, N)) + + if l_idx < r_idx and l_idx >= 0 and r_idx <= N: + xt = x[l_idx:r_idx] + yt = y[l_idx:r_idx] + + if len(xt) > 10: + att0, att1 = attcalcx1(xt, yt, x0_val, x0r_val, + x1_val, fun_para_static.get('x1r', 0), 0) + + fun_startpara = x1fun3setup(fun_para_static, att0, att1) + + try: + result = least_squares( + lambda p: x1fun3(p, fun_para_static, xt, yt)[0], + fun_startpara, method='lm', + ftol=tol_fun, xtol=tol_x, max_nfev=max_iter + ) + calcpara = result.x + resnorm[0] = np.sum(result.fun ** 2) + exitflag = 1 if result.success else -1 + except Exception: + calcpara, resnorm[0], exitflag = _simple_lm( + lambda p: x1fun3(p, fun_para_static, xt, yt)[0], + fun_startpara, tol_fun, tol_x, max_iter + ) + + _, fun_para_static['reg_sub'], _ = x1fun3(calcpara, fun_para_static, xt, yt) + dataoutleft = x1fun3out(calcpara, fun_para_static) + + calcval = { + 'alpha0': dataoutleft.get('alpha0', 0), + 'alpha1': dataoutleft.get('alpha1', 0), + 'x': dataoutleft.get('x1', 0) + } + + dataout['left']['pos']['result'] = calcval['x'] + dataout['left']['att']['inner'] = calcval['alpha1'] + dataout['left']['att']['outer'] = calcval['alpha0'] + + minxt = np.min(xt) + maxxt = np.max(xt) + errorlevel[:, 0] = edge_error2( + calcval, exitflag, resnorm[0], np.mean(yt), att0, + minxt, maxxt, + modul_para.get('minatt1', 0), modul_para.get('maxatt1', 1), + modul_para.get('mincontr', 0), modul_para.get('maxcontr', 100), + modul_para.get('contrsign', 0), + modul_para.get('resmax', 1), + 0.1 * (maxxt - minxt), 0.05 * (maxxt - minxt), + len(yt) + ) + else: + errorlevel[0, 0] = 50 + else: + errorlevel[0, 0] = 50 + + x1r_val = fun_para_static.get('x1r', 0) + x1rlimit_l = modul_para.get('x1rlimit_l', 0) + x1rlimit_r = modul_para.get('x1rlimit_r', 0) + + leftcut_r = x1r_val - range_inner - filtlength + if leftcut_r < (x1rlimit_l - filtlength): + leftcut_r = x1rlimit_l - filtlength + rightcut_r = x1r_val + range_outer + filtlength + if rightcut_r > (x1rlimit_r + filtlength): + rightcut_r = x1rlimit_r + filtlength + + l_idx_r = int(ind(leftcut_r, dx, 0, N)) + r_idx_r = int(ind(rightcut_r, dx, 0, N)) + + if l_idx_r < r_idx_r and l_idx_r >= 0 and r_idx_r <= N: + xt_r = x[l_idx_r:r_idx_r] + yt_r = y[l_idx_r:r_idx_r] + + if len(xt_r) > 10: + att0_r, att1_r = attcalcx1(xt_r, yt_r, x0_val, x0r_val, + x1_val, x1r_val, 1) + + fun_startpara_r = x1fun3setup(fun_para_static, att0_r, att1_r) + + try: + result_r = least_squares( + lambda p: x1fun3(p, fun_para_static, xt_r, yt_r)[0], + fun_startpara_r, method='lm', + ftol=tol_fun, xtol=tol_x, max_nfev=max_iter + ) + calcpara_r = result_r.x + resnorm[1] = np.sum(result_r.fun ** 2) + exitflag_r = 1 if result_r.success else -1 + except Exception: + calcpara_r, resnorm[1], exitflag_r = _simple_lm( + lambda p: x1fun3(p, fun_para_static, xt_r, yt_r)[0], + fun_startpara_r, tol_fun, tol_x, max_iter + ) + + _, fun_para_static['reg_sub'], _ = x1fun3(calcpara_r, fun_para_static, xt_r, yt_r) + dataoutright = x1fun3out(calcpara_r, fun_para_static) + + calcval_r = { + 'alpha0': dataoutright.get('alpha0', 0), + 'alpha1': dataoutright.get('alpha1', 0), + 'x': dataoutright.get('x1r', 0) + } + + dataout['right']['pos']['result'] = calcval_r['x'] + dataout['right']['att']['inner'] = calcval_r['alpha1'] + dataout['right']['att']['outer'] = calcval_r['alpha0'] + + minxt_r = np.min(xt_r) + maxxt_r = np.max(xt_r) + errorlevel[:, 1] = edge_error2( + calcval_r, exitflag_r, resnorm[1], np.mean(yt_r), att0_r, + minxt_r, maxxt_r, + modul_para.get('minatt1', 0), modul_para.get('maxatt1', 1), + modul_para.get('mincontr', 0), modul_para.get('maxcontr', 100), + modul_para.get('contrsign', 0), + modul_para.get('resmax', 1), + 0.1 * (maxxt_r - minxt_r), 0.05 * (maxxt_r - minxt_r), + len(yt_r) + ) + else: + errorlevel[0, 1] = 50 + else: + errorlevel[0, 1] = 50 + + dataoutleft = dataout['left'] + dataoutright = dataout['right'] + + if errorlevel[0, 0] == 0 and errorlevel[0, 1] == 0: + dataout['alpha0'] = 0.5 * (dataoutleft['att']['outer'] + dataoutright['att']['outer']) + dataout['x1'] = dataoutleft['pos']['result'] + dataout['x1r'] = dataoutright['pos']['result'] + dataout['alpha1'] = 0.5 * (dataoutleft['att']['inner'] + dataoutright['att']['inner']) + elif errorlevel[0, 0] == 0: + dataout['alpha0'] = dataoutleft['att']['outer'] + dataout['x1'] = dataoutleft['pos']['result'] + dataout['x1r'] = 0 + dataout['alpha1'] = dataoutleft['att']['inner'] + elif errorlevel[0, 1] == 0: + dataout['alpha0'] = dataoutright['att']['outer'] + dataout['x1'] = 0 + dataout['x1r'] = dataoutright['pos']['result'] + dataout['alpha1'] = dataoutright['att']['inner'] + + return dataout, errorlevel, resnorm + + +def cxlr11(I, I0, Anzpara, conf): + from math_utils import is_pe + conf = np.asarray(conf, dtype=np.float64).ravel() + I = np.asarray(I, dtype=np.float64).ravel() + + conf20 = conf[19] if len(conf) > 19 else 0 + + if is_pe(conf20): + Pegel00 = conf[120] / 100.0 if len(conf) > 120 else 0.5 + Lowpegel11 = conf[121] / 100.0 if len(conf) > 121 else 0.2 + Highpegel11 = conf[122] / 100.0 if len(conf) > 122 else 0.8 + else: + Pegel00 = conf[37] / 100.0 if len(conf) > 37 else 0.5 + Lowpegel11 = conf[38] / 100.0 if len(conf) > 38 else 0.2 + Highpegel11 = conf[39] / 100.0 if len(conf) > 39 else 0.8 + + dx = conf[91] if len(conf) > 91 else 0.048 + dx = float(dx) if dx is not None else 0.048 + if dx == 0: + dx = 0.048 + + xl00, xr00 = 0.0, 0.0 + xl01, xr01 = 0.0, 0.0 + xl11, xr11 = 0.0, 0.0 + xl41, xr41 = 0.0, 0.0 + xlr41det = 0 + errorl, errorr = 0, 0 + count = len(I) + NOMINS = conf[8] if len(conf) > 8 else 0 + + I_slice = I[1:count-1] + Iind = np.where(I_slice >= Pegel00 * I0)[0] + + if len(Iind) > 0: + startind1 = Iind[0] + 2 + stopind1 = Iind[-1] + 2 + + xl00 = (startind1 - 1) * dx + xr00 = (stopind1 - 1) * dx + + I_mid = I[startind1-1:stopind1] + Iind2 = np.where(I_mid <= Lowpegel11 * I0)[0] + + if (len(Iind2) == 0 and errorl == 0 and errorr == 0 and NOMINS == 0 and + 131 <= conf20 <= 150): + filtlength = 11 + rsigma = 0.7 + from math_utils import gauss + from signal_utils import filter2k3 + filtvek = gauss(rsigma * 0.5 * (filtlength - 1), filtlength) + try: + INF, N2 = filter2k3(filtvek, I) + Imin = np.min(INF[:len(INF)]) + IminPegel = Imin / I0 + if IminPegel < (Pegel00 - 0.01): + Iind2 = np.where(I_mid <= (IminPegel + 0.01) * I0)[0] + except Exception: + pass + + if len(Iind2) > 0: + startind2 = Iind2[0] + startind1 + stopind2 = Iind2[-1] + startind1 + + xl01 = (startind2 - 1) * dx + xr01 = (stopind2 - 1) * dx + + I_left = I[startind1-1:startind2] + Iind3 = np.where(I_left >= Highpegel11 * I0)[0] + if len(Iind3) > 0: + stopind3 = Iind3[-1] + startind1 + xl11 = (stopind3 - 1) * dx + else: + errorl = 4 + + I_right = I[stopind2-1:stopind1] + Iind4 = np.where(I_right >= Highpegel11 * I0)[0] + if len(Iind4) > 0: + startind3 = Iind4[0] + stopind2 + xr11 = (startind3 - 1) * dx + else: + errorr = 4 + else: + errorl = 4 + errorr = 4 + else: + errorl = 4 + errorr = 4 + + if errorl == 0 and errorr == 0: + if ((131 <= conf20 <= 150 and NOMINS == 0) or (105 <= conf20 <= 110)): + DistIndMin = 100 if conf20 == 144 else 25 + DistMin = 10 if (105 <= conf20 <= 110) else 1.0 + + filtlength = 11 + rsigma = 0.7 + from math_utils import gauss + from signal_utils import filter2k3 + filtvek = gauss(rsigma * 0.5 * (filtlength - 1), filtlength) + try: + INF, N2 = filter2k3(filtvek, I) + Imin = np.min(INF[:len(INF)]) + ObjInd_arr = np.where(INF[:len(INF)] <= Imin)[0] + if len(ObjInd_arr) > 0: + ObjInd = ObjInd_arr[0] + left_end = max(0, ObjInd - DistIndMin) + right_start = min(len(INF), ObjInd + DistIndMin) + + Imin1 = np.min(INF[:left_end]) if left_end > 0 else Imin + Imin2 = np.min(INF[right_start:]) if right_start < len(INF) else Imin + + if Imin2 < Imin1: + right_arr = np.where(INF[right_start:] <= Imin2)[0] + ObjIndR = right_start + (right_arr[-1] if len(right_arr) > 0 else 0) + ObjIndL = ObjInd + else: + left_arr = np.where(INF[:left_end] <= Imin1)[0] + ObjIndL = left_arr[0] if len(left_arr) > 0 else 0 + ObjIndR = ObjInd + + mid_point = round(ObjIndL + (ObjIndR - ObjIndL) / 2) + IminL, IndMinL = np.min(INF[ObjIndL:mid_point]), np.argmin(INF[ObjIndL:mid_point]) + IminR, IndMinR = np.min(INF[mid_point:ObjIndR]), np.argmin(INF[mid_point:ObjIndR]) + + DistL = abs(((ObjIndL + IndMinL - 1) * dx) - xl11) + DistR = abs(((mid_point + IndMinR - 1) * dx) - xr11) + + if DistL < DistMin or DistR < DistMin: + xl41 = xl11 + DistL + xr41 = xr11 - DistR + xlr41det = 1 + + if conf20 == 144: + xl41 = ObjIndL * dx + xr41 = ObjIndR * dx + xlr41det = 2 + except Exception: + pass + + return xl11, xl00, errorl, xr11, xr00, errorr, xl41, xr41, xlr41det diff --git a/algorithm/edge_detection_utils.py b/algorithm/edge_detection_utils.py new file mode 100644 index 0000000..8ee5366 --- /dev/null +++ b/algorithm/edge_detection_utils.py @@ -0,0 +1,1230 @@ +import numpy as np + +try: + from .math_utils import ind + from .extremum_utils import minmax, minmax2, findmaxima, lowlimit + from .signal_utils import filter2k3 + from .geometry_utils import strng2 +except ImportError: + from math_utils import ind + from extremum_utils import minmax, minmax2, findmaxima, lowlimit + from signal_utils import filter2k3 + from geometry_utils import strng2 + + +def i0detect(I, DistI0, dx, Lowrad, errorin): + I0 = 1.0 + errorlevel = np.zeros(2, dtype=np.float64) + + dx = float(dx) if dx is not None else 0.048 + if dx == 0: + dx = 0.048 + + if len(I) == 0: + errorin[0] = 9 + + errorlevel[0] = errorin[0] if len(errorin) > 0 else 0 + errorlevel[1] = errorin[1] if len(errorin) > 1 else 0 + + count = len(I) + Imax = np.max(I) + limitfak1 = 0.95 + limitfak2 = 0.90 + midcount = int(np.round(DistI0 / dx)) + + run = 1 + i = 1 + startind = 0 + while run: + if I[i] > limitfak1 * Imax: + startind = i + run = 0 + elif i == count - 1: + run = 0 + else: + i = i + 1 + + if startind > 0: + run = 1 + else: + run = 0 + i = startind + stopind = 0 + while run: + if (I[i] < limitfak2 * Imax) or (i > (startind + 2 * midcount)): + stopind = i + run = 0 + elif i == count - 1: + run = 0 + else: + i = i + 1 + + Il = 1.0 + if (startind > 0) and (stopind > 0) and ((stopind - startind) > midcount): + Anz = stopind - startind + 1 + Il = 1.0 + np.sum(I[startind:stopind + 1]) + Il = Il / Anz + + run = 1 + i = count - 2 + startind = 0 + while run: + if I[i] > limitfak1 * Imax: + startind = i + run = 0 + elif i == 0: + run = 0 + else: + i = i - 1 + + if startind > 0: + run = 1 + else: + run = 0 + i = startind + stopind = 0 + while run: + if (I[i] < limitfak2 * Imax) or (i < (startind - 2 * midcount)): + stopind = i + run = 0 + elif i == 0: + run = 0 + else: + i = i - 1 + + Ir = 1.0 + if (startind > 0) and (stopind > 0) and ((startind - stopind) > midcount): + Anz = startind - stopind + 1 + Ir = 1.0 + np.sum(I[stopind:startind + 1]) + Ir = Ir / Anz + + if ((Il / Ir) > 0.985) and ((Il / Ir) < 1.015): + I0 = (Il + Ir) / 2.0 + else: + if Il > Ir: + I0 = Il + else: + I0 = Ir + + if Imax > 1.1 * I0: + I0 = Imax + errorlevel[0] = 1 + + if I0 < Lowrad and Lowrad >= 1000: + errorlevel[1] = 9 + if I0 < 2250: + errorlevel[0] = 112 + errorlevel[1] = 0 + + if errorin[1] != 0: + errorlevel[1] = errorin[1] + + return I0, errorlevel + + +def i0det2(I, xl11, xr11, conf, errin=None): + if errin is not None and len(errin) >= 2: + errorlevel = np.array(errin[:2], dtype=np.float64) + else: + errorlevel = np.zeros(2, dtype=np.float64) + + if errorlevel[0] != 0: + return 1.0, errorlevel + + I0 = 1.0 + dx = conf[91] if len(conf) > 91 else 0.1 + dx = float(dx) if dx is not None else 0.1 + if dx == 0: + dx = 0.1 + count = len(I) + I0diff = conf[33] / 100.0 if len(conf) > 33 else 0.015 + DistI0 = conf[34] if len(conf) > 34 else 3.0 + Dist01 = 0.1 + + Indl = ind(xl11 - Dist01 - DistI0, dx, 0, count) + Indr = ind(xl11 - Dist01, dx, 0, count) + Indl = int(Indl) + Indr = int(Indr) + Anz = Indr - Indl + 1 + if Anz < 20: + errorlevel[0] = 25 + return I0, errorlevel + Il = np.sum(I[Indl - 1:Indr]) + Il = Il / Anz + + Indl = int(ind(xr11 + Dist01, dx, 0, count)) + if Indl > count: + Indl = count + Indr = int(ind(xr11 + Dist01 + DistI0, dx, 0, count)) + if Indr > count: + Indr = count + Anz = Indr - Indl + 1 + if Anz < 20: + errorlevel[0] = 25 + return I0, errorlevel + Ir = np.sum(I[Indl - 1:Indr]) + Ir = Ir / Anz + + if ((Il / Ir) > (1 - I0diff)) and ((Il / Ir) < (1 + I0diff)): + I0 = (Il + Ir) / 2.0 + else: + errorlevel[0] = 25 + if Il > Ir: + I0 = Il + else: + I0 = Ir + + return I0, errorlevel + + +def x41det2(x, IN, conf): + xl11 = conf[0] + xr11 = conf[1] + Dist41 = conf[2] + I0 = conf[3] + Offpegel41 = conf[4] + Off41 = conf[5] + Minpegel41 = conf[7] if len(conf) > 7 else 0 + Minidiff = conf[8] if len(conf) > 8 else 0 + Ber = conf[9] if len(conf) > 9 else 0 + Anzpara = conf[10] if len(conf) > 10 else 0 + dx = conf[11] if len(conf) > 11 else 0.1 + Maximumc = conf[12] if len(conf) > 12 else 0 + CableType = conf[13] if len(conf) > 13 else 0 + xr41det = conf[14] if len(conf) > 14 else 0 + alpha0 = None + if len(conf) > 15: + alpha0 = conf[15] + level = 0 + if len(conf) > 16: + level = conf[16] + + if CableType == 22: + if (xr11 - xl11) < 40: + Filtertyp = 2 + else: + Filtertyp = 3 + elif CableType == 7: + if alpha0 is None: + alpha0 = 0.01 + IN_bp, _ = lowlimit(IN, np.exp(-alpha0 * (xr11 - xl11))) + IN = IN_bp + Offpegel41 = 0 + Off41 = 0 + Filtertyp = 4 + elif (CableType == 2) or (CableType == 63500000): + alpha0 = 0.2 + maxsehne = (xr11 - xl11) + bp = np.exp(-alpha0 * maxsehne) + mindetlevel = 0.01 + if bp < mindetlevel: + bp = mindetlevel + IN_bp, _ = lowlimit(IN, bp) + IN = IN_bp + Offpegel41 = 0 + Off41 = 0 + Filtertyp = 1 + else: + Filtertyp = 1 + + if Filtertyp == 1: + lengthref1 = 0.09 + lengthref2 = 0.06 + shiftlength = 0.15 + gain = 4.75 + fpara1 = np.ones(int(np.round(lengthref1 / dx)) + 1) + fpara1 = (1.0 / len(fpara1)) * fpara1 + fpara2 = np.zeros(int(np.round(lengthref2 / dx)) + 1) + filtpara = np.concatenate([-fpara1, fpara2, fpara1]) * gain + shiftind = int(np.round(shiftlength / dx)) + 1 + elif Filtertyp == 2: + lengthref1 = 0.09 + lengthref2 = 0.78 + shiftlength = 0.45 + gain = 2.1492 + fpara1 = -1 * np.ones(int(np.round(lengthref1 / dx)) + 1) + fpara1 = (1.0 / len(fpara1)) * fpara1 + fpara2 = np.ones(int(np.round(lengthref2 / dx)) + 1) + fpara2 = (1.0 / len(fpara2)) * fpara2 + filtpara = np.concatenate([fpara1, fpara2]) * gain + shiftind = int(np.round(shiftlength / dx)) + 1 + elif Filtertyp == 3: + lengthref1 = 0.09 + lengthref2 = 1.74 + shiftlength = 0.9 + gain = 1.056 + fpara1 = -1 * np.ones(int(np.round(lengthref1 / dx)) + 1) + fpara1 = (1.0 / len(fpara1)) * fpara1 + fpara2 = np.ones(int(np.round(lengthref2 / dx)) + 1) + fpara2 = (1.0 / len(fpara2)) * fpara2 + filtpara = np.concatenate([fpara1, fpara2]) * gain + shiftind = int(np.round(shiftlength / dx)) + 1 + elif Filtertyp == 4: + lengthref1 = 0.09 + lengthref2 = 0.12 + shiftlength = 0.09 + gain = 2.1492 + fpara1 = -1 * np.ones(int(np.round(lengthref1 / dx)) + 1) + fpara1 = (1.0 / len(fpara1)) * fpara1 + fpara2 = np.ones(int(np.round(lengthref2 / dx)) + 1) + fpara2 = (1.0 / len(fpara2)) * fpara2 + filtpara = np.concatenate([fpara1, fpara2]) * gain + shiftind = int(np.round(shiftlength / dx)) + 1 + else: + filtpara = np.array([1.0]) + shiftind = 1 + + errorlevel = np.zeros(2, dtype=np.float64) + + if xr41det: + filtpara = filtpara[::-1] + + NN = len(IN) + if Dist41 < dx: + Dist41 = dx + if xr41det: + ll = int(ind(xl11 + (xr11 - xl11) / 2, dx, 0, NN)) + rr = int(ind(xr11 - Dist41, dx, 0, NN)) + else: + ll = int(ind(xl11 + Dist41, dx, 0, NN)) + rr = int(ind(xl11 + (xr11 - xl11) / 2, dx, 0, NN)) + + Offset = Offpegel41 + Off41 / I0 + + x41 = 0.0 + if (x[ll - 1] > xl11) and (x[rr - 1] < xr11) and (ll < rr): + s1 = strng2(x[ll - 1:rr], xl11, xr11) + k1 = -(np.log((IN[ll - 1:rr] + Offset) / (1 + Offset))) / s1 + k1 = np.nan_to_num(k1, nan=0.0, posinf=0.0, neginf=0.0) + + Idiff, N2 = filter2k3(filtpara, k1, 2) + + if CableType == 63500000: + x41_idx = findmaxima(Idiff, 0.6, not xr41det) + Minidiffv = Idiff[int(x41_idx) - 1] if int(x41_idx) > 0 else 0 + elif CableType == 118: + Minidiffv, x41_idx = minmax2(Idiff, Maximumc, xr41det, level) + x41_idx = np.round(x41_idx) + else: + Minidiffv, x41_idx = minmax(Idiff, Maximumc) + x41_idx = np.round(x41_idx) + + if xr41det: + x41_idx = x41_idx + (ll - 1) + shiftind + else: + x41_idx = x41_idx + (ll - 1) - shiftind + + x41_idx = int(np.clip(x41_idx, 1, NN)) + Relpegelx41 = IN[x41_idx - 1] + if (IN[x41_idx - 1] * I0 < Minpegel41): + errorlevel[0] = 7 + + x41 = (x41_idx - 1) * dx + if abs(Minidiffv) < Minidiff: + errorlevel[0] = 7 + else: + x41 = 0.0 + errorlevel[0] = 7 + + return x41, errorlevel + + +def DaeMinMaxDet(DaeKurve, LR, Tube, StartInd, DeltaMinMax): + Grenze = 6 + + MaxAnz = 0 + MinAnz = 0 + IndMax = np.array([], dtype=np.float64) + IndMin = np.array([], dtype=np.float64) + Maximum = np.zeros((2, 1), dtype=np.float64) + Minimum = np.zeros((2, 1), dtype=np.float64) + l = 0 + k = 0 + m = 0 + BitMax = 0 + BitMin = 0 + + DaeKurve = np.asarray(DaeKurve, dtype=np.float64).copy() + + if len(DaeKurve) == 0: + return MaxAnz, MinAnz, IndMax, IndMin + + IndGrenze = 0 + if LR == 0: + k = 0 + for i in range(len(DaeKurve)): + if np.isinf(DaeKurve[i]) or np.isnan(DaeKurve[i]): + DaeKurve[i] = 0 + elif k < Grenze: + DaeKurve[i] = 0 + k = k + 1 + IndGrenze = i + 1 + k = 0 + elif LR == 1: + k = 0 + for i in range(len(DaeKurve) - 1, -1, -1): + if np.isinf(DaeKurve[i]) or np.isnan(DaeKurve[i]): + DaeKurve[i] = 0 + elif k < Grenze: + DaeKurve[i] = 0 + k = k + 1 + IndGrenze = i - 1 + k = 0 + + for i in range(1, len(DaeKurve) - 1): + if DaeKurve[i] != 0: + if (DaeKurve[i - 1] < DaeKurve[i]) and (DaeKurve[i] > DaeKurve[i + 1]): + if (Maximum[0, l] == 0) and (i != IndGrenze): + Maximum[0, l] = DaeKurve[i] + Maximum[1, l] = i + BitMax = 1 + + if (DaeKurve[i] > Maximum[0, l]) and (Maximum[0, l] != 0): + if DaeKurve[i] <= Maximum[0, l] + DeltaMinMax: + Maximum[0, l] = DaeKurve[i] + Maximum[1, l] = i + BitMax = 1 + else: + if (Minimum.shape[1] > 1) and (Maximum.shape[1] == 1): + Maximum[0, l] = DaeKurve[i] + Maximum[1, l] = i + BitMax = 1 + else: + Minimum = np.column_stack([Minimum, np.zeros(2)]) + Minimum[0, m] = Maximum[0, l] + Minimum[1, m] = Maximum[1, 0] + Maximum[0, l] = DaeKurve[i] + Maximum[1, l] = i + BitMax = 1 + m = m + 1 + + if (DaeKurve[i - 1] > DaeKurve[i]) and (DaeKurve[i] < DaeKurve[i + 1]): + if Minimum[0, m] == 0: + Minimum[0, m] = DaeKurve[i] + Minimum[1, m] = i + BitMin = 1 + + if DaeKurve[i] < Minimum[0, m]: + if DaeKurve[i] >= Minimum[0, m] - DeltaMinMax: + Minimum[0, m] = DaeKurve[i] + Minimum[1, m] = i + BitMin = 1 + else: + if (Maximum.shape[1] > 1) and (Minimum.shape[1] == 1): + Minimum[0, m] = DaeKurve[i] + Minimum[1, m] = i + BitMin = 1 + else: + Maximum = np.column_stack([Maximum, np.zeros(2)]) + Maximum[0, l] = Minimum[0, m] + Maximum[1, l] = Minimum[1, m] + Minimum[0, m] = DaeKurve[i] + Minimum[1, m] = i + BitMin = 1 + l = l + 1 + + if BitMin == 1: + MaxValue = 0 + if Maximum[0, l] != 0: + MaxValue = Maximum[0, l] + elif Maximum.shape[1] > 1: + MaxValue = Maximum[0, l - 1] + + if MaxValue != 0: + if Minimum[0, m] <= MaxValue - DeltaMinMax: + if Minimum[0, l if l < m else m] != 0: + pass + if Maximum[0, l] != 0: + l = l + 1 + Maximum = np.column_stack([Maximum, np.zeros(2)]) + Maximum[0, l] = 0 + Maximum[1, l] = 0 + else: + Minimum[0, m] = 0 + Minimum[1, m] = 0 + + BitMin = 0 + + if BitMax == 1: + MinValue = 0 + if Minimum[0, m] != 0: + MinValue = Minimum[0, m] + elif Minimum.shape[1] > 1: + MinValue = Minimum[0, m - 1] + + if MinValue != 0: + if Maximum[0, l] > MinValue + DeltaMinMax: + if Minimum[0, m] != 0: + m = m + 1 + Minimum = np.column_stack([Minimum, np.zeros(2)]) + Minimum[0, m] = 0 + Minimum[1, m] = 0 + else: + Maximum[0, l] = 0 + Maximum[1, l] = 0 + + BitMax = 0 + + temp = np.where(Maximum[0, :] != 0)[0] + if len(temp) > 0: + MaxAnz = len(temp) + IndMax = Maximum[1, temp] + StartInd + temp = np.where(Minimum[0, :] != 0)[0] + if len(temp) > 0: + MinAnz = len(temp) + IndMin = Minimum[1, temp] + StartInd + + return MaxAnz, MinAnz, IndMax, IndMin + + +def GradMinMaxDet(grad, LR, DaeGrad, MinMax, Tube, Indxlr11): + if Tube == 0: + if (LR == 0) and (DaeGrad == 1) and (MinMax == 1): + ThrAttGrad = 5e-4 + elif (LR == 0) and (DaeGrad == 1) and (MinMax == 0): + ThrAttGrad = 2.5e-3 + elif (LR == 1) and (DaeGrad == 1) and (MinMax == 0): + ThrAttGrad = 5e-4 + elif (LR == 1) and (DaeGrad == 1) and (MinMax == 1): + ThrAttGrad = 2.5e-3 + else: + ThrAttGrad = 1e-3 + else: + if (LR == 0) and (DaeGrad == 1) and (MinMax == 1): + ThrAttGrad = 5e-4 + elif (LR == 0) and (DaeGrad == 1) and (MinMax == 0): + ThrAttGrad = 1.5e-3 + elif (LR == 1) and (DaeGrad == 1) and (MinMax == 0): + ThrAttGrad = 5e-4 + elif (LR == 1) and (DaeGrad == 1) and (MinMax == 1): + ThrAttGrad = 1.5e-3 + else: + ThrAttGrad = 1e-3 + + if (Tube == 0) or (Tube == 1): + if (LR == 0) and (DaeGrad == 2) and (MinMax == 1): + ThrAttGrad = 5e-4 + elif (LR == 0) and (DaeGrad == 2) and (MinMax == 0): + ThrAttGrad = 1.5e-3 + elif (LR == 1) and (DaeGrad == 2) and (MinMax == 0): + ThrAttGrad = 5e-4 + elif (LR == 1) and (DaeGrad == 2) and (MinMax == 1): + ThrAttGrad = 1.5e-3 + + if Tube == 0: + IndexGrenze = 5 + else: + IndexGrenze = 7 + if DaeGrad == 2: + IndexGrenze = 100 + + if Tube == 0: + ThrNoiseGrad = 0.5 + else: + ThrNoiseGrad = 0.4 + + if DaeGrad == 1: + ThrNoiseDae = 0.5 + elif DaeGrad == 2: + ThrNoiseDae = 0.2 + else: + ThrNoiseDae = 0.5 + + j = 0 + k = 0 + MinAnz = 0 + MaxAnz = 0 + IndMinGrad = np.array([], dtype=np.float64) + IndMaxGrad = np.array([], dtype=np.float64) + Minimum = np.zeros((2, 0), dtype=np.float64) + Maximum = np.zeros((2, 0), dtype=np.float64) + + grad = np.asarray(grad, dtype=np.float64) + + for i in range(1, len(grad) - 1): + if (grad[i] < grad[i - 1]) and (grad[i] < grad[i + 1]): + Minimum = np.column_stack([Minimum, np.array([grad[i], i])]) + j = j + 1 + + for i in range(1, len(grad) - 1): + if (grad[i] > grad[i - 1]) and (grad[i] > grad[i + 1]): + Maximum = np.column_stack([Maximum, np.array([grad[i], i])]) + k = k + 1 + + if LR == 0: + if DaeGrad == 0: + if Minimum.shape[1] > 0: + Ind = np.where(Minimum[0, :])[0] + if len(Ind) > 0: + MinimumMean = np.mean(Minimum[0, Ind]) + else: + MinimumMean = 0 + for j_idx in range(Minimum.shape[1]): + if Minimum[0, j_idx] > MinimumMean: + Minimum[0, j_idx] = 0 + Minimum[1, j_idx] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + if len(IndMinAnz) > 1: + for i in range(len(IndMinAnz) - 1): + Index = Minimum[1, IndMinAnz[i]] + Value = Minimum[0, IndMinAnz[i]] + IndexNext = Minimum[1, IndMinAnz[i + 1]] + ValueNext = Minimum[0, IndMinAnz[i + 1]] + if (IndexNext - Index) <= IndexGrenze: + if abs(Value) < abs(ValueNext): + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + elif abs(Value) > abs(ValueNext): + if i < (len(IndMinAnz) - 1): + IndexNext2 = Minimum[1, IndMinAnz[i + 2]] + ValueNext2 = Minimum[0, IndMinAnz[i + 2]] + if (IndexNext2 - IndexNext) <= IndexGrenze: + if abs(Value) < abs(ValueNext2): + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + elif abs(Value) > abs(ValueNext2): + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + Minimum[0, IndMinAnz[i + 2]] = 0 + Minimum[1, IndMinAnz[i + 2]] = 0 + else: + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + else: + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + MinValue = np.min(Minimum[0, :]) if len(Minimum[0, :]) > 0 else 0 + if len(IndMinAnz) > 1: + for i in range(len(IndMinAnz)): + Value = Minimum[0, IndMinAnz[i]] + if MinValue != 0 and abs(Value / MinValue) < ThrNoiseGrad: + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + if len(IndMinAnz) > 0: + MinAnz = len(IndMinAnz) + IndMinGrad = Minimum[1, IndMinAnz] + + elif DaeGrad == 1: + if MinMax == 1: + if Maximum.shape[1] > 0: + Ind = np.where(Maximum[0, :])[0] + if len(Ind) > 0: + MaximumMean = np.mean(Maximum[0, Ind]) + else: + MaximumMean = 0 + for i in range(Maximum.shape[1]): + if Maximum[0, i] < MaximumMean: + Maximum[0, i] = 0 + Maximum[1, i] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + if len(IndMaxAnz) > 1: + for i in range(len(IndMaxAnz) - 1): + Index = Maximum[1, IndMaxAnz[i]] + Value = Maximum[0, IndMaxAnz[i]] + IndexNext = Maximum[1, IndMaxAnz[i + 1]] + ValueNext = Maximum[0, IndMaxAnz[i + 1]] + if (IndexNext - Index) <= IndexGrenze: + if abs(Value) < abs(ValueNext): + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + elif abs(Value) > abs(ValueNext): + if i < (len(IndMaxAnz) - 1): + IndexNext2 = Maximum[1, IndMaxAnz[i + 2]] + ValueNext2 = Maximum[0, IndMaxAnz[i + 2]] + if (IndexNext2 - IndexNext) <= IndexGrenze: + if abs(Value) < abs(ValueNext2): + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + elif abs(Value) > abs(ValueNext2): + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + Maximum[0, IndMaxAnz[i + 2]] = 0 + Maximum[1, IndMaxAnz[i + 2]] = 0 + else: + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + else: + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + MaxValue = np.max(Maximum[0, :]) if len(Maximum[0, :]) > 0 else 0 + if len(IndMaxAnz) > 1: + for i in range(len(IndMaxAnz)): + Value = Maximum[0, IndMaxAnz[i]] + if MaxValue != 0 and abs(Value / MaxValue) < ThrNoiseDae: + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + for i in range(len(IndMaxAnz)): + Value = Maximum[0, IndMaxAnz[i]] + if abs(Value) < ThrAttGrad: + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + if len(IndMaxAnz) > 0: + if abs(Maximum[1, IndMaxAnz[0]] - Indxlr11) < 15: + Maximum[0, IndMaxAnz[0]] = 0 + Maximum[1, IndMaxAnz[0]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + if len(IndMaxAnz) > 0: + MaxAnz = len(IndMaxAnz) + IndMaxGrad = Maximum[1, IndMaxAnz] + + elif MinMax == 0: + if Minimum.shape[1] > 0: + Ind = np.where(Minimum[0, :])[0] + if len(Ind) > 0: + MinimumMean = np.mean(Minimum[0, Ind]) + else: + MinimumMean = 0 + for j_idx in range(Minimum.shape[1]): + if Minimum[0, j_idx] > MinimumMean: + Minimum[0, j_idx] = 0 + Minimum[1, j_idx] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + if len(IndMinAnz) > 1: + for i in range(len(IndMinAnz) - 1): + Index = Minimum[1, IndMinAnz[i]] + Value = Minimum[0, IndMinAnz[i]] + IndexNext = Minimum[1, IndMinAnz[i + 1]] + ValueNext = Minimum[0, IndMinAnz[i + 1]] + if (IndexNext - Index) <= IndexGrenze: + if abs(Value) < abs(ValueNext): + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + elif abs(Value) > abs(ValueNext): + if i < (len(IndMinAnz) - 1): + IndexNext2 = Minimum[1, IndMinAnz[i + 2]] + ValueNext2 = Minimum[0, IndMinAnz[i + 2]] + if (IndexNext2 - IndexNext) <= IndexGrenze: + if abs(Value) < abs(ValueNext2): + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + elif abs(Value) > abs(ValueNext2): + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + Minimum[0, IndMinAnz[i + 2]] = 0 + Minimum[1, IndMinAnz[i + 2]] = 0 + else: + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + else: + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + MinValue = np.min(Minimum[0, :]) if len(Minimum[0, :]) > 0 else 0 + if len(IndMinAnz) > 1: + for i in range(len(IndMinAnz)): + Value = Minimum[0, IndMinAnz[i]] + if MinValue != 0 and abs(Value / MinValue) < ThrNoiseDae: + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + for i in range(len(IndMinAnz)): + Value = Minimum[0, IndMinAnz[i]] + if abs(Value) < ThrAttGrad: + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + if len(IndMinAnz) > 0: + if abs(Minimum[1, IndMinAnz[-1]] - Indxlr11) < 15: + Minimum[0, IndMinAnz[-1]] = 0 + Minimum[1, IndMinAnz[-1]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + if len(IndMinAnz) > 0: + MinAnz = len(IndMinAnz) + IndMinGrad = Minimum[1, IndMinAnz] + + elif DaeGrad == 2: + if MinMax == 1: + if Maximum.shape[1] > 0: + Ind = np.where(Maximum[0, :])[0] + if len(Ind) > 0: + MaximumMean = np.mean(Maximum[0, Ind]) + else: + MaximumMean = 0 + for i in range(Maximum.shape[1]): + if Maximum[0, i] < MaximumMean: + Maximum[0, i] = 0 + Maximum[1, i] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + if len(IndMaxAnz) > 1: + for i in range(len(IndMaxAnz) - 1): + Index = Maximum[1, IndMaxAnz[i]] + Value = Maximum[0, IndMaxAnz[i]] + IndexNext = Maximum[1, IndMaxAnz[i + 1]] + ValueNext = Maximum[0, IndMaxAnz[i + 1]] + if (IndexNext - Index) <= IndexGrenze: + if abs(Value) < abs(ValueNext): + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + elif abs(Value) > abs(ValueNext): + if i < (len(IndMaxAnz) - 1): + IndexNext2 = Maximum[1, IndMaxAnz[i + 2]] + ValueNext2 = Maximum[0, IndMaxAnz[i + 2]] + if (IndexNext2 - IndexNext) <= IndexGrenze: + if abs(Value) < abs(ValueNext2): + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + elif abs(Value) > abs(ValueNext2): + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + Maximum[0, IndMaxAnz[i + 2]] = 0 + Maximum[1, IndMaxAnz[i + 2]] = 0 + else: + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + else: + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + MaxValue = np.max(Maximum[0, :]) if len(Maximum[0, :]) > 0 else 0 + if len(IndMaxAnz) > 1: + for i in range(len(IndMaxAnz)): + Value = Maximum[0, IndMaxAnz[i]] + if MaxValue != 0 and abs(Value / MaxValue) < ThrNoiseDae: + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + for i in range(len(IndMaxAnz)): + Value = Maximum[0, IndMaxAnz[i]] + if abs(Value) < ThrAttGrad: + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + if len(IndMaxAnz) > 0: + MaxAnz = len(IndMaxAnz) + IndMaxGrad = Maximum[1, IndMaxAnz] + + elif MinMax == 0: + if Minimum.shape[1] > 0: + Ind = np.where(Minimum[0, :])[0] + if len(Ind) > 0: + MinimumMean = np.mean(Minimum[0, Ind]) + else: + MinimumMean = 0 + for j_idx in range(Minimum.shape[1]): + if Minimum[0, j_idx] > MinimumMean: + Minimum[0, j_idx] = 0 + Minimum[1, j_idx] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + if len(IndMinAnz) > 1: + for i in range(len(IndMinAnz) - 1): + Index = Minimum[1, IndMinAnz[i]] + Value = Minimum[0, IndMinAnz[i]] + IndexNext = Minimum[1, IndMinAnz[i + 1]] + ValueNext = Minimum[0, IndMinAnz[i + 1]] + if (IndexNext - Index) <= IndexGrenze: + if abs(Value) < abs(ValueNext): + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + elif abs(Value) > abs(ValueNext): + if i < (len(IndMinAnz) - 1): + IndexNext2 = Minimum[1, IndMinAnz[i + 2]] + ValueNext2 = Minimum[0, IndMinAnz[i + 2]] + if (IndexNext2 - IndexNext) <= IndexGrenze: + if abs(Value) < abs(ValueNext2): + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + elif abs(Value) > abs(ValueNext2): + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + Minimum[0, IndMinAnz[i + 2]] = 0 + Minimum[1, IndMinAnz[i + 2]] = 0 + else: + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + else: + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + MinValue = np.min(Minimum[0, :]) if len(Minimum[0, :]) > 0 else 0 + if len(IndMinAnz) > 1: + for i in range(len(IndMinAnz)): + Value = Minimum[0, IndMinAnz[i]] + if MinValue != 0 and abs(Value / MinValue) < ThrNoiseDae: + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + for i in range(len(IndMinAnz)): + Value = Minimum[0, IndMinAnz[i]] + if abs(Value) < ThrAttGrad: + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + if len(IndMinAnz) > 0: + MinAnz = len(IndMinAnz) + IndMinGrad = Minimum[1, IndMinAnz] + + elif LR == 1: + if DaeGrad == 0: + if Maximum.shape[1] > 0: + Ind = np.where(Maximum[0, :])[0] + if len(Ind) > 0: + MaximumMean = np.mean(Maximum[0, Ind]) + else: + MaximumMean = 0 + for i in range(Maximum.shape[1]): + if Maximum[0, i] < MaximumMean: + Maximum[0, i] = 0 + Maximum[1, i] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + if len(IndMaxAnz) > 1: + for i in range(len(IndMaxAnz) - 1): + Index = Maximum[1, IndMaxAnz[i]] + Value = Maximum[0, IndMaxAnz[i]] + IndexNext = Maximum[1, IndMaxAnz[i + 1]] + ValueNext = Maximum[0, IndMaxAnz[i + 1]] + if (IndexNext - Index) <= IndexGrenze: + if abs(Value) < abs(ValueNext): + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + elif abs(Value) > abs(ValueNext): + if i < (len(IndMaxAnz) - 1): + IndexNext2 = Maximum[1, IndMaxAnz[i + 2]] + ValueNext2 = Maximum[0, IndMaxAnz[i + 2]] + if (IndexNext2 - IndexNext) <= IndexGrenze: + if abs(Value) < abs(ValueNext2): + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + elif abs(Value) > abs(ValueNext2): + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + Maximum[0, IndMaxAnz[i + 2]] = 0 + Maximum[1, IndMaxAnz[i + 2]] = 0 + else: + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + else: + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + MaxValue = np.max(Maximum[0, :]) if len(Maximum[0, :]) > 0 else 0 + if len(IndMaxAnz) > 1: + for i in range(len(IndMaxAnz)): + Value = Maximum[0, IndMaxAnz[i]] + if MaxValue != 0 and abs(Value / MaxValue) < ThrNoiseGrad: + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + if len(IndMaxAnz) > 0: + MaxAnz = len(IndMaxAnz) + IndMaxGrad = Maximum[1, IndMaxAnz] + + elif DaeGrad == 1: + if MinMax == 0: + if Minimum.shape[1] > 0: + Ind = np.where(Minimum[0, :])[0] + if len(Ind) > 0: + MinimumMean = np.mean(Minimum[0, Ind]) + else: + MinimumMean = 0 + for j_idx in range(Minimum.shape[1]): + if Minimum[0, j_idx] > MinimumMean: + Minimum[0, j_idx] = 0 + Minimum[1, j_idx] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + if len(IndMinAnz) > 1: + for i in range(len(IndMinAnz) - 1): + Index = Minimum[1, IndMinAnz[i]] + Value = Minimum[0, IndMinAnz[i]] + IndexNext = Minimum[1, IndMinAnz[i + 1]] + ValueNext = Minimum[0, IndMinAnz[i + 1]] + if (IndexNext - Index) <= IndexGrenze: + if abs(Value) < abs(ValueNext): + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + elif abs(Value) > abs(ValueNext): + if i < (len(IndMinAnz) - 1): + IndexNext2 = Minimum[1, IndMinAnz[i + 2]] + ValueNext2 = Minimum[0, IndMinAnz[i + 2]] + if (IndexNext2 - IndexNext) <= IndexGrenze: + if abs(Value) < abs(ValueNext2): + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + elif abs(Value) > abs(ValueNext2): + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + Minimum[0, IndMinAnz[i + 2]] = 0 + Minimum[1, IndMinAnz[i + 2]] = 0 + else: + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + else: + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + MinValue = np.min(Minimum[0, :]) if len(Minimum[0, :]) > 0 else 0 + if len(IndMinAnz) > 1: + for i in range(len(IndMinAnz)): + Value = Minimum[0, IndMinAnz[i]] + if MinValue != 0 and abs(Value / MinValue) < ThrNoiseDae: + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + for i in range(len(IndMinAnz)): + Value = Minimum[0, IndMinAnz[i]] + if abs(Value) < ThrAttGrad: + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + if len(IndMinAnz) > 0: + if abs(Minimum[1, IndMinAnz[-1]] - Indxlr11) < 15: + Minimum[0, IndMinAnz[-1]] = 0 + Minimum[1, IndMinAnz[-1]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + if len(IndMinAnz) > 0: + MinAnz = len(IndMinAnz) + IndMinGrad = Minimum[1, IndMinAnz] + + elif MinMax == 1: + if Maximum.shape[1] > 0: + Ind = np.where(Maximum[0, :])[0] + if len(Ind) > 0: + MaximumMean = np.mean(Maximum[0, Ind]) + else: + MaximumMean = 0 + for i in range(Maximum.shape[1]): + if Maximum[0, i] < MaximumMean: + Maximum[0, i] = 0 + Maximum[1, i] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + if len(IndMaxAnz) > 1: + for i in range(len(IndMaxAnz) - 1): + Index = Maximum[1, IndMaxAnz[i]] + Value = Maximum[0, IndMaxAnz[i]] + IndexNext = Maximum[1, IndMaxAnz[i + 1]] + ValueNext = Maximum[0, IndMaxAnz[i + 1]] + if (IndexNext - Index) <= IndexGrenze: + if abs(Value) < abs(ValueNext): + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + elif abs(Value) > abs(ValueNext): + if i < (len(IndMaxAnz) - 1): + IndexNext2 = Maximum[1, IndMaxAnz[i + 2]] + ValueNext2 = Maximum[0, IndMaxAnz[i + 2]] + if (IndexNext2 - IndexNext) <= IndexGrenze: + if abs(Value) < abs(ValueNext2): + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + elif abs(Value) > abs(ValueNext2): + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + Maximum[0, IndMaxAnz[i + 2]] = 0 + Maximum[1, IndMaxAnz[i + 2]] = 0 + else: + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + else: + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + MaxValue = np.max(Maximum[0, :]) if len(Maximum[0, :]) > 0 else 0 + if len(IndMaxAnz) > 1: + for i in range(len(IndMaxAnz)): + Value = Maximum[0, IndMaxAnz[i]] + if MaxValue != 0 and abs(Value / MaxValue) < ThrNoiseDae: + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + for i in range(len(IndMaxAnz)): + Value = Maximum[0, IndMaxAnz[i]] + if abs(Value) < ThrAttGrad: + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + if len(IndMaxAnz) > 0: + if abs(Maximum[1, IndMaxAnz[0]] - Indxlr11) < 15: + Maximum[0, IndMaxAnz[0]] = 0 + Maximum[1, IndMaxAnz[0]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + if len(IndMaxAnz) > 0: + MaxAnz = len(IndMaxAnz) + IndMaxGrad = Maximum[1, IndMaxAnz] + + elif DaeGrad == 2: + if MinMax == 0: + if Minimum.shape[1] > 0: + Ind = np.where(Minimum[0, :])[0] + if len(Ind) > 0: + MinimumMean = np.mean(Minimum[0, Ind]) + else: + MinimumMean = 0 + for j_idx in range(Minimum.shape[1]): + if Minimum[0, j_idx] > MinimumMean: + Minimum[0, j_idx] = 0 + Minimum[1, j_idx] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + if len(IndMinAnz) > 1: + for i in range(len(IndMinAnz) - 1): + Index = Minimum[1, IndMinAnz[i]] + Value = Minimum[0, IndMinAnz[i]] + IndexNext = Minimum[1, IndMinAnz[i + 1]] + ValueNext = Minimum[0, IndMinAnz[i + 1]] + if (IndexNext - Index) <= IndexGrenze: + if abs(Value) < abs(ValueNext): + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + elif abs(Value) > abs(ValueNext): + if i < (len(IndMinAnz) - 1): + IndexNext2 = Minimum[1, IndMinAnz[i + 2]] + ValueNext2 = Minimum[0, IndMinAnz[i + 2]] + if (IndexNext2 - IndexNext) <= IndexGrenze: + if abs(Value) < abs(ValueNext2): + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + elif abs(Value) > abs(ValueNext2): + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + Minimum[0, IndMinAnz[i + 2]] = 0 + Minimum[1, IndMinAnz[i + 2]] = 0 + else: + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + else: + Minimum[0, IndMinAnz[i + 1]] = 0 + Minimum[1, IndMinAnz[i + 1]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + MinValue = np.min(Minimum[0, :]) if len(Minimum[0, :]) > 0 else 0 + if len(IndMinAnz) > 1: + for i in range(len(IndMinAnz)): + Value = Minimum[0, IndMinAnz[i]] + if MinValue != 0 and abs(Value / MinValue) < ThrNoiseDae: + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + for i in range(len(IndMinAnz)): + Value = Minimum[0, IndMinAnz[i]] + if abs(Value) < ThrAttGrad: + Minimum[0, IndMinAnz[i]] = 0 + Minimum[1, IndMinAnz[i]] = 0 + + IndMinAnz = np.where(Minimum[0, :] != 0)[0] + if len(IndMinAnz) > 0: + MinAnz = len(IndMinAnz) + IndMinGrad = Minimum[1, IndMinAnz] + + elif MinMax == 1: + if Maximum.shape[1] > 0: + Ind = np.where(Maximum[0, :])[0] + if len(Ind) > 0: + MaximumMean = np.mean(Maximum[0, Ind]) + else: + MaximumMean = 0 + for i in range(Maximum.shape[1]): + if Maximum[0, i] < MaximumMean: + Maximum[0, i] = 0 + Maximum[1, i] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + if len(IndMaxAnz) > 1: + for i in range(len(IndMaxAnz) - 1): + Index = Maximum[1, IndMaxAnz[i]] + Value = Maximum[0, IndMaxAnz[i]] + IndexNext = Maximum[1, IndMaxAnz[i + 1]] + ValueNext = Maximum[0, IndMaxAnz[i + 1]] + if (IndexNext - Index) <= IndexGrenze: + if abs(Value) < abs(ValueNext): + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + elif abs(Value) > abs(ValueNext): + if i < (len(IndMaxAnz) - 1): + IndexNext2 = Maximum[1, IndMaxAnz[i + 2]] + ValueNext2 = Maximum[0, IndMaxAnz[i + 2]] + if (IndexNext2 - IndexNext) <= IndexGrenze: + if abs(Value) < abs(ValueNext2): + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + elif abs(Value) > abs(ValueNext2): + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + Maximum[0, IndMaxAnz[i + 2]] = 0 + Maximum[1, IndMaxAnz[i + 2]] = 0 + else: + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + else: + Maximum[0, IndMaxAnz[i + 1]] = 0 + Maximum[1, IndMaxAnz[i + 1]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + MaxValue = np.max(Maximum[0, :]) if len(Maximum[0, :]) > 0 else 0 + if len(IndMaxAnz) > 1: + for i in range(len(IndMaxAnz)): + Value = Maximum[0, IndMaxAnz[i]] + if MaxValue != 0 and abs(Value / MaxValue) < ThrNoiseDae: + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + for i in range(len(IndMaxAnz)): + Value = Maximum[0, IndMaxAnz[i]] + if abs(Value) < ThrAttGrad: + Maximum[0, IndMaxAnz[i]] = 0 + Maximum[1, IndMaxAnz[i]] = 0 + + IndMaxAnz = np.where(Maximum[0, :] != 0)[0] + if len(IndMaxAnz) > 0: + MaxAnz = len(IndMaxAnz) + IndMaxGrad = Maximum[1, IndMaxAnz] + + return MinAnz, MaxAnz, IndMinGrad, IndMaxGrad diff --git a/algorithm/extremum_utils.py b/algorithm/extremum_utils.py new file mode 100644 index 0000000..155cdde --- /dev/null +++ b/algorithm/extremum_utils.py @@ -0,0 +1,331 @@ +import numpy as np +try: + from .math_utils import polyfit2 +except ImportError: + from math_utils import polyfit2 + + +def limit(x, uplimit, lowlimit, limitflag=None): + x = np.asarray(x, dtype=np.float64) + if limitflag is None: + limitflag = np.ones_like(x, dtype=bool) + else: + limitflag = np.asarray(limitflag, dtype=bool) + y = x.copy() + errorl = 0 + lflag = 0 + uplimiterused = 0 + lowlimiterused = 0 + if np.isscalar(uplimit): + uplimit = uplimit * np.ones_like(x) + if np.isscalar(lowlimit): + lowlimit = lowlimit * np.ones_like(x) + if (x.shape == uplimit.shape) and (x.shape == limitflag.shape): + uplimiterused = 1 + ind = np.where((x > uplimit) & limitflag)[0] + y[ind] = uplimit[ind] + if len(ind) > 0: + lflag = 1 + if (x.shape == lowlimit.shape) and (x.shape == limitflag.shape): + lowlimiterused = 1 + ind = np.where((x < lowlimit) & limitflag)[0] + y[ind] = lowlimit[ind] + if len(ind) > 0: + lflag = 1 + if (not uplimiterused) and (not lowlimiterused): + errorl = 1 + return y, errorl, lflag + + +def lowlimit(x, bp): + x = np.asarray(x, dtype=np.float64) + y = x.copy() + yind = np.where(x < bp)[0] + a2 = 1.0 / (2 * bp) + a0 = 0.5 * bp + y[yind] = a2 * x[yind] ** 2 + a0 + return y, a0 + + +def symlimit(symj, symj2, NOMJACK1, NOMJACK2): + if (NOMJACK1 > 0) and (NOMJACK2 > 0): + if NOMJACK1 < NOMJACK2: + NOMJACK = NOMJACK1 + else: + NOMJACK = NOMJACK2 + elif NOMJACK1 > 0: + NOMJACK = NOMJACK1 + elif NOMJACK2 > 0: + NOMJACK = NOMJACK2 + else: + NOMJACK = 0 + if NOMJACK > 0: + if symj > NOMJACK: + symj = NOMJACK + if symj2 > NOMJACK: + symj2 = NOMJACK + return symj, symj2 + + +def _minmaxp(y, smax): + y = np.asarray(y, dtype=np.float64) + if smax: + ys = np.max(y) + xs = np.argmax(y) + 1 + else: + ys = np.min(y) + xs = np.argmin(y) + 1 + if (xs > 1) and (xs < len(y)): + x_arr = np.array([xs - 1, xs, xs + 1], dtype=np.float64) + p = polyfit2(x_arr, y[x_arr.astype(int) - 1], 2) + xs = -p[1] / (2 * p[0]) + ys = p[2] - (p[1] ** 2) / (4 * p[0]) + return ys, xs + + +def minmax(y, smax): + y = np.asarray(y, dtype=np.float64) + ys = 0.0 + xs = 0.0 + N = len(y) + if N == 1: + ys = y[0] + xs = 1.0 + elif N == 2: + if (y[1] > y[0]) and smax: + ys = y[1] + xs = 2.0 + elif (y[1] > y[0]) and not smax: + ys = y[0] + xs = 1.0 + elif (y[1] < y[0]) and smax: + ys = y[0] + xs = 1.0 + else: + ys = y[1] + xs = 2.0 + elif N > 2: + run = 1 + i = 0 + Il = N + if smax: + while run and (i < N - 1): + if y[i + 1] > y[i]: + run = 0 + Il = i + else: + i = i + 1 + else: + while run and (i < N - 1): + if y[i + 1] < y[i]: + run = 0 + Il = i + else: + i = i + 1 + run = 1 + i = N - 1 + Ir = 0 + if smax: + while run and (i > 0): + if y[i - 1] > y[i]: + run = 0 + Ir = i + else: + i = i - 1 + else: + while run and (i > 0): + if y[i - 1] < y[i]: + run = 0 + Ir = i + else: + i = i - 1 + if Il < Ir: + ys, xs = _minmaxp(y[Il:Ir + 1], smax) + xs = xs + Il - 1 + else: + ys, xs = _minmaxp(y, smax) + return ys, xs + + +def _minmaxp2(y, smax, xr41det, level): + y = np.asarray(y, dtype=np.float64) + if smax: + if not xr41det: + found = np.where(y > level)[0] + if len(found) > 0: + xs = found[0] + while (xs + 1 < len(y)) and (y[xs + 1] > y[xs]): + xs = xs + 1 + else: + xs = None + else: + found = np.where(y > level)[0] + if len(found) > 0: + xs = found[-1] + while (xs > 0) and (y[xs - 1] > y[xs]): + xs = xs - 1 + else: + xs = None + else: + ys = np.min(y) + xs = np.argmin(y) + if xs is not None: + if (xs > 0) and (xs < len(y) - 1): + x_arr = np.array([xs, xs + 1, xs + 2], dtype=np.float64) + p = polyfit2(x_arr, y[[xs - 1, xs, xs + 1]], 2) + xs = -p[1] / (2 * p[0]) + ys = p[2] - (p[1] ** 2) / (4 * p[0]) + else: + xs = 0.0 + ys = 0.0 + return ys, float(xs) if isinstance(xs, (int, np.integer)) else xs + + +def minmax2(y, smax, xr41det, level): + y = np.asarray(y, dtype=np.float64) + ys = 0.0 + xs = 0.0 + N = len(y) + if N == 1: + ys = y[0] + xs = 1.0 + elif N == 2: + if (y[1] > y[0]) and smax: + ys = y[1] + xs = 2.0 + elif (y[1] > y[0]) and not smax: + ys = y[0] + xs = 1.0 + elif (y[1] < y[0]) and smax: + ys = y[0] + xs = 1.0 + else: + ys = y[1] + xs = 2.0 + elif N > 2: + run = 1 + i = 0 + Il = N + if smax: + while run and (i < N - 1): + if y[i + 1] > y[i]: + run = 0 + Il = i + else: + i = i + 1 + else: + while run and (i < N - 1): + if y[i + 1] < y[i]: + run = 0 + Il = i + else: + i = i + 1 + run = 1 + i = N - 1 + Ir = 0 + if smax: + while run and (i > 0): + if y[i - 1] > y[i]: + run = 0 + Ir = i + else: + i = i - 1 + else: + while run and (i > 0): + if y[i - 1] < y[i]: + run = 0 + Ir = i + else: + i = i - 1 + if Il < Ir: + ys, xs = _minmaxp2(y[Il:Ir + 1], smax, xr41det, level) + xs = xs + Il - 1 + else: + ys, xs = _minmaxp2(y, smax, xr41det, level) + return ys, xs + + +def minmaxall(x): + x = np.asarray(x, dtype=np.float64) + Val_max = np.array([]) + Ind_max = np.array([]) + Val_min = np.array([]) + Ind_min = np.array([]) + inan = np.where(np.isnan(x))[0] + if len(inan) > 0: + x = np.delete(x, inan) + Nt = len(x) + if Nt < 3: + return Val_max, Ind_max, Val_min, Ind_min + dx = np.diff(x) + b = (dx > 0).astype(int) + db = np.diff(b) + Ind_max = np.where(db == -1)[0] + 1 + Ind_min = np.where(db == 1)[0] + 1 + Val_max = x[Ind_max] + Val_min = x[Ind_min] + sort_idx = np.argsort(-Ind_max) + Ind_max = Ind_max[sort_idx] + Val_max = Val_max[sort_idx] + sort_idx = np.argsort(-Ind_min) + Ind_min = Ind_min[sort_idx] + Val_min = Val_min[sort_idx] + return Val_max, Ind_max, Val_min, Ind_min + + +def findmaxima(I, levelfactor, left): + I = np.asarray(I, dtype=np.float64) + maximum = np.max(I) + maxindex = np.argmax(I) + meanI = np.mean(I) + minlimit1 = meanI + 4.0 * np.std(I) + minlimit2 = levelfactor * (maximum - meanI) + meanI + I2 = I.copy() + if minlimit1 >= 0.99 * maximum: + return float(maxindex) + if minlimit1 > minlimit2: + minlimit2 = minlimit1 + ind = np.where(I < minlimit2)[0] + I2[ind] = minlimit2 + I2_padded = np.pad(I2, (1, 1), mode='edge') + max_filt = np.maximum(np.maximum(I2_padded[:-2], I2_padded[1:-1]), I2_padded[2:]) + I3 = (I2 == max_filt) + maxindexvek = np.where(I3)[0] + if left: + maxindex = float(maxindexvek[0]) + else: + maxindex = float(maxindexvek[-1]) + return maxindex + + +def qcheck(Indiff, dx, Ref, klevel, Anzpara=0): + Indiff = np.asarray(Indiff, dtype=np.float64) + errorlevel = np.zeros(2) + N = len(Indiff) + x = np.arange(N) * dx + A = polyfit2(x, Indiff, 2) + Scheitelx = -A[1] / (2 * A[0]) + if Scheitelx > N * dx: + errorlevel[1] = 11 + if Scheitelx < 0: + errorlevel[1] = 11 + if abs(A[0]) > 0: + Scheitely = A[2] - (A[1] ** 2) / (4 * A[0]) + diff1 = abs(np.polyval([A[0], A[1], A[2]], 0) - Scheitely) + diff2 = abs(np.polyval([A[0], A[1], A[2]], N * dx) - Scheitely) + diff = (diff1 + diff2) / 2 + Kontrast = diff * 1 / (N * dx) + if Kontrast < klevel: + errorlevel[0] = 11 + else: + errorlevel[0] = 11 + Maximum = (A[0] < 0) + return errorlevel, Maximum + + +def errfunc(errorl, errorlevel): + if (errorlevel[0] == 0) and (errorl[0] > 0): + errorlevel[0] = errorl[0] + if (errorlevel[1] == 0) and (errorl[1] > 0): + errorlevel[1] = errorl[1] + return errorlevel diff --git a/algorithm/filtering_utils.py b/algorithm/filtering_utils.py new file mode 100644 index 0000000..6db8d26 --- /dev/null +++ b/algorithm/filtering_utils.py @@ -0,0 +1,199 @@ +import numpy as np +try: + from .filtmat_data import GLOBAL_KLAUS_AMAT, GLOBAL_KLAUS_BMAT +except ImportError: + from filtmat_data import GLOBAL_KLAUS_AMAT, GLOBAL_KLAUS_BMAT +try: + from .signal_utils import _lfilter +except ImportError: + from signal_utils import _lfilter + + +def buttmat(fgn): + errorl = 0 + N = 73 + fgnmin = 1 + fgnmax = 0.001 + + m0 = np.log(1 / fgnmin) - (np.log(1 / fgnmax) - np.log(1 / fgnmin)) / (N - 1) + m1 = (np.log(1 / fgnmax) - np.log(1 / fgnmin)) / (N - 1) + + if np.isfinite(fgn) and fgn > 0: + log_val = np.log(1 / fgn) + if np.isfinite(log_val): + Index = int(np.round((log_val - m0) / m1)) + else: + Index = 0 + else: + Index = 0 + + if Index < 1: + Index = 1 + errorl = 70 + elif Index > N: + Index = N + errorl = 70 + + A = GLOBAL_KLAUS_AMAT[Index - 1, :].copy() + B = GLOBAL_KLAUS_BMAT[Index - 1, :].copy() + return B, A, errorl + + +def _moving(x, y, span): + ynan = np.isnan(y) + span = int(np.floor(span)) + n = len(y) + span = min(span, n) + width = span - 1 + np.mod(span, 2) + xreps = np.any(np.diff(x) == 0) + if width == 1 and not xreps and not np.any(ynan): + return y.copy() + if not xreps and not np.any(ynan): + b = np.ones(width) / width + c = _lfilter(b, np.array([1.0]), y)[0] + cbegin = np.cumsum(y[0:width - 2]) + idx = np.arange(0, width - 2, 2) + cbegin = cbegin[idx] / (np.arange(1, width - 2, 2)) + cend = np.cumsum(y[n - 1:n - width + 2:-1]) + idx2 = np.arange(len(cend) - 1, -1, -2) + cend = cend[idx2] / (np.arange(width - 2, 0, -2)) + c = np.concatenate([cbegin, c[width - 1:], cend]) + elif not xreps: + yy = y.copy() + yy[ynan] = 0 + nn = (~ynan).astype(float) + ynum = _moving(x, yy, span) + yden = _moving(x, nn, span) + c = ynum / yden + else: + notnan = ~ynan + yy = y.copy() + yy[ynan] = 0 + c = np.zeros(n) + for i in range(n): + if i > 0 and x[i] == x[i - 1]: + c[i] = c[i - 1] + continue + R = i + while R < n - 1 and x[R + 1] == x[R]: + R = R + 1 + hf = int(np.ceil(max(0, (span - (R - i + 1)) / 2))) + hf = min(min(hf, i), (n - R - 1)) + L = i - hf + while L > 0 and x[L] == x[L - 1]: + L = L - 1 + R = R + hf + while R < n - 1 and x[R] == x[R + 1]: + R = R + 1 + c[i] = np.sum(yy[L:R + 1]) / np.sum(notnan[L:R + 1]) + return c + + +def smooth(*args): + nargin = len(args) + if nargin < 1: + raise ValueError('SMOOTH needs at least one argument.') + + if nargin == 1 or (nargin > 1 and (np.isscalar(args[1]) or isinstance(args[1], str))): + is_x = 0 + y = np.asarray(args[0], dtype=np.float64).ravel() + x = np.arange(1, len(y) + 1, dtype=np.float64) + else: + is_x = 1 + y = np.asarray(args[1], dtype=np.float64).ravel() + x = np.asarray(args[0], dtype=np.float64).ravel() + + span = None + span_idx = 1 + is_x + if span_idx >= nargin: + is_span = 0 + elif isinstance(args[span_idx], str): + is_span = 0 + else: + is_span = 1 + span = args[span_idx] + + method = None + method_idx = 2 + is_x + is_span + if method_idx < nargin: + method = args[method_idx] + + t = len(y) + if t == 0: + return y.copy() + if len(x) != t: + raise ValueError('X and Y must be the same length.') + + if method is None: + diffx = np.diff(x) + if np.all(np.abs(np.diff(diffx)) <= np.finfo(float).eps * max(abs(x[0]), abs(x[-1]))): + method = 'moving' + else: + method = 'lowess' + + if span is not None and span <= 0: + raise ValueError('SPAN must be positive.') + if span is None: + span = 5 + elif span < 1: + span = int(np.ceil(span * t)) + + idx = np.arange(t) + sortx = np.any(np.diff(np.isnan(x)) < 0) + if sortx or np.any(np.diff(x) < 0): + sort_idx = np.argsort(x) + x = x[sort_idx] + y = y[sort_idx] + idx = idx[sort_idx] + + c = np.full(y.shape, np.nan) + ok = ~np.isnan(x) + if method == 'moving': + c[ok] = _moving(x[ok], y[ok], span) + else: + c[ok] = _moving(x[ok], y[ok], span) + + c_orig = np.empty_like(c) + c_orig[idx] = c + return c_orig + + +def hendfilt(Tab2, pegdiff, tdiff): + Tab2 = np.asarray(Tab2, dtype=np.float64).copy() + N = Tab2.shape[1] + + for i in range(N): + Tab2[5, i] = (Tab2[2, i] + Tab2[3, i]) / 2 + + for i in range(1, N - 1): + if Tab2[4, i] == 3: + pegval = Tab2[0, i] + avgt = Tab2[5, i] + + il = i - 1 + stop = 0 + while not stop: + tr1 = (Tab2[0, il] - pegval) < pegdiff + tr2 = Tab2[4, il] == -2 + tr3 = Tab2[4, il] == -3 + if tr1 and (tr2 or tr3): + if abs(Tab2[5, il] - avgt) < tdiff: + Tab2[4, il] = 0 + il = il - 1 + if not tr1 or il < 0: + stop = 1 + + ir = i + 1 + stop = 0 + while not stop: + tr1 = (pegval - Tab2[0, ir]) < pegdiff + tr2 = Tab2[4, ir] == -2 + tr3 = Tab2[4, ir] == -3 + if tr1 and (tr2 or tr3): + if abs(Tab2[5, ir] - avgt) < tdiff: + Tab2[4, ir] = 0 + ir = ir + 1 + if not tr1 or ir >= N: + stop = 1 + + return Tab2 diff --git a/algorithm/filtmat_data.py b/algorithm/filtmat_data.py new file mode 100644 index 0000000..2c1c9e2 --- /dev/null +++ b/algorithm/filtmat_data.py @@ -0,0 +1,153 @@ +import numpy as np + +GLOBAL_KLAUS_AMAT = np.array([ + [1.0000000000000000e+00, 2.0000000000000000e+00, 9.9999999999999967e-01], + [1.0000000000000000e+00, 1.5977251539192581e+00, 6.6606034085418508e-01], + [1.0000000000000000e+00, 1.2468841550541940e+00, 4.6124441824842299e-01], + [1.0000000000000000e+00, 9.4239126155026609e-01, 3.3318566260159432e-01], + [1.0000000000000000e+00, 6.7596863630246729e-01, 2.5353565420277441e-01], + [1.0000000000000000e+00, 4.4033434667920651e-01, 2.0605911602722060e-01], + [1.0000000000000000e+00, 2.2980951121587750e-01, 1.8092433791593329e-01], + [1.0000000000000000e+00, 4.0109367662085393e-02, 1.7185728107194909e-01], + [1.0000000000000000e+00, -1.3198460762042799e-01, 1.7465399227788719e-01], + [1.0000000000000000e+00, -2.8890891325817353e-01, 1.8636682564340301e-01], + [1.0000000000000000e+00, -4.3253481955187900e-01, 2.0484103674312951e-01], + [1.0000000000000000e+00, -5.6432694722750698e-01, 2.2844175658658011e-01], + [1.0000000000000000e+00, -6.8545755612815262e-01, 2.5588849739176600e-01], + [1.0000000000000000e+00, -7.9688844579316587e-01, 2.8615239835370410e-01], + [1.0000000000000000e+00, -8.9942942434243522e-01, 3.1839102204906933e-01], + [1.0000000000000000e+00, -9.9377983518294521e-01, 3.5190603656445790e-01], + [1.0000000000000000e+00, -1.0805578149911359e+00, 3.8611499708545283e-01], + [1.0000000000000000e+00, -1.1603206706776970e+00, 4.2053184915997471e-01], + [1.0000000000000000e+00, -1.2335788560497589e+00, 4.5475282027325142e-01], + [1.0000000000000000e+00, -1.3008053803759310e+00, 4.8844562822441978e-01], + [1.0000000000000000e+00, -1.3624420076096999e+00, 5.2134073017277149e-01], + [1.0000000000000000e+00, -1.4189032520151461e+00, 5.5322384321310591e-01], + [1.0000000000000000e+00, -1.4705789084027430e+00, 5.8392929032261198e-01], + [1.0000000000000000e+00, -1.5178356506534880e+00, 6.1333392834160771e-01], + [1.0000000000000000e+00, -1.5610180758007179e+00, 6.4135153805756295e-01], + [1.0000000000000000e+00, -1.6004494522408690e+00, 6.6792762744765932e-01], + [1.0000000000000000e+00, -1.6364323418846010e+00, 6.9303463605669202e-01], + [1.0000000000000000e+00, -1.6692492010850160e+00, 7.1666754398816523e-01], + [1.0000000000000000e+00, -1.6991630189294160e+00, 7.3883989175850850e-01], + [1.0000000000000000e+00, -1.7264180197289480e+00, 7.5958021318432878e-01], + [1.0000000000000000e+00, -1.7512404357672879e+00, 7.7892887639013275e-01], + [1.0000000000000000e+00, -1.7738393436882240e+00, 7.9693532033584413e-01], + [1.0000000000000000e+00, -1.7944075509949431e+00, 8.1365566734507011e-01], + [1.0000000000000000e+00, -1.8131225161885269e+00, 8.2915068664585023e-01], + [1.0000000000000000e+00, -1.8301472857120860e+00, 8.4348408014207199e-01], + [1.0000000000000000e+00, -1.8456314320755609e+00, 8.5672105946642696e-01], + [1.0000000000000000e+00, -1.8597119795931449e+00, 8.6892718262426649e-01], + [1.0000000000000000e+00, -1.8725143065777390e+00, 8.8016741895457951e-01], + [1.0000000000000000e+00, -1.8841530152854831e+00, 8.9050541242917070e-01], + [1.0000000000000000e+00, -1.8947327631950359e+00, 9.0000291522218923e-01], + [1.0000000000000000e+00, -1.9043490512370449e+00, 9.0871936578263923e-01], + [1.0000000000000000e+00, -1.9130889663156949e+00, 9.1671158814696363e-01], + [1.0000000000000000e+00, -1.9210318768816379e+00, 9.2403359179282185e-01], + [1.0000000000000000e+00, -1.9282500814425421e+00, 9.3073645385204040e-01], + [1.0000000000000000e+00, -1.9348094107650140e+00, 9.3686826789583366e-01], + [1.0000000000000000e+00, -1.9407697851658681e+00, 9.4247414573055011e-01], + [1.0000000000000000e+00, -1.9461857287484561e+00, 9.4759626066998193e-01], + [1.0000000000000000e+00, -1.9511068427455369e+00, 9.5227392256885546e-01], + [1.0000000000000000e+00, -1.9555782403150359e+00, 9.5654367651120331e-01], + [1.0000000000000000e+00, -1.9596409452256840e+00, 9.6043941845431113e-01], + [1.0000000000000000e+00, -1.9633322568886440e+00, 9.6399252234660449e-01], + [1.0000000000000000e+00, -1.9666860841571381e+00, 9.6723197428170304e-01], + [1.0000000000000000e+00, -1.9697332502439810e+00, 9.7018451013810536e-01], + [1.0000000000000000e+00, -1.9725017710085120e+00, 9.7287475390190015e-01], + [1.0000000000000000e+00, -1.9750171087490049e+00, 9.7532535449551250e-01], + [1.0000000000000000e+00, -1.9773024035113260e+00, 9.7755711945470947e-01], + [1.0000000000000000e+00, -1.9793786837948040e+00, 9.7958914422369248e-01], + [1.0000000000000000e+00, -1.9812650584057760e+00, 9.8143893618737510e-01], + [1.0000000000000000e+00, -1.9829788910811610e+00, 9.8312253284277851e-01], + [1.0000000000000000e+00, -1.9845359593803891e+00, 9.8465461373833985e-01], + [1.0000000000000000e+00, -1.9859505992257189e+00, 9.8604860598995414e-01], + [1.0000000000000000e+00, -1.9872358363589491e+00, 9.8731678332362816e-01], + [1.0000000000000000e+00, -1.9884035058773890e+00, 9.8847035870347932e-01], + [1.0000000000000000e+00, -1.9894643609138769e+00, 9.8951957068626561e-01], + [1.0000000000000000e+00, -1.9904281714344580e+00, 9.9047376370446927e-01], + [1.0000000000000000e+00, -1.9913038140430270e+00, 9.9134146252338540e-01], + [1.0000000000000000e+00, -1.9920993536045399e+00, 9.9213044114704108e-01], + [1.0000000000000000e+00, -1.9928221174267970e+00, 9.9284778646596483e-01], + [1.0000000000000000e+00, -1.9934787626752650e+00, 9.9349995694924131e-01], + [1.0000000000000000e+00, -1.9940753376351670e+00, 9.9409283668580684e-01], + [1.0000000000000000e+00, -1.9946173373801479e+00, 9.9463178507723216e-01], + [1.0000000000000000e+00, -1.9951097543564580e+00, 9.9512168247753408e-01], + [1.0000000000000000e+00, -1.9955571243457890e+00, 9.9556697206597489e-01] +]) + +GLOBAL_KLAUS_BMAT = np.array([ + [9.9999999999999978e-01, 2.0000000000000000e+00, 9.9999999999999978e-01], + [8.1594637369336087e-01, 1.6318927473867220e+00, 8.1594637369336087e-01], + [6.7703214332565431e-01, 1.3540642866513091e+00, 6.7703214332565431e-01], + [5.6889423103796510e-01, 1.1377884620759300e+00, 5.6889423103796510e-01], + [4.8237607262631038e-01, 9.6475214525262087e-01, 4.8237607262631038e-01], + [4.1159836567660679e-01, 8.2319673135321358e-01, 4.1159836567660679e-01], + [3.5268346228295272e-01, 7.0536692456590533e-01, 3.5268346228295272e-01], + [3.0299166218350870e-01, 6.0598332436701730e-01, 3.0299166218350870e-01], + [2.6066734616436482e-01, 5.2133469232872964e-01, 2.6066734616436482e-01], + [2.2436447809630741e-01, 4.4872895619261483e-01, 2.2436447809630741e-01], + [1.9307655429781259e-01, 3.8615310859562518e-01, 1.9307655429781259e-01], + [1.6602870233976830e-01, 3.3205740467953648e-01, 1.6602870233976830e-01], + [1.4260773531590329e-01, 2.8521547063180669e-01, 1.4260773531590329e-01], + [1.2231598814013460e-01, 2.4463197628026909e-01, 1.2231598814013460e-01], + [1.0474039942665850e-01, 2.0948079885331711e-01, 1.0474039942665850e-01], + [8.9531550345378186e-02, 1.7906310069075640e-01, 8.9531550345378186e-02], + [7.6389295523579259e-02, 1.5277859104715849e-01, 7.6389295523579259e-02], + [6.5052794620569399e-02, 1.3010558924113880e-01, 6.5052794620569399e-02], + [5.5293491055873063e-02, 1.1058698211174610e-01, 5.5293491055873063e-02], + [4.6910061962122218e-02, 9.3820123924244436e-02, 4.6910061962122218e-02], + [3.9724680640767777e-02, 7.9449361281535569e-02, 3.9724680640767777e-02], + [3.3580147799490007e-02, 6.7160295598980013e-02, 3.3580147799490007e-02], + [2.8337595479967309e-02, 5.6675190959934618e-02, 2.8337595479967309e-02], + [2.3874569422029871e-02, 4.7749138844059742e-02, 2.3874569422029871e-02], + [2.0083365564211249e-02, 4.0166731128422513e-02, 2.0083365564211249e-02], + [1.6869543801697699e-02, 3.3739087603395390e-02, 1.6869543801697699e-02], + [1.4150573543022710e-02, 2.8301147086045420e-02, 1.4150573543022710e-02], + [1.1854585725787429e-02, 2.3709171451574858e-02, 1.1854585725787429e-02], + [9.9192182072731783e-03, 1.9838436414546360e-02, 9.9192182072731783e-03], + [8.2905483638451849e-03, 1.6581096727690370e-02, 8.2905483638451849e-03], + [6.9221101557111484e-03, 1.3844220311422300e-02, 6.9221101557111484e-03], + [5.7739941619049662e-03, 1.1547988323809931e-02, 5.7739941619049662e-03], + [4.8120290875317551e-03, 9.6240581750635101e-03, 4.8120290875317551e-03], + [4.0070426143307136e-03, 8.0140852286614273e-03, 4.0070426143307136e-03], + [3.3341986074965639e-03, 6.6683972149931270e-03, 3.3341986074965639e-03], + [2.7724068477165691e-03, 5.5448136954331373e-03, 2.7724068477165691e-03], + [2.3038007577803892e-03, 4.6076015155607783e-03, 2.3038007577803892e-03], + [1.9132780942101300e-03, 3.8265561884202599e-03, 1.9132780942101300e-03], + [1.5880992859219620e-03, 3.1761985718439249e-03, 1.5880992859219620e-03], + [1.3175380067883271e-03, 2.6350760135766542e-03, 1.3175380067883271e-03], + [1.0925786363985830e-03, 2.1851572727971669e-03, 1.0925786363985830e-03], + [9.0565545781723378e-04, 1.8113109156344680e-03, 9.0565545781723378e-04], + [7.5042872779604308e-04, 1.5008574555920859e-03, 7.5042872779604308e-04], + [6.2159310237452914e-04, 1.2431862047490581e-03, 6.2159310237452914e-04], + [5.1471428270480346e-04, 1.0294285654096069e-03, 5.1471428270480346e-04], + [4.2609014117045430e-04, 8.5218028234090859e-04, 4.2609014117045430e-04], + [3.5263298038146212e-04, 7.0526596076292414e-04, 3.5263298038146212e-04], + [2.9176995582957938e-04, 5.8353991165915886e-04, 2.9176995582957938e-04], + [2.4135904904196151e-04, 4.8271809808392302e-04, 2.4135904904196151e-04], + [1.9961830715684031e-04, 3.9923661431368052e-04, 1.9961830715684031e-04], + [1.6506636449001300e-04, 3.3013272898002599e-04, 1.6506636449001300e-04], + [1.3647253114124069e-04, 2.7294506228248139e-04, 1.3647253114124069e-04], + [1.1281497353113350e-04, 2.2562994706226691e-04, 1.1281497353113350e-04], + [9.3245723346929710e-05, 1.8649144669385939e-04, 9.3245723346929710e-05], + [7.7061436626946200e-05, 1.5412287325389240e-04, 7.7061436626946200e-05], + [6.3678985845805336e-05, 1.2735797169161070e-04, 6.3678985845805336e-05], + [5.2615107222236952e-05, 1.0523021444447390e-04, 5.2615107222236952e-05], + [4.3469445399707540e-05, 8.6938890799415081e-05, 4.3469445399707540e-05], + [3.5910440404379740e-05, 7.1820880808759480e-05, 3.5910440404379740e-05], + [2.9663589487805009e-05, 5.9327178975610018e-05, 2.9663589487805009e-05], + [2.4501691058748110e-05, 4.9003382117496219e-05, 2.4501691058748110e-05], + [2.0236741169715741e-05, 4.0473482339431488e-05, 2.0236741169715741e-05], + [1.6713206522633861e-05, 3.3426413045267722e-05, 1.6713206522633861e-05], + [1.3802443097066240e-05, 2.7604886194132480e-05, 1.3802443097066240e-05], + [1.1398067502915721e-05, 2.2796135005831442e-05, 1.1398067502915721e-05], + [9.4121200895358470e-06, 1.8824240179071691e-05, 9.4121200895358470e-06], + [7.7718856253961022e-06, 1.5543771250792201e-05, 7.7718856253961022e-06], + [6.4172597919465169e-06, 1.2834519583893030e-05, 6.4172597919465169e-06], + [5.2985684941830868e-06, 1.0597136988366170e-05, 5.2985684941830868e-06], + [4.3747626598533706e-06, 8.7495253197067413e-06, 4.3747626598533706e-06], + [3.6119242710075379e-06, 7.2238485420150766e-06, 3.6119242710075379e-06], + [2.9820302690219962e-06, 5.9640605380439923e-06, 2.9820302690219962e-06], + [2.4619300464101550e-06, 4.9238600928203091e-06, 2.4619300464101550e-06] +]) diff --git a/algorithm/gateway.py b/algorithm/gateway.py new file mode 100644 index 0000000..2643df1 --- /dev/null +++ b/algorithm/gateway.py @@ -0,0 +1,1091 @@ +import time +import numpy as np +import scipy +import os +import copy +import math + + +_global_mem = None +_Lsq_LM_on = 0 +_Unsharpness = 0 + + +def get_user_data(): + global _global_mem + return copy.deepcopy(_global_mem) if _global_mem is not None else None + + +def set_user_data(mem): + global _global_mem + _global_mem = copy.deepcopy(mem) + + +def reset_user_data(): + global _global_mem + _global_mem = None + + +def _convert_cable_type(cableTypeOrg): + """四位数cableType转换为标准类型,并返回sectorAna标志""" + sectorAna = 0 + cableType = cableTypeOrg + + digits = int(math.floor(math.log10(cableTypeOrg))) + 1 if cableTypeOrg > 0 else 0 + if digits == 4: + if cableTypeOrg in (1111, 1112, 1113, 1114): + cableType = 111 + elif cableTypeOrg in (2100, 2200, 2300, 2400): + cableType = 2 + elif cableTypeOrg in (2210, 2220, 2230, 2240): + cableType = 22 + elif cableTypeOrg in (1181, 1182, 1183): + cableType = 118 + elif cableTypeOrg in (1110, 1120, 1130, 1140): + cableType = 11 + elif cableTypeOrg in (1210, 1220, 1230, 1240): + cableType = 12 + elif cableTypeOrg in (1231, 11232, 1233, 1234): + cableType = 123 + elif cableTypeOrg in (1161, 1162, 1163, 1164): + cableType = 116 + + if cableType == 11: + cableType = 1 + sectorAna = 1 + elif cableType == 12: + cableType = 2 + sectorAna = 1 + + return cableType, sectorAna + + +def _parse_settings(settings_arr, in_struct, mem): + """完整解析Settings数组,对应MATLAB第586-1194行""" + s = mem['MatlabGateway']['settings'] + n = len(settings_arr) + + if n > 17: + s['videoOffs'] = int(settings_arr[17]) + else: + s['videoOffs'] = 0 + + if n >= 7: + s['nominalData'] = settings_arr[1:7].copy() + else: + s['nominalData'] = np.zeros(6) + + if 'tolchk' not in s: + s['tolchk'] = {} + if len(s['nominalData']) >= 6: + s['tolchk']['NomDM'] = s['nominalData'][4] + s['tolchk']['NomOSC'] = s['nominalData'][3] + s['tolchk']['NomISO'] = s['nominalData'][2] + s['tolchk']['NomISC'] = s['nominalData'][1] + s['tolchk']['NomCore'] = s['nominalData'][5] + + if 'avgData' not in s: + s['avgData'] = {} + if n > 9: + s['avgData']['init'] = int(settings_arr[9]) + if n > 10: + s['avgData']['video_req_time'] = settings_arr[10] + if n > 11: + s['avgData']['dia_insens'] = settings_arr[11] + mean_time_fac = 1 + if n > 12: + s['avgData']['mean_time_dm'] = settings_arr[12] * mean_time_fac + if n > 13: + s['avgData']['lay_insens'] = settings_arr[13] + if n > 14: + s['avgData']['mean_time_lay'] = settings_arr[14] * mean_time_fac + if n > 15: + s['unit'] = int(settings_arr[15]) + if n > 16: + s['bRotateXDir'] = int(settings_arr[16]) + + if 'plausiData' not in s: + s['plausiData'] = {} + if n > 19: + s['plausiData']['check_dm'] = int(settings_arr[19]) + s['plausiData']['abs_limit_dm'] = settings_arr[20] + s['plausiData']['rel_limit_dm'] = settings_arr[21] + if n > 22: + s['plausiData']['check_lay'] = int(settings_arr[22]) + s['plausiData']['abs_limit_lay'] = settings_arr[23] + s['plausiData']['rel_limit_lay'] = settings_arr[24] + + if n >= 32: + gmd = settings_arr[24:32] + if 'geometryData' not in s: + s['geometryData'] = {'x': {}, 'y': {}} + s['geometryData']['x']['x0'] = gmd[0] + s['geometryData']['y']['x0'] = gmd[1] + s['geometryData']['x']['y0'] = gmd[2] + s['geometryData']['y']['y0'] = gmd[3] + s['geometryData']['x']['xCCD'] = gmd[4] + s['geometryData']['y']['xCCD'] = gmd[5] + s['geometryData']['x']['yCCD'] = gmd[6] + s['geometryData']['y']['yCCD'] = gmd[7] + + if 'correctionData' not in s: + s['correctionData'] = {'x': np.array([]), 'y': np.array([])} + if 'gap' not in s: + s['gap'] = {'x': np.array([]), 'y': np.array([]), + 'dxCCD': {'x': 0, 'y': 0}} + + if n > 33: + devicetype = int(settings_arr[33]) + if devicetype < 500 or devicetype > 8101: + devicetype = 8000 + s['version']['devicetype'] = devicetype + + if n > 35: + s['cableStructure'] = int(settings_arr[35]) + + ind = 36 + if ind < n: + anz = int(settings_arr[ind]) + if anz > 0 and ind + anz < n: + s['correctionData']['x'] = settings_arr[ind + 1:ind + anz + 1].copy() + ind = ind + anz + 1 + + if ind < n: + anz = int(settings_arr[ind]) + if anz > 0 and ind + anz < n: + s['correctionData']['y'] = settings_arr[ind + 1:ind + anz + 1].copy() + ind = ind + anz + 1 + + if ind < n: + s['gap']['dxCCD']['x'] = settings_arr[ind] + ind += 1 + if ind < n: + Ngapx = int(settings_arr[ind]) + ind += 1 + if Ngapx > 0 and ind + 2 * Ngapx <= n: + gap_x = np.zeros((4, Ngapx)) + gap_x[0, :] = settings_arr[ind:ind + Ngapx] + ind += Ngapx + gap_x[1, :] = settings_arr[ind:ind + Ngapx] + ind += Ngapx + s['gap']['x'] = gap_x + else: + ind += 2 * Ngapx + + if ind < n: + s['gap']['dxCCD']['y'] = settings_arr[ind] + ind += 1 + if ind < n: + Ngapy = int(settings_arr[ind]) + ind += 1 + if Ngapy > 0 and ind + 2 * Ngapy <= n: + gap_y = np.zeros((4, Ngapy)) + gap_y[0, :] = settings_arr[ind:ind + Ngapy] + ind += Ngapy + gap_y[1, :] = settings_arr[ind:ind + Ngapy] + ind += Ngapy + s['gap']['y'] = gap_y + else: + ind += 2 * Ngapy + + if 'geometryData' not in s: + s['geometryData'] = {'x': {}, 'y': {}} + s['geometryData']['x']['gamma'] = np.array([]) + s['geometryData']['y']['gamma'] = np.array([]) + if ind + 1 < n: + s['geometryData']['x']['gamma'] = settings_arr[ind] + ind += 1 + s['geometryData']['y']['gamma'] = settings_arr[ind] + ind += 1 + + if 'cableData' not in s: + s['cableData'] = {} + s['cableData']['baseAngle'] = np.array([]) + s['cableData']['orientation'] = np.array([]) + if ind + 1 < n: + s['cableData']['baseAngle'] = settings_arr[ind] + ind += 1 + s['cableData']['orientation'] = settings_arr[ind] + ind += 1 + + s['cableData']['nomHeight'] = np.array([]) + s['cableData']['nomWidth'] = np.array([]) + s['cableData']['threshold'] = np.array([]) + if ind + 2 < n: + s['cableData']['nomHeight'] = settings_arr[ind] + ind += 1 + s['cableData']['nomWidth'] = settings_arr[ind] + ind += 1 + s['cableData']['threshold'] = settings_arr[ind] + ind += 1 + + s['eightpoint'] = np.array([]) + if ind < n: + s['eightpoint'] = settings_arr[ind] + ind += 1 + + s['cableData']['nomR1'] = np.array([]) + s['cableData']['nomR2'] = np.array([]) + s['cableData']['twistMaximum'] = np.array([]) + if 'attprofsett' not in s: + s['attprofsett'] = {} + s['attprofsett']['mode'] = np.array([]) + s['attprofsett']['outer_margin'] = np.array([]) + s['attprofsett']['inner_margin'] = np.array([]) + s['attprofsett']['ringsize'] = np.array([]) + s['attprofsett']['meantime'] = np.array([]) + s['attprofsett']['refattfactor'] = np.array([]) + if ind + 8 < n: + s['cableData']['nomR1'] = settings_arr[ind] + ind += 1 + s['cableData']['nomR2'] = settings_arr[ind] + ind += 1 + s['cableData']['twistMaximum'] = settings_arr[ind] + ind += 1 + s['attprofsett']['mode'] = int(settings_arr[ind]) + ind += 1 + s['attprofsett']['outer_margin'] = settings_arr[ind] + ind += 1 + s['attprofsett']['inner_margin'] = settings_arr[ind] + ind += 1 + s['attprofsett']['ringsize'] = settings_arr[ind] + ind += 1 + s['attprofsett']['meantime'] = settings_arr[ind] + ind += 1 + s['attprofsett']['refattfactor'] = settings_arr[ind] + ind += 1 + + s['avgData']['mean_time_vw'] = np.array([]) + if ind < n: + s['avgData']['mean_time_vw'] = settings_arr[ind] + ind += 1 + + mem['MatlabGateway']['err_meas_head'] = np.zeros((2, 1)) + s['avgData']['dia_warninsens'] = np.array([]) + s['avgData']['lay_warninsens'] = np.array([]) + if ind + 3 < n: + mem['MatlabGateway']['err_meas_head'][0, 0] = settings_arr[ind] + ind += 1 + mem['MatlabGateway']['err_meas_head'][1, 0] = settings_arr[ind] + ind += 1 + s['avgData']['dia_warninsens'] = settings_arr[ind] + ind += 1 + s['avgData']['lay_warninsens'] = settings_arr[ind] + ind += 1 + + devicetype = s['version'].get('devicetype', 8000) + s['avgData']['xray8k'] = (devicetype >= 8000 and devicetype <= 8101) + + if 'voiddetectsett' not in s: + s['voiddetectsett'] = {} + s['voiddetectsett']['on'] = np.array([]) + s['voiddetectsett']['maxerrdiam'] = np.array([]) + if ind + 1 < n: + s['voiddetectsett']['on'] = int(settings_arr[ind]) + ind += 1 + s['voiddetectsett']['maxerrdiam'] = settings_arr[ind] + ind += 1 + + s['avgData']['reduceavgon'] = np.array([]) + if ind < n: + s['avgData']['reduceavgon'] = int(settings_arr[ind]) + ind += 1 + + s['dm_laser_core'] = np.array([]) + if ind < n: + s['dm_laser_core'] = settings_arr[ind] + ind += 1 + + s['avgData']['determine_distance'] = np.array([]) + if ind < n: + s['avgData']['determine_distance'] = int(settings_arr[ind]) + ind += 1 + + s['tolchk']['NomWTH'] = np.array([]) + s['tolchk']['PtolDMmean'] = np.array([]) + s['tolchk']['NtolDMmean'] = np.array([]) + s['tolchk']['PtolDM'] = np.array([]) + s['tolchk']['NtolDM'] = np.array([]) + s['tolchk']['PtolOSCmean'] = np.array([]) + s['tolchk']['NtolOSCmean'] = np.array([]) + s['tolchk']['PtolOSC'] = np.array([]) + s['tolchk']['NtolOSC'] = np.array([]) + s['tolchk']['PtolOSCecc'] = np.array([]) + s['tolchk']['PtolISOmean'] = np.array([]) + s['tolchk']['NtolISCmean'] = np.array([]) + s['tolchk']['PtolISO'] = np.array([]) + s['tolchk']['NtolISO'] = np.array([]) + s['tolchk']['PtolISOecc'] = np.array([]) + s['tolchk']['NtolISOmean'] = np.array([]) + s['tolchk']['PtolISCmean'] = np.array([]) + s['tolchk']['PtolISC'] = np.array([]) + s['tolchk']['NtolISC'] = np.array([]) + s['tolchk']['PtolISCecc'] = np.array([]) + s['tolchk']['PtolWTHmean'] = np.array([]) + s['tolchk']['NtolWTHmean'] = np.array([]) + s['tolchk']['PtolWTH'] = np.array([]) + s['tolchk']['NtolWTH'] = np.array([]) + s['tolchk']['PtolWTHecc'] = np.array([]) + s['tolchk']['PtolCoremean'] = np.array([]) + s['tolchk']['NtolCoremean'] = np.array([]) + s['tolchk']['PtolCore'] = np.array([]) + s['tolchk']['NtolCore'] = np.array([]) + + if ind + 28 <= n: + s['tolchk']['NomWTH'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolDMmean'] = settings_arr[ind] + ind += 1 + s['tolchk']['NtolDMmean'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolDM'] = settings_arr[ind] + ind += 1 + s['tolchk']['NtolDM'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolOSCmean'] = settings_arr[ind] + ind += 1 + s['tolchk']['NtolOSCmean'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolOSC'] = settings_arr[ind] + ind += 1 + s['tolchk']['NtolOSC'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolOSCecc'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolISOmean'] = settings_arr[ind] + ind += 1 + s['tolchk']['NtolISCmean'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolISO'] = settings_arr[ind] + ind += 1 + s['tolchk']['NtolISO'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolISOecc'] = settings_arr[ind] + ind += 1 + s['tolchk']['NtolISOmean'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolISCmean'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolISC'] = settings_arr[ind] + ind += 1 + s['tolchk']['NtolISC'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolISCecc'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolWTHmean'] = settings_arr[ind] + ind += 1 + s['tolchk']['NtolWTHmean'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolWTH'] = settings_arr[ind] + ind += 1 + s['tolchk']['NtolWTH'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolWTHecc'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolCoremean'] = settings_arr[ind] + ind += 1 + s['tolchk']['NtolCoremean'] = settings_arr[ind] + ind += 1 + s['tolchk']['PtolCore'] = settings_arr[ind] + ind += 1 + s['tolchk']['NtolCore'] = settings_arr[ind] + ind += 1 + + s['AutoDetHVon'] = np.array([]) + if ind < n: + s['AutoDetHVon'] = int(settings_arr[ind]) + ind += 1 + + s['ProdType'] = np.array([]) + if ind < n: + s['ProdType'] = int(settings_arr[ind]) + ind += 1 + + s['VideoRec'] = np.array([]) + if ind < n: + s['VideoRec'] = int(settings_arr[ind]) + ind += 1 + + s['VideoRecNr'] = np.array([]) + if ind < n: + s['VideoRecNr'] = settings_arr[ind] + ind += 1 + + s['voltage'] = np.array([]) + if ind < n: + s['voltage'] = settings_arr[ind] + ind += 1 + + s['TwistAngle'] = 0 + if ind < n: + s['TwistAngle'] = settings_arr[ind] * np.pi / 180 + ind += 1 + + s['RiffleHeight'] = 0 + if ind < n: + s['RiffleHeight'] = settings_arr[ind] + if s['RiffleHeight'] <= 0: + s['RiffleHeight'] = 0 + ind += 1 + + s['RiffleTopWidth'] = 0 + if ind < n: + s['RiffleTopWidth'] = settings_arr[ind] + if s['RiffleTopWidth'] <= 0: + s['RiffleTopWidth'] = 0 + ind += 1 + + s['RiffleBaseWidth'] = 0 + if ind < n: + s['RiffleBaseWidth'] = settings_arr[ind] + if s['RiffleBaseWidth'] <= 0: + s['RiffleBaseWidth'] = 0 + ind += 1 + + s['RiffleCount'] = 0 + if ind < n: + s['RiffleCount'] = int(settings_arr[ind]) + if s['RiffleCount'] <= 0: + s['RiffleCount'] = 0 + ind += 1 + + s['Reconstruct'] = 0 + if ind < n: + s['Reconstruct'] = int(settings_arr[ind]) + if s['Reconstruct'] < 0 or s['Reconstruct'] > 4: + s['Reconstruct'] = 0 + ind += 1 + + s['rest'] = np.array([]) + if ind + 2 < n: + s['rest'] = settings_arr[ind:ind + 3].copy() + ind += 3 + + s['paraECClimit'] = np.array([]) + if ind < n: + s['paraECClimit'] = settings_arr[ind] + ind += 1 + + s['paraECCmin'] = np.array([]) + if ind < n: + s['paraECCmin'] = settings_arr[ind] + ind += 1 + + if ind < n: + rest_arr = settings_arr[ind:].copy() + if len(rest_arr) > 0: + if isinstance(s.get('rest'), np.ndarray) and s['rest'].size > 0: + s['rest'] = np.concatenate([s['rest'], rest_arr]) + else: + s['rest'] = rest_arr + + return mem + + +def _init_mem(settings_arr, in_struct): + mem = {'MatlabGateway': {}, 'Unsharpness': {}} + mem['MatlabGateway']['settings'] = {} + mem['MatlabGateway']['settings']['confData'] = np.array([]) + mem['MatlabGateway']['settings']['geometryData'] = {'x': {}, 'y': {}} + + if len(settings_arr) >= 32: + gmd = settings_arr[24:32] + mem['MatlabGateway']['settings']['geometryData']['x']['x0'] = gmd[0] + mem['MatlabGateway']['settings']['geometryData']['y']['x0'] = gmd[1] + mem['MatlabGateway']['settings']['geometryData']['x']['y0'] = gmd[2] + mem['MatlabGateway']['settings']['geometryData']['y']['y0'] = gmd[3] + mem['MatlabGateway']['settings']['geometryData']['x']['xCCD'] = gmd[4] + mem['MatlabGateway']['settings']['geometryData']['y']['xCCD'] = gmd[5] + mem['MatlabGateway']['settings']['geometryData']['x']['yCCD'] = gmd[6] + mem['MatlabGateway']['settings']['geometryData']['y']['yCCD'] = gmd[7] + + mem['MatlabGateway']['rawIntensity'] = {'x': np.array([]), 'y': np.array([])} + mem['MatlabGateway']['refIntensity'] = { + 'bright': {'x': np.array([]), 'y': np.array([])}, + 'dark': {'static': {'x': np.array([]), 'y': np.array([])}, + 'dynamic': {'x': np.array([]), 'y': np.array([])}}, + } + mem['MatlabGateway']['StoreOption'] = 0 + mem['MatlabGateway']['restartRefVideo'] = settings_arr[32] if len(settings_arr) > 32 else 0 + mem['MatlabGateway']['settings']['calib_struct'] = {'int': np.array([]), 'ext': np.array([])} + mem['Unsharpness']['FiltMatrix_X'] = np.array([]) + mem['Unsharpness']['FiltMatrix_Y'] = np.array([]) + mem['MatlabGateway']['Debugdata'] = {'Errorcounter': 0} + + mem['MatlabGateway']['settings']['version'] = {'NXT': in_struct.get('NXT', 0)} + mem['MatlabGateway']['settings']['cableTypeOrg'] = settings_arr[7] if len(settings_arr) > 7 else 0 + + mem = _parse_settings(settings_arr, in_struct, mem) + + return mem + + +def _safe_get(obj, key, default=None): + """安全获取字段,支持 dict 和 mat_struct""" + if isinstance(obj, dict): + return obj.get(key, default) + if hasattr(obj, key): + val = getattr(obj, key) + if isinstance(val, np.ndarray) and val.size == 1: + return val.flat[0] + return val + return default + + +def _safe_has(obj, key): + """安全检查字段是否存在,支持 dict 和 mat_struct""" + if isinstance(obj, dict): + return key in obj + return hasattr(obj, key) + + +def matlabgateway(in_struct): + # 转换 mat_struct 为 dict(如果需要) + if not isinstance(in_struct, dict) and ( + hasattr(in_struct, '_fieldnames') or + (isinstance(in_struct, np.ndarray) and in_struct.size > 0 and + hasattr(in_struct.flat[0], '_fieldnames'))): + in_struct = _mat_struct_to_dict(in_struct) + + OutStruct = {} + memStruct = {} + + OutStruct['GatewayStatus'] = np.array([]) + OutStruct['AnaVersion'] = np.array([]) + OutStruct['WtOSC'] = np.array([]) + OutStruct['WtINS'] = np.array([]) + OutStruct['WtISC'] = np.array([]) + OutStruct['WtALL'] = np.array([]) + OutStruct['DmCORE'] = np.array([]) + OutStruct['DmALL'] = np.array([]) + OutStruct['DmINS'] = np.array([]) + OutStruct['DmISC'] = np.array([]) + OutStruct['WtBis'] = np.array([]) + OutStruct['MMAng'] = np.array([]) + OutStruct['AttCoeff'] = np.array([]) + OutStruct['AttCoeffSt'] = np.array([]) + OutStruct['VW'] = np.array([]) + OutStruct['xyPos'] = np.array([]) + OutStruct['Warning'] = np.array([]) + OutStruct['Void'] = np.array([]) + OutStruct['Edges'] = np.array([]) + OutStruct['Tolcheckout'] = np.array([]) + OutStruct['AutoDet'] = np.array([]) + + has_iIntensX = 'iIntensX' in in_struct + if has_iIntensX: + OutStruct['NormVideoX'] = np.array([]) + OutStruct['NormVideoY'] = np.array([]) + OutStruct['EdgesLeftX'] = np.array([]) + OutStruct['EdgesRightX'] = np.array([]) + OutStruct['EdgesLeftY'] = np.array([]) + OutStruct['EdgesRightY'] = np.array([]) + else: + for i in range(1, 9): + OutStruct[f'NormVideo1{i}'] = np.array([]) + OutStruct[f'NormVideo2{i}'] = np.array([]) + OutStruct[f'EdgesLeft1{i}'] = np.array([]) + OutStruct[f'EdgesLeft2{i}'] = np.array([]) + OutStruct[f'EdgesRight1{i}'] = np.array([]) + OutStruct[f'EdgesRight2{i}'] = np.array([]) + + OutStruct['ScanWay'] = np.zeros((1, 4)) + OutStruct['Debugdata'] = {'Errorcounter': 0} + if has_iIntensX: + OutStruct['Debugdata']['dmOut'] = np.zeros((3, 2)) + else: + OutStruct['Debugdata']['dmOut'] = np.zeros((3, 14)) + + mem = None + global _Lsq_LM_on, _Unsharpness + _Lsq_LM_on = 0 + _Unsharpness = 0 + try: + from analysis_utils import startx2ana + from overview_utils import startx8ana, ovrview + + settings_arr = np.asarray(in_struct.get('Settings', np.zeros(200)), dtype=np.float64) + + mem = get_user_data() + is_mem_new = (mem is None or 'MatlabGateway' not in mem) + if is_mem_new: + mem = _init_mem(settings_arr, in_struct) + # 读取配置文件 + config_file = in_struct.get('ConfigFile', '') + confData = mem['MatlabGateway']['settings'].get('confData', np.array([])) + if (config_file and len(config_file) > 0 and + (not isinstance(confData, np.ndarray) or confData.size == 0)): + import os + if os.path.isfile(config_file): + from calibration_utils import floatread + mem['MatlabGateway']['settings']['confData'] = floatread(config_file, 1) + else: + # 尝试在 ConfigFiles 目录中查找 + local_cfg = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + 'ConfigFiles', 'confx2.prn') + if os.path.isfile(local_cfg): + from calibration_utils import floatread + mem['MatlabGateway']['settings']['confData'] = floatread(local_cfg, 1) + # 设置 confData[19] = cableType (对应 MATLAB confData(20)) + confData = mem['MatlabGateway']['settings'].get('confData', np.array([])) + if isinstance(confData, np.ndarray) and confData.size > 19 and len(settings_arr) > 7: + confData[19] = settings_arr[7] + # 计算 dx = conf[31] * conf[30],对应 MATLAB chksettings + if isinstance(confData, np.ndarray) and confData.size > 91: + confData[89] = confData[31] * confData[30] if confData.size > 31 else 0 + confData[90] = 1 + confData[91] = confData[89] / confData[90] if confData[90] != 0 else 0.048 + if confData[91] == 0: + confData[91] = 0.048 + + # 加载校准数据(对应 MATLAB matlabgateway.m 第 661-715 行) + calib_int = mem['MatlabGateway']['settings'].get('calib_struct', {}).get('int', np.array([])) + config_file = in_struct.get('ConfigFile', '') + if (not isinstance(calib_int, dict) or len(calib_int) == 0) and len(config_file) > 10: + import os + from calibration_utils import read_calibration + + devicetype = mem['MatlabGateway']['settings'].get('version', {}).get('devicetype', 8000) + # 对应 MATLAB switch-case 语句(matlabgateway.m 第 663-707 行) + califile_map = { + 500: 'Internal_Layer_Calibration_2120.cfg', + 501: 'Internal_Layer_Calibration_2120.cfg', + 502: 'Internal_Layer_Calibration_2035.cfg', + 503: 'Internal_Layer_Calibration_2080.cfg', + 504: 'Internal_Layer_Calibration_2300.cfg', + 505: 'Internal_Layer_Calibration_2060.cfg', + 506: 'Internal_Layer_Calibration_2200.cfg', + 507: 'Internal_Layer_Calibration_2120.cfg', + 508: 'Internal_Layer_Calibration_2120.cfg', + 8000: 'Internal_Layer_Calibration_8000.cfg', + 8001: 'Internal_Layer_Calibration_8000.cfg', + 8100: 'Internal_Layer_Calibration_8100.cfg', + 8101: 'Internal_Layer_Calibration_8100.cfg', + } + califile_name = califile_map.get(devicetype, 'Internal_Layer_Calibration_xxxx.cfg') + if devicetype not in califile_map: + print(f'[matlabgateway] Warning: Unknown measuring head devicetype={devicetype}') + + # 尝试从 ConfigFile 同目录中查找 + cfg_dir = os.path.dirname(config_file) + califile = os.path.join(cfg_dir, califile_name) + if not os.path.isfile(califile): + # 尝试在项目 ConfigFiles 目录中查找 + local_calib = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + 'ConfigFiles', califile_name) + if os.path.isfile(local_calib): + califile = local_calib + else: + califile = '' + + if califile and os.path.isfile(califile): + calib_data = read_calibration(califile) + if isinstance(calib_data, dict) and len(calib_data) > 0: + mem['MatlabGateway']['settings']['calib_struct']['int'] = calib_data + else: + if len(settings_arr) >= 32: + gmd = settings_arr[24:32] + if 'geometryData' not in mem['MatlabGateway']['settings']: + mem['MatlabGateway']['settings']['geometryData'] = {'x': {}, 'y': {}} + mem['MatlabGateway']['settings']['geometryData']['x']['x0'] = gmd[0] + mem['MatlabGateway']['settings']['geometryData']['y']['x0'] = gmd[1] + mem['MatlabGateway']['settings']['geometryData']['x']['y0'] = gmd[2] + mem['MatlabGateway']['settings']['geometryData']['y']['y0'] = gmd[3] + mem['MatlabGateway']['settings']['geometryData']['x']['xCCD'] = gmd[4] + mem['MatlabGateway']['settings']['geometryData']['y']['xCCD'] = gmd[5] + mem['MatlabGateway']['settings']['geometryData']['x']['yCCD'] = gmd[6] + mem['MatlabGateway']['settings']['geometryData']['y']['yCCD'] = gmd[7] + mem['MatlabGateway']['settings']['version'] = {'NXT': in_struct.get('NXT', 0)} + mem['MatlabGateway']['settings']['cableTypeOrg'] = settings_arr[7] if len(settings_arr) > 7 else 0 + mem = _parse_settings(settings_arr, in_struct, mem) + + cableTypeOrg = mem['MatlabGateway']['settings'].get('cableTypeOrg', 0) + cableType, sectorAna = _convert_cable_type(cableTypeOrg) + mem['MatlabGateway']['settings']['cableType'] = cableType + mem['MatlabGateway']['settings']['sectorAna'] = sectorAna + + if _Unsharpness == 1 and (cableTypeOrg < 51 or cableTypeOrg > 53): + fx = mem['Unsharpness'].get('FiltMatrix_X', np.array([])) + fy = mem['Unsharpness'].get('FiltMatrix_Y', np.array([])) + if (not isinstance(fx, np.ndarray) or fx.size == 0 or + not isinstance(fy, np.ndarray) or fy.size == 0): + devicetype = settings_arr[33] if len(settings_arr) > 33 else 0 + devicetype_int = int(devicetype) + print(f'[matlabgateway] Unsharpness enabled but not yet supported ' + f'(device type {devicetype_int}). GenFiltMatrix and FiltPara_*.mat ' + f'loading are not implemented in Python version.') + + IntensType = int(settings_arr[0]) if len(settings_arr) > 0 else 0 + + if has_iIntensX: + if IntensType == 0 or IntensType == 4 or IntensType == 5: + mem['MatlabGateway']['rawIntensity']['x'] = np.asarray(in_struct.get('iIntensX', []), dtype=np.float64) + mem['MatlabGateway']['rawIntensity']['y'] = np.asarray(in_struct.get('iIntensY', []), dtype=np.float64) + if IntensType == 1: + mem['MatlabGateway']['refIntensity']['bright']['x'] = np.asarray(in_struct.get('iIntensX', []), dtype=np.float64) + mem['MatlabGateway']['refIntensity']['bright']['y'] = np.asarray(in_struct.get('iIntensY', []), dtype=np.float64) + if IntensType == 2: + mem['MatlabGateway']['refIntensity']['dark']['static']['x'] = np.asarray(in_struct.get('iIntensX', []), dtype=np.float64) + mem['MatlabGateway']['refIntensity']['dark']['static']['y'] = np.asarray(in_struct.get('iIntensY', []), dtype=np.float64) + if IntensType == 3: + mem['MatlabGateway']['refIntensity']['dark']['dynamic']['x'] = np.asarray(in_struct.get('iIntensX', []), dtype=np.float64) + mem['MatlabGateway']['refIntensity']['dark']['dynamic']['y'] = np.asarray(in_struct.get('iIntensY', []), dtype=np.float64) + + if IntensType == 0: + mem['MatlabGateway']['refIntensity']['bright']['x'] = np.asarray(in_struct.get('iBrightX', []), dtype=np.float64) + mem['MatlabGateway']['refIntensity']['bright']['y'] = np.asarray(in_struct.get('iBrightY', []), dtype=np.float64) + mem['MatlabGateway']['refIntensity']['dark']['static']['x'] = np.asarray(in_struct.get('iDarkStaticX', []), dtype=np.float64) + mem['MatlabGateway']['refIntensity']['dark']['static']['y'] = np.asarray(in_struct.get('iDarkStaticY', []), dtype=np.float64) + mem['MatlabGateway']['refIntensity']['dark']['dynamic']['x'] = np.asarray(in_struct.get('iDarkDynamicX', []), dtype=np.float64) + mem['MatlabGateway']['refIntensity']['dark']['dynamic']['y'] = np.asarray(in_struct.get('iDarkDynamicY', []), dtype=np.float64) + + if IntensType in (7, 8, 9): + raw_list = [] + prefixes = [] + if IntensType == 7: + prefixes = ['11', '12', '13', '14', '15', '16', '17', '18'] + elif IntensType == 8: + prefixes = ['21', '22', '23', '24', '25', '26', '27', '28'] + elif IntensType == 9: + prefixes = ['11', '12', '13', '14', '15', '16', '17', '18', + '21', '22', '23', '24', '25', '26', '27', '28'] + for p in prefixes: + kx = f'iIntens{p[:1]}{p[1:]}' if len(p) == 2 else f'iIntens{p}' + ky = kx + x_data = in_struct.get(f'iIntens{p}', np.array([])) + y_data = in_struct.get(f'iIntens{p}', np.array([])) + if isinstance(x_data, np.ndarray) and x_data.size > 0: + raw_list.append({ + 'x': np.asarray(x_data, dtype=np.float64), + 'y': np.asarray(y_data, dtype=np.float64) + }) + if len(raw_list) > 0: + mem['MatlabGateway']['rawIntensity'] = raw_list + + new_restartRefVideo = settings_arr[32] if len(settings_arr) > 32 else 0 + if new_restartRefVideo != mem['MatlabGateway'].get('restartRefVideo', 0): + mem['MatlabGateway']['restartRefVideo'] = new_restartRefVideo + mem['MatlabGateway']['refIntensity']['bright']['x'] = np.array([]) + mem['MatlabGateway']['refIntensity']['dark']['static']['x'] = np.array([]) + mem['MatlabGateway']['refIntensity']['dark']['dynamic']['x'] = np.array([]) + + gatewayStatus = 0 + + bright_x = mem['MatlabGateway']['refIntensity']['bright'].get('x', np.array([])) + dark_static_x = mem['MatlabGateway']['refIntensity']['dark']['static'].get('x', np.array([])) + dark_dynamic_x = mem['MatlabGateway']['refIntensity']['dark']['dynamic'].get('x', np.array([])) + + if isinstance(bright_x, np.ndarray) and bright_x.size == 0: + gatewayStatus |= 2 + if isinstance(dark_static_x, np.ndarray) and dark_static_x.size == 0: + gatewayStatus |= 4 + if isinstance(dark_dynamic_x, np.ndarray) and dark_dynamic_x.size == 0: + gatewayStatus |= 8 + elif isinstance(dark_dynamic_x, np.ndarray) and np.mean(dark_dynamic_x) < 1: + gatewayStatus |= 8 + + if IntensType in (4, 5, 7, 8, 9): + gatewayStatus = 0 + + if not has_iIntensX: + raw_list = in_struct.get('rawIntensity', []) + if isinstance(raw_list, list): + mem['MatlabGateway']['rawIntensity'] = raw_list + ref_list = in_struct.get('refIntensity', []) + if isinstance(ref_list, list): + mem['MatlabGateway']['refIntensity'] = ref_list + sensorStatus_raw = in_struct.get('sensorStatus', np.zeros((20,))) + sensorStatus_arr = np.asarray(sensorStatus_raw).flatten() + sensorStatus_decoded = np.zeros((20, 16), dtype=np.uint16) + for i in range(min(20, len(sensorStatus_arr))): + val = int(sensorStatus_arr[i]) + for bit in range(16): + sensorStatus_decoded[i, bit] = (val >> bit) & 1 + mem['MatlabGateway']['sensorStatus'] = sensorStatus_decoded + + if IntensType in (0, 4, 5, 7, 8, 9) and gatewayStatus == 0: + if IntensType == 0 and has_iIntensX: + rawvideo = [mem['MatlabGateway']['rawIntensity']['x'], + mem['MatlabGateway']['rawIntensity']['y']] + rawbrightvideo = [mem['MatlabGateway']['refIntensity']['bright']['x'], + mem['MatlabGateway']['refIntensity']['bright']['y']] + rawvideoDark_static = [mem['MatlabGateway']['refIntensity']['dark']['static']['x'], + mem['MatlabGateway']['refIntensity']['dark']['static']['y']] + rawvideoDark_dynamic = [mem['MatlabGateway']['refIntensity']['dark']['dynamic']['x'], + mem['MatlabGateway']['refIntensity']['dark']['dynamic']['y']] + rawdarkvideo = rawvideoDark_dynamic + + settings = mem['MatlabGateway']['settings'] + errsettings = mem['MatlabGateway']['err_meas_head'] + mem_local = {} + init = 1 + + if _Unsharpness == 1: + print('[matlabgateway] Unsharpness mode for startx2ana is not yet supported. ' + 'Falling back to normal mode.') + + (avgresults, results, edges, status_x, status_y, + attL_x, attR_x, attL_y, attR_y, errnorm, + AutoDet, mem_local, IN_x, IN_y, AttCoeff, AttCoeffSt, Void) = startx2ana( + rawvideo, rawdarkvideo, rawvideoDark_static, rawvideoDark_dynamic, + rawbrightvideo, settings, errsettings, mem_local, init + ) + + OutStruct['AutoDet'] = AutoDet + OutStruct['AttCoeff'] = AttCoeff + OutStruct['AttCoeffSt'] = AttCoeffSt + OutStruct['Void'] = Void + + _fill_outstruct_2k(OutStruct, avgresults, results, edges, status_x, status_y) + + elif IntensType in (4, 5): + axis = 0 if IntensType == 4 else 1 + settings = mem['MatlabGateway']['settings'] + err_meas_head = mem['MatlabGateway']['err_meas_head'] + sensorStatus = mem['MatlabGateway'].get('sensorStatus', np.zeros((20, 16))) + rawInt = mem['MatlabGateway'].get('rawIntensity', {}) + if isinstance(rawInt, list) and len(rawInt) > 0: + rawInt_single = rawInt[0] + elif isinstance(rawInt, dict) and 'x' in rawInt: + rawInt_single = rawInt + else: + rawInt_single = {'x': np.array([]), 'y': np.array([])} + senPair = [1, 1] + + (avgresults, results, edges, status, att, err, layeruse, + AttCoeff, AttCoeffSt, Void, AutoDet, ScanWay, + NormVideoX, NormVideoY, detail_a, detail_b) = startx8ana( + rawInt_single, settings, err_meas_head, sensorStatus, senPair, axis + ) + + OutStruct['AutoDet'] = AutoDet + OutStruct['AttCoeff'] = AttCoeff + OutStruct['AttCoeffSt'] = AttCoeffSt + OutStruct['Void'] = Void + OutStruct['ScanWay'] = ScanWay + if hasattr(NormVideoX, '__len__'): + OutStruct['NormVideoX'] = np.asarray(NormVideoX) + if hasattr(NormVideoY, '__len__'): + OutStruct['NormVideoY'] = np.asarray(NormVideoY) + + # 调用 conv2dsp 计算综合结果 + from conv2dsp_utils import conv2dsp + s = mem['MatlabGateway']['settings'] + factMinWt = settings_arr[34] if len(settings_arr) > 34 else 1 + devicetype_val = s.get('version', {}).get('devicetype', 8000) + NXT_val = s.get('version', {}).get('NXT', 0) + bRotateXDir_val = s.get('bRotateXDir', 0) + unit_val = s.get('unit', 0) + cableType_val = s.get('cableType', 0) + eightpoint_val = s.get('eightpoint', 0) + reduceavgon_val = s.get('avgData', {}).get('reduceavgon', 0) + twistAngle_val = s.get('TwistAngle', 0) + sectorAna_val = s.get('sectorAna', 0) + + (OSC_c, ISO_c, ISC_c, WTH_c, DMTotal_c, DMCore_c, DMINS_c, DMISC_c, + BisecWTH_c, MinMaxAng_c) = conv2dsp( + avgresults, bRotateXDir_val, factMinWt, unit_val, layeruse, + cableType_val, eightpoint_val, reduceavgon_val, twistAngle_val, + s, devicetype_val, sectorAna_val, NXT_val + ) + + # 按 MATLAB 格式拼接 [value_row, status_row] + def _pack_result(val_arr): + a = np.asarray(val_arr, dtype=np.float64) + return np.concatenate([a[0, :], a[1, :]]) + + OutStruct['WtOSC'] = _pack_result(OSC_c) + OutStruct['WtINS'] = _pack_result(ISO_c) + OutStruct['WtISC'] = _pack_result(ISC_c) + OutStruct['WtALL'] = _pack_result(WTH_c) + OutStruct['DmCORE'] = _pack_result(DMCore_c) + OutStruct['DmALL'] = _pack_result(DMTotal_c) + OutStruct['DmINS'] = _pack_result(DMINS_c) + OutStruct['DmISC'] = _pack_result(DMISC_c) + OutStruct['WtBis'] = _pack_result(BisecWTH_c) + OutStruct['MMAng'] = _pack_result(MinMaxAng_c) + + if 'left' in edges and 'right' in edges: + left_edges = edges['left'] + right_edges = edges['right'] + OutStruct['EdgesLeftX'] = left_edges.get('x', np.array([])) + OutStruct['EdgesLeftY'] = left_edges.get('y', np.array([])) + OutStruct['EdgesRightX'] = right_edges.get('x', np.array([])) + OutStruct['EdgesRightY'] = right_edges.get('y', np.array([])) + + elif IntensType in (7, 8): + axis = 0 if IntensType == 7 else 1 + settings = mem['MatlabGateway']['settings'] + err_meas_head = mem['MatlabGateway']['err_meas_head'] + sensorStatus = mem['MatlabGateway'].get('sensorStatus', np.zeros((20, 16))) + rawInt = mem['MatlabGateway'].get('rawIntensity', []) + if isinstance(rawInt, dict) and 'x' in rawInt: + rawInt_list = [rawInt] + elif isinstance(rawInt, list) and len(rawInt) > 0: + rawInt_list = rawInt + else: + rawInt_list = [] + cableTypeOrg_val = settings.get('cableTypeOrg', 0) + + if cableTypeOrg_val in (111, 2, 22, 116) and len(rawInt_list) > 0: + settings, err_meas_head = ovrview(rawInt_list, settings, err_meas_head, sensorStatus, axis) + + num_sensors = len(rawInt_list) + NormVideoX_arr = [] + NormVideoY_arr = [] + + for senPair in range(num_sensors): + settings_loc = copy.deepcopy(settings) + settings_loc['avgData'] = settings_loc.get('avgData', {}) + if senPair > 0: + settings_loc['avgData']['init'] = 0 + + raw_sen = rawInt[senPair] if isinstance(rawInt, list) and senPair < len(rawInt) else rawInt + sen_pair_arr = [senPair + 1, num_sensors] + + (avgresults_s, results_s, edges_s, status_s, att_s, err_s, layeruse_s, + AttCoeff_s, AttCoeffSt_s, Void_s, AutoDet_s, ScanWay_s, + NVx, NVy, da, db) = startx8ana( + raw_sen, settings_loc, err_meas_head, sensorStatus, sen_pair_arr, axis + ) + + if hasattr(NVx, '__len__'): + NormVideoX_arr.append(np.asarray(NVx)) + if hasattr(NVy, '__len__'): + NormVideoY_arr.append(np.asarray(NVy)) + + prefix = '1' if axis == 0 else '2' + for i in range(min(4, len(NormVideoY_arr))): + OutStruct[f'NormVideo{prefix}{2*i+1}'] = NormVideoY_arr[i] if i < len(NormVideoY_arr) else np.array([]) + OutStruct[f'NormVideo{prefix}{2*i+2}'] = NormVideoX_arr[i] if i < len(NormVideoX_arr) else np.array([]) + + OutStruct['GatewayStatus'] = np.array([np.uint16(gatewayStatus), np.uint16(0)]) + memStruct = mem + + except Exception as e: + import traceback + OutStruct['Warning'] = str(e) + '\n' + traceback.format_exc() + OutStruct['GatewayStatus'] = np.array([np.uint16(15), np.uint16(0)]) + memStruct = mem if mem is not None else {} + + finally: + if mem is not None: + set_user_data(mem) + + return OutStruct, memStruct + + +def _fill_outstruct_2k(OutStruct, avgresults, results, edges, status_x, status_y): + if isinstance(avgresults, dict): + dmOut = avgresults.get('dmOut', np.zeros((3, 2))) + if isinstance(dmOut, np.ndarray): + OutStruct['DmALL'] = dmOut + + coreDm = avgresults.get('coreDm', np.zeros((3, 2))) + if isinstance(coreDm, np.ndarray): + OutStruct['DmCORE'] = coreDm + + left = avgresults.get('left', {}) + right = avgresults.get('right', {}) + if isinstance(left, dict): + osc = left.get('osc', np.zeros((3, 2))) + iso = left.get('iso', np.zeros((3, 2))) + isc = left.get('isc', np.zeros((3, 2))) + if isinstance(osc, np.ndarray): + OutStruct['WtOSC'] = osc + if isinstance(iso, np.ndarray): + OutStruct['WtINS'] = iso + if isinstance(isc, np.ndarray): + OutStruct['WtISC'] = isc + + if isinstance(edges, dict): + left_edges = edges.get('left', {}) + right_edges = edges.get('right', {}) + if isinstance(left_edges, dict): + OutStruct['EdgesLeftX'] = left_edges.get('x', np.array([])) + OutStruct['EdgesLeftY'] = left_edges.get('y', np.array([])) + if isinstance(right_edges, dict): + OutStruct['EdgesRightX'] = right_edges.get('x', np.array([])) + OutStruct['EdgesRightY'] = right_edges.get('y', np.array([])) + + +def _mat_value_convert(val): + """将MATLAB加载的值转换为Python原生类型""" + if isinstance(val, np.ndarray): + if val.size == 0: + return np.array([]) + val_sq = np.squeeze(val) + if val_sq.ndim == 0: + if val_sq.dtype.kind in ('U', 'S'): + return str(val_sq.item()) + return val_sq.item() + return val_sq + return val + + +def _mat_struct_to_dict(elem): + """将 MATLAB struct 元素递归转换为 Python dict""" + if isinstance(elem, np.ndarray): + if elem.size == 0: + return {} + elem = elem.flat[0] if elem.size > 0 else elem + result = {} + fieldnames = [] + if hasattr(elem, '_fieldnames'): + fieldnames = elem._fieldnames + elif isinstance(elem, np.void) and elem.dtype.names: + fieldnames = elem.dtype.names + + for fn in fieldnames: + if hasattr(elem, fn): + raw_val = getattr(elem, fn) + else: + raw_val = elem[fn] + is_sub = False + if isinstance(raw_val, np.ndarray): + test = raw_val.flat[0] if raw_val.size > 0 else raw_val + if hasattr(test, '_fieldnames') or (isinstance(test, np.void) and test.dtype.names): + is_sub = True + if is_sub and isinstance(raw_val, np.ndarray): + items = [] + for i in range(raw_val.size): + items.append(_mat_struct_to_dict(raw_val.flat[i])) + result[fn] = items if len(items) > 1 else items[0] + else: + result[fn] = _mat_value_convert(raw_val) + return result + +def cpyAlgorithm(in_struct_path): + try: + if in_struct_path.endswith('.mat'): + in_struct = scipy.io.loadmat(in_struct_path) + if 'InStruct' in in_struct: + in_struct = _mat_struct_to_dict(in_struct['InStruct']) + in_struct['ConfigFile'] = r'D:\Qt\CpyAlgorithmServerQt\cpyAlgorithmMatlab2Python\ConfigFiles\confx2.prn' + else: + in_struct = np.load(in_struct_path) + except FileNotFoundError: + print(f"File not found: {in_struct_path}") + return None + except Exception as e: + print(f"Error loading file: {in_struct_path}") + print(e) + return None + + time_start = time.time() + outStruct, mem = matlabgateway(in_struct) + if outStruct is None: + return None + time_end = time.time() + print(f"Gateway time: {time_end - time_start:.4f} seconds") + + + out_struct_path = in_struct_path.replace('_in', '_new_out') + if in_struct_path.endswith('.mat'): + scipy.io.savemat(out_struct_path, {'OutStruct': outStruct, 'mem': mem}) + else: + np.savez(out_struct_path, OutStruct=outStruct, mem=mem) + + return out_struct_path diff --git a/algorithm/geometry_utils.py b/algorithm/geometry_utils.py new file mode 100644 index 0000000..8b21e4f --- /dev/null +++ b/algorithm/geometry_utils.py @@ -0,0 +1,933 @@ +import numpy as np +from thickness_utils import warnlogic + + +def strng2(x, left_edge, right_edge, flag=1): + """ + 计算 X 射线穿过圆形/圆柱形截面物体时,在每个像素位置处的材料路径长度(厚度)。 + + 对应 Matlab 的 strng2 函数。 + + 参数: + x: numpy.ndarray - 像素位置坐标数组 + left_edge: float - 物体左边缘位置 + right_edge: float - 物体右边缘位置 + flag: int - 计算模式标志 (默认1: 标准圆形截面路径长度) + + 返回: + numpy.ndarray: 与 x 同长度的数组,每个位置处的材料厚度 + 物体外的位置返回 0 + """ + x = np.asarray(x, dtype=np.float64) + + if right_edge <= left_edge: + return np.zeros_like(x) + + center = (left_edge + right_edge) / 2.0 + radius = (right_edge - left_edge) / 2.0 + + dx = x - center + inside = np.abs(dx) <= radius + + s = np.zeros_like(x) + s[inside] = 2.0 * np.sqrt(radius**2 - dx[inside]**2) + + return s + + +def strngellips(x, left_edge, right_edge, other_axis_diameter, flag=1): + """ + 计算 X 射线穿过椭圆形截面物体时,在每个像素位置处的材料路径长度(厚度)。 + + 对应 Matlab 的 strngellips 函数。 + + 参数: + x: numpy.ndarray - 像素位置坐标数组(沿当前扫描轴) + left_edge: float - 椭圆在当前扫描轴上的左边缘 + right_edge: float - 椭圆在当前扫描轴上的右边缘 + other_axis_diameter: float - 椭圆另一个正交轴的直径 + flag: int - 计算模式标志 (默认1: 标准椭圆截面路径长度) + + 返回: + numpy.ndarray: 与 x 同长度的数组,每个位置处的材料厚度 + 物体外的位置返回 0 + """ + x = np.asarray(x, dtype=np.float64) + + if right_edge <= left_edge or other_axis_diameter <= 0: + return np.zeros_like(x) + + a = (right_edge - left_edge) / 2.0 + b = other_axis_diameter / 2.0 + center = (left_edge + right_edge) / 2.0 + + dx = x - center + inside = np.abs(dx) <= a + + s = np.zeros_like(x) + ratio = (dx[inside] / a) ** 2 + ratio = np.clip(ratio, 0.0, 1.0) + s[inside] = 2.0 * b * np.sqrt(1.0 - ratio) + + return s + + +def xy_correct(xL_x, xR_x, xL_y, xR_y, x0_x, y0_x, xCCD_x, yCCD_x, + x0_y, y0_y, xCCD_y, yCCD_y, gamma_x, gamma_y, + status_x, status_y, statusL_x, statusR_x, statusL_y, statusR_y, + delta_xk, delta_yk, kx, ky, mode, layeruse): + xL_x = np.atleast_2d(np.asarray(xL_x, dtype=np.float64)) + xR_x = np.atleast_2d(np.asarray(xR_x, dtype=np.float64)) + xL_y = np.atleast_2d(np.asarray(xL_y, dtype=np.float64)) + xR_y = np.atleast_2d(np.asarray(xR_y, dtype=np.float64)) + status_x = np.atleast_2d(np.asarray(status_x, dtype=np.float64)) + status_y = np.atleast_2d(np.asarray(status_y, dtype=np.float64)) + statusL_x = np.atleast_2d(np.asarray(statusL_x, dtype=np.float64)) + statusR_x = np.atleast_2d(np.asarray(statusR_x, dtype=np.float64)) + statusL_y = np.atleast_2d(np.asarray(statusL_y, dtype=np.float64)) + statusR_y = np.atleast_2d(np.asarray(statusR_y, dtype=np.float64)) + + if kx is None or len(kx) == 0: + kx = np.zeros(32) + kx[27] = 1.0 + ky = np.zeros(32) + ky[27] = 1.0 + else: + kx = np.asarray(kx, dtype=np.float64).flatten() + ky = np.asarray(ky, dtype=np.float64).flatten() + if len(kx) == 40: + kx = kx[:32] + ky = ky[:32] + + if gamma_x is None: + gamma_x = 90.0 + gamma_y = 90.0 + + VALID = 0 + LOW_LEVEL_ERR = 1 + XL00_DETECT_ERR = 2 + XR00_DETECT_ERR = 3 + XL11_DETECT_ERR = 4 + XR11_DETECT_ERR = 5 + NO_CABLE_ERR = 6 + LOW_RADIATION_ERR = 9 + DOUBLE_ERR = 10 + OUTER_DM_ERR = 14 + CORE_DM_ERR = 15 + OSC_ERR = 16 + ISC_ERR = 17 + SCANNER_DATA_ERR = 18 + CONF_DATA_ERR = 19 + CHKSPEED_ERR = 24 + WINDOW_DIRTY_ERR = 25 + LAYER_NOT_REQUESTED = 45 + CAM_SYSERR = 251 + GV_OFF_SYSERR = 252 + HV_OFF_SYSERR = 253 + + globalfailure = np.array([LOW_LEVEL_ERR, XL00_DETECT_ERR, XR00_DETECT_ERR, + XL11_DETECT_ERR, XR11_DETECT_ERR, NO_CABLE_ERR, + LOW_RADIATION_ERR, DOUBLE_ERR, SCANNER_DATA_ERR, + CONF_DATA_ERR, CHKSPEED_ERR, WINDOW_DIRTY_ERR, + CAM_SYSERR, GV_OFF_SYSERR, HV_OFF_SYSERR] + list(range(180, 221))) + + dmOut = np.zeros((3, 2)) + dmOut[1, :] = 255 + oscL = np.zeros((3, 2)) + oscR = np.zeros((3, 2)) + oscL[1, :] = 255 + oscR[1, :] = 255 + isoL = np.zeros((3, 2)) + isoR = np.zeros((3, 2)) + isoL[1, :] = 255 + isoR[1, :] = 255 + iscL = np.zeros((3, 2)) + iscR = np.zeros((3, 2)) + iscL[1, :] = 255 + iscR[1, :] = 255 + coreDm = np.zeros((3, 2)) + coreDm[1, :] = 255 + wthL = np.zeros((3, 2)) + wthR = np.zeros((3, 2)) + wthL[1, :] = 255 + wthR[1, :] = 255 + xk = np.zeros((3, 4)) + yk = np.zeros((3, 4)) + xk[1, :] = 255 + yk[1, :] = 255 + + gamma_x = gamma_x * np.pi / 180.0 + gamma_y = gamma_y * np.pi / 180.0 + + beta_x = np.zeros(4) + beta_y = np.zeros(4) + tgBeta_x = np.zeros(4) + tgBeta_y = np.zeros(4) + rL_x = np.zeros(4) + rL_y = np.zeros(4) + rR_x = np.zeros(4) + rR_y = np.zeros(4) + + for n in range(4): + if mode == 1: + denomLx = x0_x - xCCD_x - xL_x[0, n] * np.cos(gamma_x) + denomRx = x0_x - xCCD_x - xR_x[0, n] * np.cos(gamma_x) + if abs(denomLx) < 1e-15: + denomLx = 1e-15 + if abs(denomRx) < 1e-15: + denomRx = 1e-15 + beta_x[n] = 0.5 * ( + np.arctan((xL_x[0, n] * np.sin(gamma_x) - y0_x + yCCD_x) / denomLx) + + np.arctan((xR_x[0, n] * np.sin(gamma_x) - y0_x + yCCD_x) / denomRx) + ) + tgBeta_x[n] = np.tan(beta_x[n]) + + denomLy = y0_y - yCCD_y - xL_y[0, n] * np.cos(gamma_y) + denomRy = y0_y - yCCD_y - xR_y[0, n] * np.cos(gamma_y) + if abs(denomLy) < 1e-15: + denomLy = 1e-15 + if abs(denomRy) < 1e-15: + denomRy = 1e-15 + beta_y[n] = 0.5 * ( + np.arctan((xL_y[0, n] * np.sin(gamma_y) - x0_y + xCCD_y) / denomLy) + + np.arctan((xR_y[0, n] * np.sin(gamma_y) - x0_y + xCCD_y) / denomRy) + ) + tgBeta_y[n] = np.tan(beta_y[n]) + else: + tgBeta_x[n] = ((xL_x[0, n] + xR_x[0, n]) / 2.0 - y0_x + yCCD_x) / (x0_x - xCCD_x) + beta_x[n] = tgBeta_x[n] + tgBeta_y[n] = ((xL_y[0, n] + xR_y[0, n]) / 2.0 - x0_y + xCCD_y) / (y0_y - yCCD_y) + beta_y[n] = tgBeta_y[n] + + if abs(tgBeta_y[n]) > 1e-15: + xk[0, n] = (tgBeta_x[n] * x0_x + y0_x - 1.0 / tgBeta_y[n] * x0_y - y0_y) / (tgBeta_x[n] - 1.0 / tgBeta_y[n]) + else: + xk[0, n] = x0_y + yk[0, n] = -(xk[0, n] - x0_x) * tgBeta_x[n] + y0_x + + xk[0, n] = xk[0, n] + delta_xk + yk[0, n] = yk[0, n] + delta_yk + + if (not statusL_x[0, n]) and (not statusR_x[0, n]) and (not statusL_y[0, n]) and (not statusR_y[0, n]): + xk[1, n] = VALID + yk[1, n] = VALID + + if statusL_x[0, 1] or statusR_x[0, 1] or statusL_y[0, 1] or statusR_y[0, 1]: + xk[0, 1] = xk[0, 0] + yk[0, 1] = yk[0, 0] + beta_x[1] = beta_x[0] + beta_y[1] = beta_y[0] + tgBeta_x[1] = tgBeta_x[0] + tgBeta_y[1] = tgBeta_y[0] + if statusL_x[0, 3] or statusR_x[0, 3] or statusL_y[0, 3] or statusR_y[0, 3]: + xk[0, 3] = xk[0, 0] + yk[0, 3] = yk[0, 0] + beta_x[3] = beta_x[0] + beta_y[3] = beta_y[0] + tgBeta_x[3] = tgBeta_x[0] + tgBeta_y[3] = tgBeta_y[0] + if statusL_x[0, 2] or statusR_x[0, 2] or statusL_y[0, 2] or statusR_y[0, 2]: + xk[0, 2] = xk[0, 3] + yk[0, 2] = yk[0, 3] + beta_x[2] = beta_x[3] + beta_y[2] = beta_y[3] + tgBeta_x[2] = tgBeta_x[3] + tgBeta_y[2] = tgBeta_y[3] + + for n in range(4): + ek_x = np.sqrt((x0_x - xk[0, n])**2 + (y0_x - yk[0, n])**2) + ek_y = np.sqrt((x0_y - xk[0, n])**2 + (y0_y - yk[0, n])**2) + + if mode == 1: + denomLx = x0_x - xCCD_x - xL_x[0, n] * np.cos(gamma_x) + denomRx = x0_x - xCCD_x - xR_x[0, n] * np.cos(gamma_x) + if abs(denomLx) < 1e-15: + denomLx = 1e-15 + if abs(denomRx) < 1e-15: + denomRx = 1e-15 + alphaL_x = np.arctan((xL_x[0, n] * np.sin(gamma_x) - y0_x + yCCD_x) / denomLx) - beta_x[n] + alphaR_x = np.arctan((xR_x[0, n] * np.sin(gamma_x) - y0_x + yCCD_x) / denomRx) - beta_x[n] + + denomLy = y0_y - yCCD_y - xL_y[0, n] * np.cos(gamma_y) + denomRy = y0_y - yCCD_y - xR_y[0, n] * np.cos(gamma_y) + if abs(denomLy) < 1e-15: + denomLy = 1e-15 + if abs(denomRy) < 1e-15: + denomRy = 1e-15 + alphaL_y = np.arctan((xL_y[0, n] * np.sin(gamma_y) - x0_y + xCCD_y) / denomLy) - beta_y[n] + alphaR_y = np.arctan((xR_y[0, n] * np.sin(gamma_y) - x0_y + xCCD_y) / denomRy) - beta_y[n] + else: + alphaL_x = ((xL_x[0, n] - y0_x + yCCD_x) / (x0_x - xCCD_x)) - tgBeta_x[n] + alphaR_x = ((xR_x[0, n] - y0_x + yCCD_x) / (x0_x - xCCD_x)) - tgBeta_x[n] + alphaL_y = ((xL_y[0, n] - x0_y + xCCD_y) / (y0_y - yCCD_y)) - tgBeta_y[n] + alphaR_y = ((xR_y[0, n] - x0_y + xCCD_y) / (y0_y - yCCD_y)) - tgBeta_y[n] + + if mode == 1: + rL_x[n] = abs(ek_x * np.sin(alphaL_x)) + rR_x[n] = abs(ek_x * np.sin(alphaR_x)) + rL_y[n] = abs(ek_y * np.sin(alphaL_y)) + rR_y[n] = abs(ek_y * np.sin(alphaR_y)) + else: + rL_x[n] = abs(ek_x * alphaL_x) + rR_x[n] = abs(ek_x * alphaR_x) + rL_y[n] = abs(ek_y * alphaL_y) + rR_y[n] = abs(ek_y * alphaR_y) + + if len(kx) == 30: + poly_terms = lambda xv, yv, rv: np.array([ + 1, xv, xv*yv, xv*yv*(2*rv), xv*yv*(2*rv)**2, + xv*yv**2, xv*yv**2*(2*rv), xv*yv**2*(2*rv)**2, + xv*(2*rv), xv*(2*rv)**2, xv**2, xv**2*yv, + xv**2*yv*(2*rv), xv**2*yv*(2*rv)**2, xv**2*yv**2, + xv**2*yv**2*(2*rv), xv**2*yv**2*(2*rv)**2, + xv**2*(2*rv), xv**2*(2*rv)**2, xv**3, yv, + yv*(2*rv), yv*(2*rv)**2, yv**2, yv**2*(2*rv), + yv**2*(2*rv)**2, yv**3, (2*rv), (2*rv)**2, (2*rv)**3 + ]) + rL_x[n] = 0.5 * np.dot(poly_terms(xk[0, n], yk[0, n], rL_x[n]), kx[:30]) + rR_x[n] = 0.5 * np.dot(poly_terms(xk[0, n], yk[0, n], rR_x[n]), kx[:30]) + rL_y[n] = 0.5 * np.dot(poly_terms(xk[0, n], yk[0, n], rL_y[n]), ky[:30]) + rR_y[n] = 0.5 * np.dot(poly_terms(xk[0, n], yk[0, n], rR_y[n]), ky[:30]) + elif len(kx) == 32: + poly_terms = lambda xv, yv, rv: np.array([ + 1, xv, xv*yv, xv*yv*(2*rv), xv*yv*(2*rv)**2, + xv*yv**2, xv*yv**2*(2*rv), xv*yv**2*(2*rv)**2, + xv*(2*rv), xv*(2*rv)**2, xv**2, xv**2*yv, + xv**2*yv*(2*rv), xv**2*yv*(2*rv)**2, xv**2*yv**2, + xv**2*yv**2*(2*rv), xv**2*yv**2*(2*rv)**2, + xv**2*(2*rv), xv**2*(2*rv)**2, xv**3, yv, + yv*(2*rv), yv*(2*rv)**2, yv**2, yv**2*(2*rv), + yv**2*(2*rv)**2, yv**3, (2*rv), (2*rv)**2, (2*rv)**3, + xv**4, yv**4 + ]) + rL_x[n] = 0.5 * np.dot(poly_terms(xk[0, n], yk[0, n], rL_x[n]), kx) + rR_x[n] = 0.5 * np.dot(poly_terms(xk[0, n], yk[0, n], rR_x[n]), kx) + rL_y[n] = 0.5 * np.dot(poly_terms(xk[0, n], yk[0, n], rL_y[n]), ky) + rR_y[n] = 0.5 * np.dot(poly_terms(xk[0, n], yk[0, n], rR_y[n]), ky) + + if (not statusL_x[0, 0]) and (not statusR_x[0, 0]) and (not statusL_y[0, 0]) and (not statusR_y[0, 0]): + dmOut[0, 0] = rL_x[0] + rR_x[0] + dmOut[0, 1] = rL_y[0] + rR_y[0] + dmOut[1, :] = VALID + + if not statusL_x[0, 1]: + oscL[0, 0] = rL_x[0] - rL_x[1] + (yk[0, 1] - yk[0, 0]) + oscL[1, 0] = VALID + else: + oscL[1, 0] = statusL_x[0, 1] + if not statusR_x[0, 1]: + oscR[0, 0] = rR_x[0] - rR_x[1] - (yk[0, 1] - yk[0, 0]) + oscR[1, 0] = VALID + else: + oscR[1, 0] = statusR_x[0, 1] + if not statusL_y[0, 1]: + oscL[0, 1] = rL_y[0] - rL_y[1] + (xk[0, 1] - xk[0, 0]) + oscL[1, 1] = VALID + else: + oscL[1, 1] = statusL_y[0, 1] + if not statusR_y[0, 1]: + oscR[0, 1] = rR_y[0] - rR_y[1] - (xk[0, 1] - xk[0, 0]) + oscR[1, 1] = VALID + else: + oscR[1, 1] = statusR_y[0, 1] + + if not statusL_x[0, 3]: + wthL[0, 0] = rL_x[0] - rL_x[3] + (yk[0, 3] - yk[0, 0]) + wthL[1, 0] = VALID + else: + wthL[1, 0] = statusL_x[0, 3] + if not statusR_x[0, 3]: + wthR[0, 0] = rR_x[0] - rR_x[3] - (yk[0, 3] - yk[0, 0]) + wthR[1, 0] = VALID + else: + wthR[1, 0] = statusR_x[0, 3] + if not statusL_y[0, 3]: + wthL[0, 1] = rL_y[0] - rL_y[3] + (xk[0, 3] - xk[0, 0]) + wthL[1, 1] = VALID + else: + wthL[1, 1] = statusL_y[0, 3] + if not statusR_y[0, 3]: + wthR[0, 1] = rR_y[0] - rR_y[3] - (xk[0, 3] - xk[0, 0]) + wthR[1, 1] = VALID + else: + wthR[1, 1] = statusR_y[0, 3] + else: + if np.any(np.isin(status_x[0, 0], globalfailure)): + dmOut[1, 0] = status_x[0, 0] + oscL[1, 0] = status_x[0, 0] + oscR[1, 0] = status_x[0, 0] + coreDm[1, 0] = status_x[0, 0] + wthL[1, 0] = status_x[0, 0] + wthR[1, 0] = status_x[0, 0] + iscL[1, 0] = status_x[0, 0] + iscR[1, 0] = status_x[0, 0] + isoL[1, 0] = status_x[0, 0] + isoR[1, 0] = status_x[0, 0] + else: + if statusL_x[0, 0]: + dmOut[1, 0] = statusL_x[0, 0] + elif statusR_x[0, 0]: + dmOut[1, 0] = statusR_x[0, 0] + else: + dmOut[1, 0] = OUTER_DM_ERR + if statusL_x[0, 1]: + oscL[1, 0] = statusL_x[0, 1] + else: + oscL[1, 0] = OUTER_DM_ERR + if statusR_x[0, 1]: + oscR[1, 0] = statusR_x[0, 1] + else: + oscR[1, 0] = OUTER_DM_ERR + if statusL_x[0, 2]: + iscL[1, 0] = statusL_x[0, 2] + else: + iscL[1, 0] = OUTER_DM_ERR + if statusR_x[0, 2]: + iscR[1, 0] = statusR_x[0, 2] + else: + iscR[1, 0] = OUTER_DM_ERR + if statusL_x[0, 3]: + coreDm[1, 0] = statusL_x[0, 3] + elif statusR_x[0, 3]: + coreDm[1, 0] = statusR_x[0, 3] + else: + coreDm[1, 0] = OUTER_DM_ERR + wthL[1, 0] = OUTER_DM_ERR + wthR[1, 0] = OUTER_DM_ERR + isoL[1, 0] = OUTER_DM_ERR + isoR[1, 0] = OUTER_DM_ERR + + if np.any(np.isin(status_y[0, 0], globalfailure)): + dmOut[1, 1] = status_y[0, 0] + oscL[1, 1] = status_y[0, 0] + oscR[1, 1] = status_y[0, 0] + coreDm[1, 1] = status_y[0, 0] + wthL[1, 1] = status_y[0, 0] + wthR[1, 1] = status_y[0, 0] + iscL[1, 1] = status_y[0, 0] + iscR[1, 1] = status_y[0, 0] + isoL[1, 1] = status_y[0, 0] + isoR[1, 1] = status_y[0, 0] + else: + if statusL_y[0, 0]: + dmOut[1, 1] = statusL_y[0, 0] + elif statusR_y[0, 0]: + dmOut[1, 1] = statusR_y[0, 0] + else: + dmOut[1, 1] = OUTER_DM_ERR + if statusL_y[0, 1]: + oscL[1, 1] = statusL_y[0, 1] + else: + oscL[1, 1] = OUTER_DM_ERR + if statusR_y[0, 1]: + oscR[1, 1] = statusR_y[0, 1] + else: + oscR[1, 1] = OUTER_DM_ERR + if statusL_y[0, 2]: + iscL[1, 1] = statusL_y[0, 2] + else: + iscL[1, 1] = OUTER_DM_ERR + if statusR_y[0, 2]: + iscR[1, 1] = statusR_y[0, 2] + else: + iscR[1, 1] = OUTER_DM_ERR + if statusL_y[0, 3]: + coreDm[1, 1] = statusL_y[0, 3] + elif statusR_y[0, 3]: + coreDm[1, 1] = statusR_y[0, 3] + else: + coreDm[1, 1] = OUTER_DM_ERR + wthL[1, 1] = OUTER_DM_ERR + wthR[1, 1] = OUTER_DM_ERR + iscL[1, 1] = OUTER_DM_ERR + iscR[1, 1] = OUTER_DM_ERR + isoL[1, 1] = OUTER_DM_ERR + isoR[1, 1] = OUTER_DM_ERR + + if ((not statusL_x[0, 3] and not statusR_x[0, 3] and not statusL_y[0, 3] and not statusR_y[0, 3]) or + (not statusL_x[0, 0] and not statusR_x[0, 0] and not statusL_y[0, 0] and not statusR_y[0, 0])): + if not statusL_x[0, 3] and not statusR_x[0, 3]: + coreDm[0, 0] = rL_x[3] + rR_x[3] + coreDm[1, 0] = VALID + elif statusL_x[0, 3]: + coreDm[1, 0] = statusL_x[0, 3] + elif statusR_x[0, 3]: + coreDm[1, 0] = statusR_x[0, 3] + + if not statusL_y[0, 3] and not statusR_y[0, 3]: + coreDm[0, 1] = rL_y[3] + rR_y[3] + coreDm[1, 1] = VALID + elif statusL_y[0, 3]: + coreDm[1, 1] = statusL_y[0, 3] + elif statusR_y[0, 3]: + coreDm[1, 1] = statusR_y[0, 3] + + if not statusL_x[0, 2] and not statusL_x[0, 3]: + iscL[0, 0] = rL_x[2] - rL_x[3] + (yk[0, 3] - yk[0, 2]) + iscL[1, 0] = VALID + else: + if statusL_x[0, 2]: + iscL[1, 0] = statusL_x[0, 2] + else: + iscL[1, 0] = statusL_x[0, 3] + + if not statusR_x[0, 2] and not statusR_x[0, 3]: + iscR[0, 0] = rR_x[2] - rR_x[3] - (yk[0, 3] - yk[0, 2]) + iscR[1, 0] = VALID + else: + if statusR_x[0, 2]: + iscR[1, 0] = statusR_x[0, 2] + else: + iscR[1, 0] = statusR_x[0, 3] + + if not statusL_y[0, 2] and not statusL_y[0, 3]: + iscL[0, 1] = rL_y[2] - rL_y[3] + (xk[0, 3] - xk[0, 2]) + iscL[1, 1] = VALID + else: + if statusL_y[0, 2]: + iscL[1, 1] = statusL_y[0, 2] + else: + iscL[1, 1] = statusL_y[0, 3] + + if not statusR_y[0, 2] and not statusR_y[0, 3]: + iscR[0, 1] = rR_y[2] - rR_y[3] - (xk[0, 3] - xk[0, 2]) + iscR[1, 1] = VALID + else: + if statusR_y[0, 2]: + iscR[1, 1] = statusR_y[0, 2] + else: + iscR[1, 1] = statusR_y[0, 3] + + if (not wthL[1, 0]) and ((not oscL[1, 0]) or oscL[1, 0] == LAYER_NOT_REQUESTED) and ((not iscL[1, 0]) or iscL[1, 0] == LAYER_NOT_REQUESTED): + isoL[0, 0] = wthL[0, 0] - oscL[0, 0] - iscL[0, 0] + isoL[1, 0] = VALID + elif wthL[1, 0]: + isoL[1, 0] = wthL[1, 0] + elif oscL[1, 0]: + isoL[1, 0] = oscL[1, 0] + elif iscL[1, 0]: + isoL[1, 0] = iscL[1, 0] + + if (not wthL[1, 1]) and ((not oscL[1, 1]) or oscL[1, 1] == LAYER_NOT_REQUESTED) and ((not iscL[1, 1]) or iscL[1, 1] == LAYER_NOT_REQUESTED): + isoL[0, 1] = wthL[0, 1] - oscL[0, 1] - iscL[0, 1] + isoL[1, 1] = VALID + elif wthL[1, 1]: + isoL[1, 1] = wthL[1, 1] + elif oscL[1, 1]: + isoL[1, 1] = oscL[1, 1] + elif iscL[1, 1]: + isoL[1, 1] = iscL[1, 1] + + if (not wthR[1, 0]) and ((not oscR[1, 0]) or oscR[1, 0] == LAYER_NOT_REQUESTED) and ((not iscR[1, 0]) or iscR[1, 0] == LAYER_NOT_REQUESTED): + isoR[0, 0] = wthR[0, 0] - oscR[0, 0] - iscR[0, 0] + isoR[1, 0] = VALID + elif wthR[1, 0]: + isoR[1, 0] = wthR[1, 0] + elif oscR[1, 0]: + isoR[1, 0] = oscR[1, 0] + elif iscR[1, 0]: + isoR[1, 0] = iscR[1, 0] + + if (not wthR[1, 1]) and ((not oscR[1, 1]) or oscR[1, 1] == LAYER_NOT_REQUESTED) and ((not iscR[1, 1]) or iscR[1, 1] == LAYER_NOT_REQUESTED): + isoR[0, 1] = wthR[0, 1] - oscR[0, 1] - iscR[0, 1] + isoR[1, 1] = wthR[1, 1] + elif wthR[1, 1]: + isoR[1, 1] = wthR[1, 1] + elif oscR[1, 1]: + isoR[1, 1] = oscR[1, 1] + elif iscR[1, 1]: + isoR[1, 1] = iscR[1, 1] + + return dmOut, oscL, oscR, isoL, isoR, iscL, iscR, coreDm, wthL, wthR, xk, yk + + +def modify_cable_position(baseAngle, orientation, height): + delta_xk = 0.0 + delta_yk = 0.0 + + if baseAngle == 0: + slope = 0.0 + orientation = 0 + elif baseAngle == 1: + slope = 0.43 + elif baseAngle == 2: + slope = 0.35 + elif baseAngle == 3: + slope = 0.37 + elif baseAngle == 4: + slope = 0.225 + else: + slope = 0.0 + + a = slope * height + + if orientation == 0: + delta_xk = 0.0 + delta_yk = 0.0 + elif orientation == 1: + delta_xk = 0.0 + delta_yk = (height / 2.0 - a) + elif orientation == 2: + delta_xk = -(height / 2.0 - a) + delta_yk = 0.0 + elif orientation == 3: + delta_xk = 0.0 + delta_yk = -(height / 2.0 - a) + elif orientation == 4: + delta_xk = (height / 2.0 - a) + delta_yk = 0.0 + else: + delta_xk = 0.0 + delta_yk = 0.0 + + return delta_xk, delta_yk + + +def axis_result(xL_x, xR_x, status_x, statusL_x, statusR_x, mode, layeruse): + xL_x = np.atleast_2d(np.asarray(xL_x, dtype=np.float64)) + xR_x = np.atleast_2d(np.asarray(xR_x, dtype=np.float64)) + status_x = np.atleast_2d(np.asarray(status_x, dtype=np.float64)) + statusL_x = np.atleast_2d(np.asarray(statusL_x, dtype=np.float64)) + statusR_x = np.atleast_2d(np.asarray(statusR_x, dtype=np.float64)) + # Ensure at least 2 rows (row 0=error code, row 1=warning code) + if status_x.shape[0] < 2: + status_x = np.vstack([status_x, np.zeros((2 - status_x.shape[0], status_x.shape[1]))]) + if statusL_x.shape[0] < 2: + statusL_x = np.vstack([statusL_x, np.zeros((2 - statusL_x.shape[0], statusL_x.shape[1]))]) + if statusR_x.shape[0] < 2: + statusR_x = np.vstack([statusR_x, np.zeros((2 - statusR_x.shape[0], statusR_x.shape[1]))]) + layeruse = np.asarray(layeruse, dtype=np.float64).ravel() + + VALID = 0 + LOW_LEVEL_ERR = 1 + XL00_DETECT_ERR = 2 + XR00_DETECT_ERR = 3 + XL11_DETECT_ERR = 4 + XR11_DETECT_ERR = 5 + NO_CABLE_ERR = 6 + LOW_RADIATION_ERR = 9 + DOUBLE_ERR = 10 + OUTER_DM_ERR = 14 + CORE_DM_ERR = 15 + OSC_ERR = 16 + ISC_ERR = 17 + SCANNER_DATA_ERR = 18 + CONF_DATA_ERR = 19 + CHKSPEED_ERR = 24 + WINDOW_DIRTY_ERR = 25 + LAYER_NOT_REQUESTED = 45 + RIFFLE_MATCH_CONFLICT = 90 + NO_SCAN_DATA_ERR = 240 + SCANNER_1_TOO_COLD = 241 + SCANNER_2_TOO_COLD = 242 + SCANNER_1_TOO_HOT = 243 + SCANNER_2_TOO_HOT = 244 + CAM_SYSERR = 251 + GV_OFF_SYSERR = 252 + HV_OFF_SYSERR = 253 + + globalfailure = np.array([ + LOW_LEVEL_ERR, XL00_DETECT_ERR, XR00_DETECT_ERR, + XL11_DETECT_ERR, XR11_DETECT_ERR, NO_CABLE_ERR, + LOW_RADIATION_ERR, DOUBLE_ERR, SCANNER_DATA_ERR, + CONF_DATA_ERR, CHKSPEED_ERR, WINDOW_DIRTY_ERR, + CAM_SYSERR, GV_OFF_SYSERR, HV_OFF_SYSERR, + NO_SCAN_DATA_ERR, SCANNER_1_TOO_COLD, SCANNER_2_TOO_COLD, + SCANNER_1_TOO_HOT, SCANNER_2_TOO_HOT + ] + list(range(180, 221)) + [RIFFLE_MATCH_CONFLICT]) + + dmOut = np.zeros((3, 1)) + dmOut[1, 0] = 255 + oscL = np.zeros((3, 1)) + oscL[1, 0] = 255 + oscR = np.zeros((3, 1)) + oscR[1, 0] = 255 + isoL = np.zeros((3, 1)) + isoL[1, 0] = 255 + isoR = np.zeros((3, 1)) + isoR[1, 0] = 255 + iscL = np.zeros((3, 1)) + iscL[1, 0] = 255 + iscR = np.zeros((3, 1)) + iscR[1, 0] = 255 + coreDm = np.zeros((3, 1)) + coreDm[1, 0] = 255 + wthL = np.zeros((3, 1)) + wthL[1, 0] = 255 + wthR = np.zeros((3, 1)) + wthR[1, 0] = 255 + xk = np.zeros((3, 4)) + xk[1, :] = 255 + rL_x = np.zeros(4) + rR_x = np.zeros(4) + + for n in range(4): + xk[0, n] = (xL_x[0, n] + xR_x[0, n]) / 2.0 + if (not statusL_x[0, n]) and (not statusR_x[0, n]): + xk[1, n] = VALID + + if statusL_x[0, 1] or statusR_x[0, 1]: + xk[0, 1] = xk[0, 0] + if statusL_x[0, 3] or statusR_x[0, 3]: + xk[0, 3] = xk[0, 0] + if statusL_x[0, 2] or statusR_x[0, 2]: + xk[0, 2] = xk[0, 3] + + for n in range(4): + rL_x[n] = abs(xL_x[0, n] - xk[0, n]) + rR_x[n] = abs(xR_x[0, n] - xk[0, n]) + + if (not statusL_x[0, 0]) and (not statusR_x[0, 0]): + dmOut[0, 0] = rL_x[0] + rR_x[0] + dmOut[1, 0] = VALID + + if not statusL_x[0, 1]: + oscL[0, 0] = rL_x[0] - rL_x[1] + (xk[0, 1] - xk[0, 0]) + oscL[1, 0] = VALID + else: + oscL[1, 0] = statusL_x[0, 1] + + if not statusR_x[0, 1]: + oscR[0, 0] = rR_x[0] - rR_x[1] - (xk[0, 1] - xk[0, 0]) + oscR[1, 0] = VALID + else: + oscR[1, 0] = statusR_x[0, 1] + + if not statusL_x[0, 3]: + wthL[0, 0] = rL_x[0] - rL_x[3] + (xk[0, 3] - xk[0, 0]) + wthL[1, 0] = VALID + else: + wthL[1, 0] = statusL_x[0, 3] + if not statusR_x[0, 3]: + wthR[0, 0] = rR_x[0] - rR_x[3] - (xk[0, 3] - xk[0, 0]) + wthR[1, 0] = VALID + else: + wthR[1, 0] = statusR_x[0, 3] + + else: + if np.any(np.isin(status_x[0, 0], globalfailure)): + dmOut[1, 0] = status_x[0, 0] + oscL[1, 0] = status_x[0, 0] + oscR[1, 0] = status_x[0, 0] + coreDm[1, 0] = status_x[0, 0] + wthL[1, 0] = status_x[0, 0] + wthR[1, 0] = status_x[0, 0] + iscL[1, 0] = status_x[0, 0] + iscR[1, 0] = status_x[0, 0] + isoL[1, 0] = status_x[0, 0] + isoR[1, 0] = status_x[0, 0] + else: + if statusL_x[0, 0]: + dmOut[1, 0] = statusL_x[0, 0] + elif statusR_x[0, 0]: + dmOut[1, 0] = statusR_x[0, 0] + else: + dmOut[1, 0] = OUTER_DM_ERR + if statusL_x[0, 1]: + oscL[1, 0] = statusL_x[0, 1] + else: + oscL[1, 0] = OUTER_DM_ERR + if statusR_x[0, 1]: + oscR[1, 0] = statusR_x[0, 1] + else: + oscR[1, 0] = OUTER_DM_ERR + if statusL_x[0, 2]: + iscL[1, 0] = statusL_x[0, 2] + else: + iscL[1, 0] = OUTER_DM_ERR + if statusR_x[0, 2]: + iscR[1, 0] = statusR_x[0, 2] + else: + iscR[1, 0] = OUTER_DM_ERR + if statusL_x[0, 3]: + coreDm[1, 0] = statusL_x[0, 3] + elif statusR_x[0, 3]: + coreDm[1, 0] = statusR_x[0, 3] + else: + coreDm[1, 0] = OUTER_DM_ERR + wthL[1, 0] = OUTER_DM_ERR + wthR[1, 0] = OUTER_DM_ERR + isoL[1, 0] = OUTER_DM_ERR + isoR[1, 0] = OUTER_DM_ERR + + if ((not statusL_x[0, 3] and not statusR_x[0, 3]) or + (not statusL_x[0, 0] and not statusR_x[0, 0])): + if not statusL_x[0, 3] and not statusR_x[0, 3]: + coreDm[0, 0] = rL_x[3] + rR_x[3] + coreDm[1, 0] = VALID + elif statusL_x[0, 3]: + coreDm[1, 0] = statusL_x[0, 3] + elif statusR_x[0, 3]: + coreDm[1, 0] = statusR_x[0, 3] + + if not statusL_x[0, 2] and not statusL_x[0, 3]: + iscL[0, 0] = rL_x[2] - rL_x[3] + (xk[0, 3] - xk[0, 2]) + iscL[1, 0] = VALID + else: + if statusL_x[0, 2]: + iscL[1, 0] = statusL_x[0, 2] + else: + iscL[1, 0] = statusL_x[0, 3] + if not statusR_x[0, 2] and not statusR_x[0, 3]: + iscR[0, 0] = rR_x[2] - rR_x[3] - (xk[0, 3] - xk[0, 2]) + iscR[1, 0] = VALID + else: + if statusR_x[0, 2]: + iscR[1, 0] = statusR_x[0, 2] + else: + iscR[1, 0] = statusR_x[0, 3] + + if (not wthL[1, 0] and ((not oscL[1, 0]) or oscL[1, 0] == LAYER_NOT_REQUESTED) + and ((not iscL[1, 0]) or iscL[1, 0] == LAYER_NOT_REQUESTED)): + isoL[0, 0] = wthL[0, 0] - oscL[0, 0] - iscL[0, 0] + isoL[1, 0] = VALID + elif wthL[1, 0]: + isoL[1, 0] = wthL[1, 0] + elif oscL[1, 0] and (layeruse[0] == 1): + isoL[1, 0] = oscL[1, 0] + elif iscL[1, 0] and (layeruse[2] == 1): + isoL[1, 0] = iscL[1, 0] + if (not wthR[1, 0] and ((not oscR[1, 0]) or oscR[1, 0] == LAYER_NOT_REQUESTED) + and ((not iscR[1, 0]) or iscR[1, 0] == LAYER_NOT_REQUESTED)): + isoR[0, 0] = wthR[0, 0] - oscR[0, 0] - iscR[0, 0] + isoR[1, 0] = VALID + elif wthR[1, 0]: + isoR[1, 0] = wthR[1, 0] + elif oscR[1, 0] and (layeruse[0] == 1): + isoR[1, 0] = oscR[1, 0] + elif iscR[1, 0] and (layeruse[2] == 1): + isoR[1, 0] = iscR[1, 0] + + warnvek = np.array([statusL_x[1, 0], statusR_x[1, 0], 0, 0]) + warnall, warnx, dummy = warnlogic(warnvek) + dmOut[2, 0] = warnx + + warncore = np.zeros(1) + warnvek = np.array([statusL_x[1, 3], statusR_x[1, 3], 0, 0]) + warnall, warncore[0], dummy = warnlogic(warnvek) + + warnwth = np.zeros(2) + warnvek = np.array([statusL_x[1, 0], statusL_x[1, 3], statusR_x[1, 0], statusR_x[1, 3]]) + warnall, warnwth[0], warnwth[1] = warnlogic(warnvek) + + warnosc = np.zeros(2) + warnvek = np.array([statusL_x[1, 0], statusL_x[1, 1], statusR_x[1, 0], statusR_x[1, 1]]) + warnall, warnosc[0], warnosc[1] = warnlogic(warnvek) + + warnisc = np.zeros(2) + warnvek = np.array([statusL_x[1, 2], statusL_x[1, 3], statusR_x[1, 2], statusR_x[1, 3]]) + warnall, warnisc[0], warnisc[1] = warnlogic(warnvek) + + warniso = np.zeros(2) + warnvek = np.array([warnwth[0], warnosc[0], warnisc[0], warnwth[1], warnosc[1], warnisc[1]]) + warnall, warniso[0], warniso[1] = warnlogic(warnvek) + + if np.array_equal(layeruse, np.array([0, 0, 0])): + wthL[0, :] = 0 + wthR[0, :] = 0 + wthL[1, :] = LAYER_NOT_REQUESTED + wthR[1, :] = LAYER_NOT_REQUESTED + oscL[0, :] = 0 + oscR[0, :] = 0 + oscL[1, :] = LAYER_NOT_REQUESTED + oscR[1, :] = LAYER_NOT_REQUESTED + isoL[0, :] = 0 + isoR[0, :] = 0 + isoL[1, :] = LAYER_NOT_REQUESTED + isoR[1, :] = LAYER_NOT_REQUESTED + iscL[0, :] = 0 + iscR[0, :] = 0 + iscL[1, :] = LAYER_NOT_REQUESTED + iscR[1, :] = LAYER_NOT_REQUESTED + coreDm[0, :] = 0 + coreDm[1, :] = LAYER_NOT_REQUESTED + elif np.array_equal(layeruse, np.array([0, 0, 1])): + wthL[2, :] = warnwth[[0, 1]] + wthR[2, :] = warnwth[1] + oscL[0, :] = 0 + oscR[0, :] = 0 + oscL[1, :] = LAYER_NOT_REQUESTED + oscR[1, :] = LAYER_NOT_REQUESTED + isoL[0, :] = 0 + isoR[0, :] = 0 + isoL[1, :] = LAYER_NOT_REQUESTED + isoR[1, :] = LAYER_NOT_REQUESTED + iscL[2, :] = warnisc[0] + iscR[2, :] = warnisc[1] + coreDm[2, :] = warncore + elif np.array_equal(layeruse, np.array([0, 1, 0])): + wthL[2, :] = warnwth[0] + wthR[2, :] = warnwth[1] + oscL[0, :] = 0 + oscR[0, :] = 0 + oscL[1, :] = LAYER_NOT_REQUESTED + oscR[1, :] = LAYER_NOT_REQUESTED + isoL[2, :] = warniso[0] + isoR[2, :] = warniso[1] + iscL[0, :] = 0 + iscR[0, :] = 0 + iscL[1, :] = LAYER_NOT_REQUESTED + iscR[1, :] = LAYER_NOT_REQUESTED + coreDm[2, :] = warncore + elif np.array_equal(layeruse, np.array([0, 1, 1])): + wthL[2, :] = warnwth[0] + wthR[2, :] = warnwth[1] + oscL[0, :] = 0 + oscR[0, :] = 0 + oscL[1, :] = LAYER_NOT_REQUESTED + oscR[1, :] = LAYER_NOT_REQUESTED + isoL[2, :] = warniso[0] + isoR[2, :] = warniso[1] + iscL[2, :] = warnisc[0] + iscR[2, :] = warnisc[1] + coreDm[2, :] = warncore + elif np.array_equal(layeruse, np.array([1, 0, 0])): + wthL[2, :] = warnwth[0] + wthR[2, :] = warnwth[1] + oscL[2, :] = warnosc[0] + oscR[2, :] = warnosc[1] + isoL[0, :] = 0 + isoR[0, :] = 0 + isoL[1, :] = LAYER_NOT_REQUESTED + isoR[1, :] = LAYER_NOT_REQUESTED + iscL[0, :] = 0 + iscR[0, :] = 0 + iscL[1, :] = LAYER_NOT_REQUESTED + iscR[1, :] = LAYER_NOT_REQUESTED + coreDm[2, :] = warncore + elif np.array_equal(layeruse, np.array([1, 0, 1])): + wthL[2, :] = warnwth[0] + wthR[2, :] = warnwth[1] + oscL[2, :] = warnosc[0] + oscR[2, :] = warnosc[1] + isoL[0, :] = 0 + isoR[0, :] = 0 + isoL[1, :] = LAYER_NOT_REQUESTED + isoR[1, :] = LAYER_NOT_REQUESTED + iscL[2, :] = warnisc[0] + iscR[2, :] = warnisc[1] + coreDm[2, :] = warncore + elif np.array_equal(layeruse, np.array([1, 1, 0])): + wthL[2, :] = warnwth[0] + wthR[2, :] = warnwth[1] + oscL[2, :] = warnosc[0] + oscR[2, :] = warnosc[1] + isoL[2, :] = warniso[0] + isoR[2, :] = warniso[1] + iscL[0, :] = 0 + iscR[0, :] = 0 + iscL[1, :] = LAYER_NOT_REQUESTED + iscR[1, :] = LAYER_NOT_REQUESTED + coreDm[2, :] = warncore + elif np.array_equal(layeruse, np.array([1, 1, 1])): + wthL[2, :] = warnwth[0] + wthR[2, :] = warnwth[1] + oscL[2, :] = warnosc[0] + oscR[2, :] = warnosc[1] + isoL[2, :] = warniso[0] + isoR[2, :] = warniso[1] + iscL[2, :] = warnisc[0] + iscR[2, :] = warnisc[1] + coreDm[2, :] = warncore + + return dmOut, oscL, oscR, isoL, isoR, iscL, iscR, coreDm, wthL, wthR, xk diff --git a/algorithm/layer_calibration_utils.py b/algorithm/layer_calibration_utils.py new file mode 100644 index 0000000..217804c --- /dev/null +++ b/algorithm/layer_calibration_utils.py @@ -0,0 +1,492 @@ +import numpy as np + + +def linint3(x, y, xi): + x = np.asarray(x, dtype=np.float64).ravel() + y = np.asarray(y, dtype=np.float64).ravel() + xi = np.asarray(xi, dtype=np.float64).ravel() + + if len(x) != len(y): + raise ValueError('length(x) must be == length(y)') + if len(x) < 2: + raise ValueError('length(x) must be >= 2') + + sort_idx = np.argsort(xi) + xi_sorted = xi[sort_idx] + + yi_sorted = np.zeros_like(xi_sorted) + N = len(x) + k = 0 + newk = True + + for i in range(len(xi_sorted)): + foundxi = False + while not foundxi: + if k < N - 1 and xi_sorted[i] >= x[k] and xi_sorted[i] < x[k + 1]: + if newk: + m = (y[k + 1] - y[k]) / (x[k + 1] - x[k]) + newk = False + yi_sorted[i] = m * (xi_sorted[i] - x[k]) + y[k] + foundxi = True + elif xi_sorted[i] <= x[0]: + m = (y[1] - y[0]) / (x[1] - x[0]) + yi_sorted[i] = m * (xi_sorted[i] - x[0]) + y[0] + foundxi = True + elif xi_sorted[i] >= x[N - 1]: + m = (y[N - 1] - y[N - 2]) / (x[N - 1] - x[N - 2]) + yi_sorted[i] = m * (xi_sorted[i] - x[N - 2]) + y[N - 2] + foundxi = True + else: + if k < N - 2: + k += 1 + newk = True + else: + raise ValueError('Linint3: No solution, because no pos. step xi') + + yi = np.zeros_like(xi) + yi[sort_idx] = yi_sorted + return yi + + +def lowlimit(x, bp): + x = np.asarray(x, dtype=np.float64) + y = x.copy() + yind = np.where(x < bp) + a2 = 1.0 / (2 * bp) + a0 = 0.5 * bp + y[yind] = a2 * x[yind] ** 2 + a0 + return y, a0 + + +def _layer_side_fit(results, side, layername, DefaultError=255.0): + lay_idx = {'osc': 0, 'iso': 1, 'isc': 2} + lay_names = ['osc', 'iso', 'isc'] + + wthvalid = (results[side]['wth'][2, :] == 0).astype(np.float64) + + other_valid = np.ones(3, dtype=object) + for li, ln in enumerate(lay_names): + if ln == layername: + this_valid = (results[side][ln][2, :] == 0).astype(np.float64) + else: + other_valid[li] = ((results[side][ln][2, :] == 0) | + (results[side][ln][2, :] == 45)).astype(np.float64) + + valid_new = wthvalid.copy() + for li, ln in enumerate(lay_names): + if ln == layername: + valid_new *= this_valid + else: + valid_new *= other_valid[li] + + other_sum = np.zeros_like(results[side]['wth'][1, :]) + for ln in lay_names: + if ln != layername: + other_sum += results[side][ln][1, :] + + results[side][layername][1, :] = ( + (results[side]['wth'][1, :] - other_sum) * valid_new + ) + + newfailed = this_valid & (1 - valid_new.astype(int)) + if np.any(newfailed): + results[side][layername][2, :] = DefaultError * newfailed.astype(np.float64) + + return results + + +def oscfit(results): + DefaultError = 255.0 + + for side in ['left', 'right']: + wthvalid = (results[side]['wth'][2, :] == 0).astype(np.float64) + oscvalid = (results[side]['osc'][2, :] == 0).astype(np.float64) + isovalid = ((results[side]['iso'][2, :] == 0) | + (results[side]['iso'][2, :] == 45)).astype(np.float64) + iscvalid = ((results[side]['isc'][2, :] == 0) | + (results[side]['isc'][2, :] == 45)).astype(np.float64) + oscvalid_new = wthvalid * oscvalid * isovalid * iscvalid + results[side]['osc'][1, :] = ( + (results[side]['wth'][1, :] - + results[side]['iso'][1, :] - + results[side]['isc'][1, :]) * oscvalid_new + ) + newfailed = oscvalid * (1 - oscvalid_new.astype(int)) + if np.any(newfailed): + results[side]['osc'][2, :] = DefaultError * newfailed.astype(np.float64) + + return results + + +def isofit(results): + DefaultError = 255.0 + + for side in ['left', 'right']: + wthvalid = (results[side]['wth'][2, :] == 0).astype(np.float64) + oscvalid = ((results[side]['osc'][2, :] == 0) | + (results[side]['osc'][2, :] == 45)).astype(np.float64) + iscvalid = ((results[side]['isc'][2, :] == 0) | + (results[side]['isc'][2, :] == 45)).astype(np.float64) + isovalid = (results[side]['iso'][2, :] == 0).astype(np.float64) + isovalid_new = wthvalid * oscvalid * isovalid * iscvalid + results[side]['iso'][1, :] = ( + (results[side]['wth'][1, :] - + results[side]['osc'][1, :] - + results[side]['isc'][1, :]) * isovalid_new + ) + newfailed = isovalid * (1 - isovalid_new.astype(int)) + if np.any(newfailed): + results[side]['iso'][2, :] = DefaultError * newfailed.astype(np.float64) + + return results + + +def iscfit(results): + DefaultError = 255.0 + + for side in ['left', 'right']: + wthvalid = (results[side]['wth'][2, :] == 0).astype(np.float64) + oscvalid = ((results[side]['osc'][2, :] == 0) | + (results[side]['osc'][2, :] == 45)).astype(np.float64) + isovalid = ((results[side]['iso'][2, :] == 0) | + (results[side]['iso'][2, :] == 45)).astype(np.float64) + iscvalid = (results[side]['isc'][2, :] == 0).astype(np.float64) + iscvalid_new = wthvalid * oscvalid * isovalid * iscvalid + results[side]['isc'][1, :] = ( + (results[side]['wth'][1, :] - + results[side]['osc'][1, :] - + results[side]['iso'][1, :]) * iscvalid_new + ) + newfailed = iscvalid * (1 - iscvalid_new.astype(int)) + if np.any(newfailed): + results[side]['isc'][2, :] = DefaultError * newfailed.astype(np.float64) + + return results + + +def corefit(results): + DefaultError = 255.0 + + corevalid_new = ( + (results['dmOut'][2, :] == 0) & + (results['left']['wth'][2, :] == 0) & + (results['right']['wth'][2, :] == 0) + ).astype(np.float64) + + results['coreDm'][1, :] = ( + (results['dmOut'][1, :] - + results['left']['wth'][1, :] - + results['right']['wth'][1, :]) * corevalid_new + ) + + newfailed = (1 - results['coreDm'][2, :].astype(int)) & (1 - corevalid_new.astype(int)) + if np.any(newfailed): + errvekx = np.array([results['dmOut'][2, 0], + results['left']['wth'][2, 0], + results['right']['wth'][2, 0]]) + errveky = np.array([results['dmOut'][2, 1], + results['left']['wth'][2, 1], + results['right']['wth'][2, 1]]) + errindx = np.where(errvekx)[0] + errindy = np.where(errveky)[0] + errxy = np.zeros(2) + if len(errindx) > 0: + errxy[0] = errvekx[errindx[0]] + if len(errindy) > 0: + errxy[1] = errveky[errindy[0]] + results['coreDm'][2, :] = errxy * newfailed.astype(np.float64) + + return results + + +def _calib_side(results, results_out, csector, layername, calib_key): + act_key = f'{calib_key}act' + nom_key = f'{calib_key}nom' + + if act_key in csector and len(np.atleast_1d(csector[act_key])) > 0: + for side in ['left', 'right']: + val_in = np.concatenate([ + results[side][layername][1, 0:2].ravel(), + results['right' if side == 'left' else 'left'][layername][1, 0:2].ravel() + ]) if side == 'left' else None + + if side == 'left': + val_in_left = np.concatenate([ + results['left'][layername][1, 0:2].ravel(), + results['right'][layername][1, 0:2].ravel() + ]) + try: + val_out = linint3(csector[act_key], csector[nom_key], val_in_left) + results_out['left'][layername][1, 0:2] = val_out[0:2] + results_out['right'][layername][1, 0:2] = val_out[2:4] + except Exception: + pass + return results_out + + +def osc_calib(results, results_out, csector): + if 'lay1act' in csector and len(np.atleast_1d(csector['lay1act'])) > 0: + val_in = np.concatenate([ + results['left']['osc'][1, 0:2].ravel(), + results['right']['osc'][1, 0:2].ravel() + ]) + try: + val_out = linint3(csector['lay1act'], csector['lay1nom'], val_in) + results_out['left']['osc'][1, 0:2] = val_out[0:2] + results_out['right']['osc'][1, 0:2] = val_out[2:4] + except Exception: + pass + return results_out + + +def iso_calib(results, results_out, csector): + if 'lay2act' in csector and len(np.atleast_1d(csector['lay2act'])) > 0: + val_in = np.concatenate([ + results['left']['iso'][1, 0:2].ravel(), + results['right']['iso'][1, 0:2].ravel() + ]) + try: + val_out = linint3(csector['lay2act'], csector['lay2nom'], val_in) + results_out['left']['iso'][1, 0:2] = val_out[0:2] + results_out['right']['iso'][1, 0:2] = val_out[2:4] + except Exception: + pass + return results_out + + +def isc_calib(results, results_out, csector): + if 'lay3act' in csector and len(np.atleast_1d(csector['lay3act'])) > 0: + val_in = np.concatenate([ + results['left']['isc'][1, 0:2].ravel(), + results['right']['isc'][1, 0:2].ravel() + ]) + try: + val_out = linint3(csector['lay3act'], csector['lay3nom'], val_in) + results_out['left']['isc'][1, 0:2] = val_out[0:2] + results_out['right']['isc'][1, 0:2] = val_out[2:4] + except Exception: + pass + return results_out + + +def layer_correct(results, calib_struct, layeruse, cableType): + import copy + results_out = copy.deepcopy(results) + + sectionindex = None + calibrate = False + + if (isinstance(calib_struct, dict) and + calib_struct.get('calibrationoff') is not None and + not calib_struct.get('calibrationoff', 1) and + not calib_struct.get('err', 1) and + len(np.atleast_1d(calib_struct.get('sectionType', []))) > 0): + + ii = 0 + run = True + NN = len(np.atleast_1d(calib_struct['sectionType'])) + sectionType = np.atleast_1d(calib_struct['sectionType']).ravel() + mincableType = np.atleast_1d(calib_struct['mincableType']).ravel() + maxcableType = np.atleast_1d(calib_struct['maxcableType']).ravel() + + while run: + if (mincableType[ii] <= cableType and + maxcableType[ii] >= cableType): + sectionindex = int(sectionType[ii]) + run = False + elif ii == NN - 1: + sectionindex = None + run = False + else: + ii += 1 + sectionindex = None + run = True + else: + sectionindex = None + + if sectionindex is not None: + sect = calib_struct.get('sect', {}).get(sectionindex, {}) + diam_err = calib_struct.get(f'sect.{sectionindex}.diam.err', 1) + wall_err = calib_struct.get(f'sect.{sectionindex}.wall.err', 1) + lay1_err = calib_struct.get(f'sect.{sectionindex}.lay1.err', 1) + lay2_err = calib_struct.get(f'sect.{sectionindex}.lay2.err', 1) + lay3_err = calib_struct.get(f'sect.{sectionindex}.lay3.err', 1) + + if not diam_err and not wall_err and not lay1_err and not lay2_err and not lay3_err: + calibrate = True + + if calibrate: + calidemand = np.zeros(3) + calidemand[0] = len(np.atleast_1d(calib_struct.get(f'sect.{sectionindex}.lay1.nom', []))) > 0 + calidemand[1] = len(np.atleast_1d(calib_struct.get(f'sect.{sectionindex}.lay2.nom', []))) > 0 + calidemand[2] = len(np.atleast_1d(calib_struct.get(f'sect.{sectionindex}.lay3.nom', []))) > 0 + + layeruse = np.asarray(layeruse).ravel() + + if np.all(layeruse == [0, 0, 0]): + ccase = 0 + elif np.all(layeruse == [0, 0, 1]): + ccase = 3 + elif np.all(layeruse == [0, 1, 0]): + ccase = 2 + elif np.all(layeruse == [0, 1, 1]): + if calidemand[1] == 0: + ccase = 5 + else: + ccase = 6 + elif np.all(layeruse == [1, 0, 0]): + ccase = 1 + elif np.all(layeruse == [1, 1, 0]): + if np.all(calidemand[0:2] == [0, 1]): + ccase = 4 + else: + ccase = 5 + elif np.all(layeruse == [1, 1, 1]): + if np.all(calidemand == [0, 1, 1]): + ccase = 4 + elif np.all(calidemand[1:3] == [1, 0]): + ccase = 6 + else: + ccase = 5 + else: + ccase = 0 + + csector = {} + for key in ['diam', 'wall', 'lay1', 'lay2', 'lay3']: + for suffix in ['act', 'nom', 'err']: + full_key = f'sect.{sectionindex}.{key}.{suffix}' + if full_key in calib_struct: + csector[f'{key}{suffix}'] = calib_struct[full_key] + + diam_nom = calib_struct.get(f'sect.{sectionindex}.diam.nom', []) + if len(np.atleast_1d(diam_nom)) > 0: + val_in = results['dmOut'][1, 0:2].ravel() + try: + val_out = linint3(calib_struct[f'sect.{sectionindex}.diam.act'], + calib_struct[f'sect.{sectionindex}.diam.nom'], + val_in) + results_out['dmOut'][1, 0:2] = val_out + except Exception: + pass + + if ccase > 0: + wall_nom = calib_struct.get(f'sect.{sectionindex}.wall.nom', []) + if len(np.atleast_1d(wall_nom)) > 0: + val_in = np.concatenate([ + results['left']['wth'][1, 0:2].ravel(), + results['right']['wth'][1, 0:2].ravel() + ]) + try: + val_out = linint3(calib_struct[f'sect.{sectionindex}.wall.act'], + calib_struct[f'sect.{sectionindex}.wall.nom'], + val_in) + results_out['left']['wth'][1, 0:2] = val_out[0:2] + results_out['right']['wth'][1, 0:2] = val_out[2:4] + except Exception: + pass + + if ccase == 1: + results_out['left']['osc'][1, :] = results_out['left']['wth'][1, :].copy() + results_out['right']['osc'][1, :] = results_out['right']['wth'][1, :].copy() + elif ccase == 2: + results_out['left']['iso'][1, :] = results_out['left']['wth'][1, :].copy() + results_out['right']['iso'][1, :] = results_out['right']['wth'][1, :].copy() + elif ccase == 3: + results_out['left']['isc'][1, :] = results_out['left']['wth'][1, :].copy() + results_out['right']['isc'][1, :] = results_out['right']['wth'][1, :].copy() + elif ccase == 4: + results_out = iso_calib(results, results_out, csector) + results_out = isc_calib(results, results_out, csector) + results_out = oscfit(results_out) + elif ccase == 5: + results_out = osc_calib(results, results_out, csector) + results_out = isc_calib(results, results_out, csector) + results_out = isofit(results_out) + elif ccase == 6: + results_out = osc_calib(results, results_out, csector) + results_out = iso_calib(results, results_out, csector) + results_out = iscfit(results_out) + + results_out = corefit(results_out) + + return results_out + + +def uponor_alucorrect2(results, cabletype): + cabletype = round(float(cabletype)) + + if cabletype not in (101, 105): + return results + + if cabletype == 101: + errvek = [ + results['dmOut'][1, 0], results['dmOut'][1, 0], + results['right']['osc'][1, 0], results['right']['osc'][1, 1], + results['left']['osc'][1, 1], results['right']['iso'][1, 0], + results['right']['iso'][1, 1], results['left']['iso'][1, 1], + ] + else: + errvek = [ + results['dmOut'][1, 0], results['dmOut'][1, 0], + results['left']['osc'][1, 0], results['left']['osc'][1, 1], + results['right']['osc'][1, 0], results['right']['osc'][1, 1], + results['left']['iso'][1, 0], results['left']['iso'][1, 1], + results['right']['iso'][1, 0], results['right']['iso'][1, 1], + ] + + if all(v == 0 for v in errvek): + if cabletype == 101: + isomitt = (1.0 / 3.0) * ( + results['right']['iso'][0, 0] + + results['left']['iso'][0, 1] + + results['right']['iso'][0, 1] + ) + + results['right']['osc'][0, 0] += 0.5 * (results['right']['iso'][0, 0] - isomitt) + results['left']['osc'][0, 1] += 0.5 * (results['left']['iso'][0, 1] - isomitt) + results['right']['osc'][0, 1] += 0.5 * (results['right']['iso'][0, 1] - isomitt) + + if not results['right']['isc'][1, 0]: + results['right']['isc'][0, 0] += 0.5 * (results['right']['iso'][0, 0] - isomitt) + if not results['left']['isc'][1, 1]: + results['left']['isc'][0, 1] += 0.5 * (results['left']['iso'][0, 1] - isomitt) + if not results['right']['isc'][1, 1]: + results['right']['isc'][0, 1] += 0.5 * (results['right']['iso'][0, 1] - isomitt) + + results['right']['iso'][0, 0] = isomitt + results['left']['iso'][0, 1] = isomitt + results['right']['iso'][0, 1] = isomitt + else: + isomitt = (1.0 / 4.0) * ( + results['left']['iso'][0, 0] + results['left']['iso'][0, 1] + + results['right']['iso'][0, 0] + results['right']['iso'][0, 1] + ) + + results['left']['osc'][0, 0] += 0.5 * (results['left']['iso'][0, 0] - isomitt) + results['right']['osc'][0, 0] += 0.5 * (results['right']['iso'][0, 0] - isomitt) + results['left']['osc'][0, 1] += 0.5 * (results['left']['iso'][0, 1] - isomitt) + results['right']['osc'][0, 1] += 0.5 * (results['right']['iso'][0, 1] - isomitt) + + if not results['left']['isc'][1, 0]: + results['left']['isc'][0, 0] += 0.5 * (results['left']['iso'][0, 0] - isomitt) + if not results['right']['isc'][1, 0]: + results['right']['isc'][0, 0] += 0.5 * (results['right']['iso'][0, 0] - isomitt) + if not results['left']['isc'][1, 1]: + results['left']['isc'][0, 1] += 0.5 * (results['left']['iso'][0, 1] - isomitt) + if not results['right']['isc'][1, 1]: + results['right']['isc'][0, 1] += 0.5 * (results['right']['iso'][0, 1] - isomitt) + + results['left']['iso'][0, 0] = isomitt + results['right']['iso'][0, 0] = isomitt + results['left']['iso'][0, 1] = isomitt + results['right']['iso'][0, 1] = isomitt + else: + errind = [i for i, v in enumerate(errvek) if v > 0] + errorvalue = np.array([0.0, errvek[errind[0]], 0.0]) + + for side in ['left', 'right']: + for layer in ['osc', 'iso', 'isc']: + for col in range(2): + results[side][layer][:, col] = errorvalue.copy() + + return results diff --git a/algorithm/math_utils.py b/algorithm/math_utils.py new file mode 100644 index 0000000..7be7cf1 --- /dev/null +++ b/algorithm/math_utils.py @@ -0,0 +1,153 @@ +import numpy as np + + +def gauss(s, k): + n = np.arange(-(k - 1) / 2, (k - 1) / 2 + 1) + g = np.exp(-n ** 2 / (2 * s ** 2)) + g = g / np.sum(g) + return g + + +def ind(x, dx, xshift=0, N=None): + Index = np.round(((x - xshift) / dx) + 1) + if N is not None: + if N == 0: + return np.array([]) + if isinstance(Index, np.ndarray): + Index[Index < 1] = 1 + Index[Index > N] = N + else: + if Index < 1: + Index = 1 + elif Index > N: + Index = N + return Index.astype(int) if isinstance(Index, np.ndarray) else int(Index) + + +def equal(a, b): + tol = b / 10000.0 + if np.isscalar(tol): + if tol < 1e-15: + tol = 1e-15 + else: + tol[tol < 1e-15] = 1e-15 + return np.abs(a - b) <= tol + + +def is_pe(cableType): + cableType = float(cableType) + if (equal(cableType, 1) or equal(cableType, 7) or equal(cableType, 44) or + equal(cableType, 60) or (73.99 <= cableType <= 78.01) or + (100.99 <= cableType <= 105.01) or (130.99 <= cableType <= 140.01) or + equal(cableType, 111) or equal(cableType, 151) or + equal(cableType, 62340000) or equal(cableType, 62434100) or + equal(cableType, 115) or equal(cableType, 62) or + equal(cableType, 123) or equal(cableType, 116)): + return 1 + else: + return 0 + + +def polyfit2(x, y, n): + x = np.asarray(x, dtype=np.float64) + y = np.asarray(y, dtype=np.float64) + if x.shape != y.shape: + raise ValueError('polyfit2: X and Y vectors must be the same size.') + x_flat = x.ravel() + y_flat = y.ravel() + if n == 1: + A = np.column_stack([x_flat, np.ones(len(x_flat))]) + elif n == 2: + A = np.column_stack([x_flat ** 2, x_flat, np.ones(len(x_flat))]) + else: + raise ValueError('polyfit2: n must be 1 or 2!') + p = np.linalg.lstsq(A, y_flat, rcond=None)[0] + return p.ravel() + + +def lininter(x, y, xi): + x = np.asarray(x, dtype=np.float64).ravel() + y = np.asarray(y, dtype=np.float64).ravel() + xi = np.asarray(xi, dtype=np.float64).ravel() + if len(x) != len(y): + raise ValueError('length(x) must be == length(y)') + if len(x) < 2: + raise ValueError('length(x) must be >= 2') + yi = np.zeros(len(xi)) + N = len(x) + k = 0 + for i in range(len(xi)): + foundxi = 0 + while foundxi == 0: + if (xi[i] >= x[k]) and (xi[i] < x[k + 1]): + m = (y[k + 1] - y[k]) / (x[k + 1] - x[k]) + yi[i] = m * (xi[i] - x[k]) + y[k] + foundxi = 1 + elif xi[i] <= x[0]: + yi[i] = y[0] + foundxi = 1 + elif xi[i] >= x[N - 1]: + yi[i] = y[N - 1] + foundxi = 1 + else: + if k != (N - 2): + k = k + 1 + else: + raise ValueError('Linint3: No solution, because no pos. step xi') + return yi + + +def linint3(x, y, xi): + x = np.asarray(x, dtype=np.float64).ravel() + y = np.asarray(y, dtype=np.float64).ravel() + xi = np.asarray(xi, dtype=np.float64).ravel() + if len(x) != len(y): + raise ValueError('length(x) must be == length(y)') + if len(x) < 2: + raise ValueError('length(x) must be >= 2') + sort_idx = np.argsort(xi) + xi_sorted = xi[sort_idx] + yi_sorted = np.zeros(len(xi_sorted)) + N = len(x) + k = 0 + for i in range(len(xi_sorted)): + foundxi = 0 + while foundxi == 0: + if (xi_sorted[i] >= x[k]) and (xi_sorted[i] < x[k + 1]): + m = (y[k + 1] - y[k]) / (x[k + 1] - x[k]) + yi_sorted[i] = m * (xi_sorted[i] - x[k]) + y[k] + foundxi = 1 + elif xi_sorted[i] <= x[0]: + m = (y[1] - y[0]) / (x[1] - x[0]) + yi_sorted[i] = m * (xi_sorted[i] - x[0]) + y[0] + foundxi = 1 + elif xi_sorted[i] >= x[N - 1]: + m = (y[N - 1] - y[N - 2]) / (x[N - 1] - x[N - 2]) + yi_sorted[i] = m * (xi_sorted[i] - x[N - 2]) + y[N - 2] + foundxi = 1 + else: + if k != (N - 2): + k = k + 1 + else: + raise ValueError('Linint3: No solution, because no pos. step xi') + yi = np.zeros_like(yi_sorted) + yi[sort_idx] = yi_sorted + return yi + + +def linreg(IN, Dl, Dr, dx, alles=0, xshift=0): + ll = ind(Dl, dx, xshift) + rr = ind(Dr, dx, xshift) + rechtsx = (ll - 1) * dx + xshift + N = 2 * (int(np.floor((rr - ll + 1) / 2))) + Indiffv = np.zeros(N) + x_arr = np.zeros(N) + Indiffv[:N] = IN[:N + ll - 1] + x_arr[:N] = np.arange(N) * dx + A = polyfit2(x_arr, Indiffv, 1) + reg = np.zeros(N) + Indiff = np.zeros(N) + reg[:N] = A[1] + A[0] * dx * np.arange(N) + Indiff[:N] = Indiffv[:N] - reg[:N] + Ref = Indiffv[int(N / 2)] + return Indiff, rechtsx, Ref diff --git a/algorithm/overview_utils.py b/algorithm/overview_utils.py new file mode 100644 index 0000000..cd49df2 --- /dev/null +++ b/algorithm/overview_utils.py @@ -0,0 +1,1296 @@ +import numpy as np +import copy +from collections import defaultdict + + +def _auto_dict(): + """递归默认字典,模拟 MATLAB 自动创建嵌套 struct 的行为""" + return defaultdict(_auto_dict) + + +def _to_regular_dict(d): + """将 auto_dict 转换为普通 dict,便于序列化""" + if isinstance(d, defaultdict): + return {k: _to_regular_dict(v) for k, v in d.items()} + elif isinstance(d, dict): + return {k: _to_regular_dict(v) for k, v in d.items()} + elif isinstance(d, list): + return [_to_regular_dict(v) for v in d] + return d + + +def _ensure_auto_dict(settings, key): + """确保 settings[key][sp] 是 auto_dict,便于嵌套访问""" + if key not in settings or not isinstance(settings[key], list): + settings[key] = [] + for i in range(len(settings[key])): + if not isinstance(settings[key][i], defaultdict): + ad = _auto_dict() + if isinstance(settings[key][i], dict): + for k, v in settings[key][i].items(): + ad[k] = v + settings[key][i] = ad + + +def _to_auto(d): + """将 dict 递归转换为 auto_dict""" + if isinstance(d, defaultdict): + return d + if isinstance(d, dict): + ad = _auto_dict() + for k, v in d.items(): + ad[k] = _to_auto(v) + return ad + if isinstance(d, list): + return [_to_auto(v) for v in d] + return d + + +def _scalar(x): + """安全获取标量值,处理各种数组形状""" + if isinstance(x, np.ndarray): + if x.size == 0: + return 0 + return float(x.ravel()[0]) + if isinstance(x, (list, tuple)): + if len(x) == 0: + return 0 + return _scalar(x[0]) + return float(x) + + +def ovrview(rawIntensity, settings, errnorm, sensorStatus, axis): + settingsOvrview = settings.copy() if isinstance(settings, dict) else settings + + if isinstance(settingsOvrview, dict): + if 'ovrview' not in settingsOvrview: + settingsOvrview['ovrview'] = {} + settingsOvrview['ovrview']['status'] = 0 + + need_init = ( + 'DMout' not in settingsOvrview['ovrview'] or + settingsOvrview.get('avgData', {}).get('init', 0) + ) + + if need_init: + for key in ['DMout', 'coreDM', 'layer3', 'layer2', 'layer1', + 'layer3r', 'layer2r', 'layer1r']: + settingsOvrview['ovrview'][key] = [] + + settingsOvrview['ovrview']['avgData'] = {} + for layername in ['DMout', 'coreDM', 'layer3', 'layer2', 'layer1', + 'layer3r', 'layer2r', 'layer1r']: + settingsOvrview['ovrview']['avgData'][layername] = {} + for idx in [1, 2]: + settingsOvrview['ovrview']['avgData'][layername][idx] = {} + for side in ['a', 'b']: + settingsOvrview['ovrview']['avgData'][layername][idx][side] = [] + + settingsOvrview['ovrview']['avgVid'] = 2 + settingsOvrview['ovrview']['BiEnMo'] = 0 + + nominalData = np.asarray(settingsOvrview.get('nominalData', np.zeros(10)), dtype=np.float64) + confData = np.asarray(settingsOvrview.get('confData', np.zeros(200)), dtype=np.float64) + + if len(confData) > 8: + confData[2] = nominalData[3] if len(nominalData) > 3 else 0 + confData[8] = nominalData[2] if len(nominalData) > 2 else 0 + confData[3] = nominalData[1] if len(nominalData) > 1 else 0 + confData[4] = nominalData[0] if len(nominalData) > 0 else 0 + + cableType = settingsOvrview.get('cableType', None) + if cableType is not None and len(confData) > 19: + confData[19] = cableType + + if len(confData) > 91: + confData[89] = confData[31] * confData[30] if len(confData) > 31 else 0 + confData[90] = 1 + confData[91] = confData[89] / confData[90] if confData[90] != 0 else 0 + + settingsOvrview['confData'] = confData + settingsOvrview['HV'] = 60 + + return settingsOvrview, errnorm + + +def startx8ana(rawIntensity, settings, err_meas_head, sensorStatus, senPair, axis): + from validation_utils import chksettings, plausi2000, plausi_layer, chk_tolchksettings + from averaging_utils import avg_mval, avg_ab, avg_mval_8pt + from detection_utils import AutoDetect + from geometry_utils import xy_correct, modify_cable_position, axis_result + from layer_calibration_utils import layer_correct, uponor_alucorrect2 + from analysis_utils import xray2000_ana_m, attprofile, voiddetect + from reconstr_utils import reconstr + from edge_detection_utils import i0detect + + detail_a = {} + detail_a['IN'] = np.nan + detail_a['nominal'] = np.nan + detail_a['left'] = {} + detail_a['left']['pos'] = {} + detail_a['left']['pos']['result'] = np.nan + detail_a['left']['pos']['start'] = np.nan + detail_a['left']['pos']['limit'] = {} + detail_a['left']['pos']['limit']['left'] = np.nan + detail_a['left']['pos']['limit']['right'] = np.nan + detail_a['left']['att'] = {} + detail_a['left']['att']['outer'] = np.nan + detail_a['left']['att']['inner'] = np.nan + detail_a['left']['error'] = np.array([np.nan, np.nan]) + detail_a['right'] = detail_a['left'].copy() + detail_a['att'] = {} + detail_a['att']['min'] = np.nan + detail_a['att']['max'] = np.nan + detail_a['contr'] = {} + detail_a['contr']['min'] = np.nan + detail_a['contr']['max'] = np.nan + detail_a['contr']['sign'] = np.nan + detail_b = {k: (v.copy() if isinstance(v, dict) else (np.array(v) if isinstance(v, np.ndarray) else v)) for k, v in detail_a.items()} + + if 'StartX2Ana' not in settings or not isinstance(settings['StartX2Ana'], dict) or 'ovrvwmem' not in settings['StartX2Ana']: + if 'StartX2Ana' not in settings or not isinstance(settings['StartX2Ana'], dict): + settings['StartX2Ana'] = {} + settings['StartX2Ana']['avgmem'] = {} + settings['StartX2Ana']['avgresults'] = {} + settings['StartX2Ana']['ovrvwmem'] = {} + if 'avgData' not in settings: + settings['avgData'] = {} + settings['avgData']['init'] = 1 + settings['StartX2Ana']['att_avgmem'] = {} + settings['StartX2Ana']['normmem'] = {} + settings['StartX2Ana']['CableType'] = {} + settings['StartX2Ana']['CableType']['Number'] = np.zeros(25) + settings['StartX2Ana']['CableType']['Counter'] = 0 + settings['StartX2Ana']['CableType']['Type'] = 0 + settings['StartX2Ana']['CableType']['NOMOSC'] = 0 + settings['StartX2Ana']['CableType']['NOMINS'] = 0 + settings['StartX2Ana']['CableType']['NOMISC'] = 0 + settings['StartX2Ana']['CableType']['BitInit'] = 1 + settings['StartX2Ana']['CableType']['HVoff'] = 0 + settings['StartX2Ana']['results'] = {} + + if 'StartX8Ana' not in settings or not isinstance(settings['StartX8Ana'], list) or len(settings['StartX8Ana']) < senPair[0] or (settings.get('avgData', {}).get('init', 0) and senPair[0] == 1): + if 'StartX8Ana' not in settings or not isinstance(settings['StartX8Ana'], list): + settings['StartX8Ana'] = [] + while len(settings['StartX8Ana']) < senPair[1]: + settings['StartX8Ana'].append(_auto_dict()) + _ensure_auto_dict(settings, 'StartX8Ana') + sp = senPair[0] - 1 + settings['StartX8Ana'][sp]['edges'] = _auto_dict() + settings['StartX8Ana'][sp]['edges']['left'] = _auto_dict() + settings['StartX8Ana'][sp]['edges']['right'] = _auto_dict() + settings['StartX8Ana'][sp]['status'] = _auto_dict() + settings['StartX8Ana'][sp]['att'] = _auto_dict() + settings['StartX8Ana'][sp]['err'] = _auto_dict() + settings['StartX8Ana'][sp]['conf93'] = [] + settings['StartX8Ana'][sp]['scanway'] = np.zeros(4) + settings['StartX8Ana'][sp]['counter'] = 0 + settings['StartX8Ana'][sp]['results'] = _auto_dict() + settings['StartX8Ana'][sp]['init'] = 1 + settings['StartX8Ana'][sp]['Riffle'] = [] + settings['StartX8Ana'][sp]['ovrvwmem'] = _auto_dict() + settings['StartX8Ana'][sp]['noterrordia'] = np.zeros(4) + elif len(settings['StartX8Ana']) < senPair[1]: + while len(settings['StartX8Ana']) < senPair[1]: + settings['StartX8Ana'].append(_auto_dict()) + _ensure_auto_dict(settings, 'StartX8Ana') + sp = senPair[0] - 1 + prev_sp = max(0, sp - 1) + settings['StartX8Ana'][sp]['edges'] = _auto_dict() + settings['StartX8Ana'][sp]['status'] = _auto_dict() + settings['StartX8Ana'][sp]['att'] = _auto_dict() + settings['StartX8Ana'][sp]['err'] = _auto_dict() + settings['StartX8Ana'][sp]['conf93'] = settings['StartX8Ana'][prev_sp].get('conf93', []) + settings['StartX8Ana'][sp]['scanway'] = settings['StartX8Ana'][prev_sp].get('scanway', np.zeros(4)).copy() + settings['StartX8Ana'][sp]['counter'] = settings['StartX8Ana'][prev_sp].get('counter', 0) + settings['StartX8Ana'][sp]['results'] = _auto_dict() + settings['StartX8Ana'][sp]['init'] = 0 + settings['StartX8Ana'][sp]['Riffle'] = settings['StartX8Ana'][prev_sp].get('Riffle', []) + settings['StartX8Ana'][sp]['ovrvwmem'] = _auto_dict() + settings['StartX8Ana'][sp]['noterrordia'] = np.zeros(4) + else: + _ensure_auto_dict(settings, 'StartX8Ana') + + if 'ovrvwmem' in settings['StartX2Ana'] and isinstance(settings['StartX2Ana']['ovrvwmem'], dict) and 'calcpara' in settings['StartX2Ana']['ovrvwmem'] and (senPair[0] == 1): + settings['StartX2Ana']['ovrvwmem']['calcpara'] = [] + + if settings.get('cableType', 0) == 115: + sp = senPair[0] - 1 + if not isinstance(settings['StartX8Ana'][sp].get('Riffle', []), np.ndarray) or settings['StartX8Ana'][sp]['Riffle'].size == 0: + print("暂不支持: load riffle.mat") + if err_meas_head[0] == 0: + err_meas_head[0] = 206 + else: + settings['riffle'] = settings['StartX8Ana'][sp]['Riffle'] + + sp = senPair[0] - 1 + if settings['StartX8Ana'][sp].get('init', 1) == 1 or (isinstance(settings['StartX8Ana'][sp].get('status', []), np.ndarray) and settings['StartX8Ana'][sp]['status'].size == 0) or not settings['StartX8Ana'][sp].get('status', []): + if err_meas_head[0]: + INITERR = err_meas_head[0] + elif (isinstance(rawIntensity.get('x', []), np.ndarray) and rawIntensity['x'].size == 0) or (isinstance(rawIntensity.get('y', []), np.ndarray) and rawIntensity['y'].size == 0): + INITERR = 240 + err_meas_head[0] = INITERR + else: + INITERR = 255 + results = {} + results['dmOut'] = np.zeros((3, 2)) + results['dmOut'][1, :] = INITERR + results['coreDm'] = np.zeros((3, 2)) + results['coreDm'][1, :] = INITERR + results['left'] = {} + results['left']['osc'] = np.zeros((3, 2)) + results['left']['osc'][1, :] = INITERR + results['left']['iso'] = np.zeros((3, 2)) + results['left']['iso'][1, :] = INITERR + results['left']['isc'] = np.zeros((3, 2)) + results['left']['isc'][1, :] = INITERR + results['left']['wth'] = np.zeros((3, 2)) + results['left']['wth'][1, :] = INITERR + results['right'] = {} + results['right']['osc'] = np.zeros((3, 2)) + results['right']['osc'][1, :] = INITERR + results['right']['iso'] = np.zeros((3, 2)) + results['right']['iso'][1, :] = INITERR + results['right']['isc'] = np.zeros((3, 2)) + results['right']['isc'][1, :] = INITERR + results['right']['wth'] = np.zeros((3, 2)) + results['right']['wth'][1, :] = INITERR + results['x'] = {} + results['x']['a'] = np.zeros((3, 4)) + results['x']['a'][1, :] = INITERR + results['x']['b'] = np.zeros((3, 4)) + results['x']['b'][1, :] = INITERR + results['y'] = {} + results['y']['a'] = np.zeros((3, 4)) + results['y']['a'][1, :] = INITERR + results['y']['b'] = np.zeros((3, 4)) + results['y']['b'][1, :] = INITERR + else: + results = settings['StartX8Ana'][sp]['results'] + + resultsAll = settings['StartX2Ana'].get('results', {}) + if (senPair[0] == 1) or not resultsAll: + if err_meas_head[0]: + INITERR = err_meas_head[0] + elif (isinstance(rawIntensity.get('x', []), np.ndarray) and rawIntensity['x'].size == 0) or (isinstance(rawIntensity.get('y', []), np.ndarray) and rawIntensity['y'].size == 0): + INITERR = 240 + err_meas_head[0] = INITERR + else: + INITERR = 255 + if not resultsAll: + resultsAll = {} + resultsAll['dmOut'] = np.zeros((3, 2)) + resultsAll['dmOut'][1, :] = INITERR + resultsAll['coreDm'] = np.zeros((3, 2)) + resultsAll['coreDm'][1, :] = INITERR + resultsAll['left'] = {} + resultsAll['left']['osc'] = np.zeros((3, 2)) + resultsAll['left']['osc'][1, :] = INITERR + resultsAll['left']['iso'] = np.zeros((3, 2)) + resultsAll['left']['iso'][1, :] = INITERR + resultsAll['left']['isc'] = np.zeros((3, 2)) + resultsAll['left']['isc'][1, :] = INITERR + resultsAll['left']['wth'] = np.zeros((3, 2)) + resultsAll['left']['wth'][1, :] = INITERR + resultsAll['right'] = {} + resultsAll['right']['osc'] = np.zeros((3, 2)) + resultsAll['right']['osc'][1, :] = INITERR + resultsAll['right']['iso'] = np.zeros((3, 2)) + resultsAll['right']['iso'][1, :] = INITERR + resultsAll['right']['isc'] = np.zeros((3, 2)) + resultsAll['right']['isc'][1, :] = INITERR + resultsAll['right']['wth'] = np.zeros((3, 2)) + resultsAll['right']['wth'][1, :] = INITERR + resultsAll['x'] = {} + resultsAll['x']['a'] = np.zeros((3, 4)) + resultsAll['x']['a'][1, :] = INITERR + resultsAll['x']['b'] = np.zeros((3, 4)) + resultsAll['x']['b'][1, :] = INITERR + resultsAll['y'] = {} + resultsAll['y']['a'] = np.zeros((3, 4)) + resultsAll['y']['a'][1, :] = INITERR + resultsAll['y']['b'] = np.zeros((3, 4)) + resultsAll['y']['b'][1, :] = INITERR + elif axis: + resultsAll['dmOut'][:, 0] = np.zeros(3) + resultsAll['dmOut'][1, 0] = INITERR + resultsAll['coreDm'][:, 0] = np.zeros(3) + resultsAll['coreDm'][1, 0] = INITERR + resultsAll['left']['osc'][:, 0] = np.zeros(3) + resultsAll['left']['osc'][1, 0] = INITERR + resultsAll['left']['iso'][:, 0] = np.zeros(3) + resultsAll['left']['iso'][1, 0] = INITERR + resultsAll['left']['isc'][:, 0] = np.zeros(3) + resultsAll['left']['isc'][1, 0] = INITERR + resultsAll['left']['wth'][:, 0] = np.zeros(3) + resultsAll['left']['wth'][1, 0] = INITERR + resultsAll['right']['osc'][:, 0] = np.zeros(3) + resultsAll['right']['osc'][1, 0] = INITERR + resultsAll['right']['iso'][:, 0] = np.zeros(3) + resultsAll['right']['iso'][1, 0] = INITERR + resultsAll['right']['isc'][:, 0] = np.zeros(3) + resultsAll['right']['isc'][1, 0] = INITERR + resultsAll['right']['wth'][:, 0] = np.zeros(3) + resultsAll['right']['wth'][1, 0] = INITERR + resultsAll['x'] = {} + resultsAll['x']['a'] = np.zeros((3, 4)) + resultsAll['x']['a'][1, :] = INITERR + resultsAll['x']['b'] = np.zeros((3, 4)) + resultsAll['x']['b'][1, :] = INITERR + else: + resultsAll['dmOut'][:, 1] = np.zeros(3) + resultsAll['dmOut'][1, 1] = INITERR + resultsAll['coreDm'][:, 1] = np.zeros(3) + resultsAll['coreDm'][1, 1] = INITERR + resultsAll['left']['osc'][:, 1] = np.zeros(3) + resultsAll['left']['osc'][1, 1] = INITERR + resultsAll['left']['iso'][:, 1] = np.zeros(3) + resultsAll['left']['iso'][1, 1] = INITERR + resultsAll['left']['isc'][:, 1] = np.zeros(3) + resultsAll['left']['isc'][1, 1] = INITERR + resultsAll['left']['wth'][:, 1] = np.zeros(3) + resultsAll['left']['wth'][1, 1] = INITERR + resultsAll['right']['osc'][:, 1] = np.zeros(3) + resultsAll['right']['osc'][1, 1] = INITERR + resultsAll['right']['iso'][:, 1] = np.zeros(3) + resultsAll['right']['iso'][1, 1] = INITERR + resultsAll['right']['isc'][:, 1] = np.zeros(3) + resultsAll['right']['isc'][1, 1] = INITERR + resultsAll['right']['wth'][:, 1] = np.zeros(3) + resultsAll['right']['wth'][1, 1] = INITERR + resultsAll['y'] = {} + resultsAll['y']['a'] = np.zeros((3, 4)) + resultsAll['y']['a'][1, :] = INITERR + resultsAll['y']['b'] = np.zeros((3, 4)) + resultsAll['y']['b'][1, :] = INITERR + + results['vw'] = np.zeros((3, 1)) + results['vw'][1, 0] = 45 + + settings, errsettings = chksettings(settings, err_meas_head, 1) + + confData = np.asarray(settings.get('confData', np.zeros(200)), dtype=np.float64) + + DistI0 = _scalar(confData[34]) + Dist01 = _scalar(confData[35]) + dx = _scalar(confData[30]) * _scalar(confData[31]) + + settings['vibwarning'] = confData[193] + + if settings.get('unit', 0) == 0: + mm2inch = 1 + inch2mm = 1 + else: + mm2inch = 1 / 25.4 + inch2mm = 25.4 + settings['nominalData'] = np.asarray(settings.get('nominalData', np.zeros(10)), dtype=np.float64) * inch2mm + + confData[2] = settings['nominalData'][3] + confData[8] = settings['nominalData'][2] + confData[3] = settings['nominalData'][1] + confData[4] = settings['nominalData'][0] + + if settings.get('cableType', 0) is not None: + confData[19] = settings['cableType'] + + confData[89] = confData[31] * confData[30] + + confData[90] = 1 + + confData[91] = confData[89] / confData[90] + + confData[94] = settings.get('version', {}).get('devicetype', 0) + + confData[93] = settings.get('avgData', {}).get('init', 0) + + settings['confData'] = confData + + if (confData[19] >= 30) and (confData[19] <= 50): + settings['mode'] = 1 + else: + settings['mode'] = 0 + + errnorm = errsettings + + conf93 = axis + + counta = len(rawIntensity.get('x', [])) + countb = len(rawIntensity.get('y', [])) + count = round((counta + countb) / 2) + + if settings.get('Reconstruct', 0) > 0: + rawIntensity['y'], rawIntensity['x'], errnorm, vibration_detected = reconstr(rawIntensity['x'], rawIntensity['y'], settings, errnorm) + + if settings.get('Reconstruct', 0) > 2: + rawIntensity['y'], rawIntensity['x'], errnorm, vibration_detected = reconstr(rawIntensity['x'], rawIntensity['y'], settings, errnorm) + if vibration_detected: + if 'plausiData' not in settings: + settings['plausiData'] = {} + settings['plausiData']['check_dm'] = 1 + settings['plausiData']['check_lay'] = 1 + + if confData[19] == 118: + if 'plausiData' not in settings: + settings['plausiData'] = {} + settings['plausiData']['check_dm'] = 1 + settings['plausiData']['check_lay'] = 1 + + I0x, errnormX = i0detect(rawIntensity['x'], confData[34], confData[91], confData[36], errnorm) + if errnormX[0] == 0: + NormVideoY = rawIntensity['x'] / I0x + else: + NormVideoY = np.zeros(len(rawIntensity['x'])) + I0y, errnormY = i0detect(rawIntensity['y'], confData[34], confData[91], confData[36], errnorm) + if errnormY[0] == 0: + NormVideoX = rawIntensity['y'] / I0y + else: + NormVideoX = np.zeros(len(rawIntensity['y'])) + + sensorStatus = np.asarray(sensorStatus) + n_sensors = sensorStatus.shape[1] if sensorStatus.ndim > 1 else 1 + if settings.get('version', {}).get('NXT', 0) == 2 and sensorStatus[4, int(0 + axis * n_sensors / 2)]: + errnormX[1] = 9 + errnormY[1] = 9 + + idx_col_x = int(2 * senPair[0] - 1 - 1 + axis * n_sensors / 2) + idx_col_y = int(2 * senPair[0] - 1 + axis * n_sensors / 2) + errnormX[0] = max([errnormX[0], sensorStatus[0, idx_col_x] * 107, sensorStatus[2, idx_col_x] * 109, sensorStatus[3, idx_col_x] * 110]) + errnormY[0] = max([errnormY[0], sensorStatus[0, idx_col_y] * 107, sensorStatus[2, idx_col_y] * 109, sensorStatus[3, idx_col_y] * 110]) + errnormX[1] = max([errnormX[1], sensorStatus[1, idx_col_x] * 108]) + errnormY[1] = max([errnormY[1], sensorStatus[1, idx_col_y] * 108]) + + if err_meas_head[0] == 0: + err_meas_head[0] = max([errnormX[0], errnormY[0]]) + if err_meas_head[0] == 0: + err_meas_head[1] = max([errnormX[1], errnormY[1]]) + + confData[92] = 1 + + tmp = _auto_dict() + + (tmp['edges']['left']['a'], tmp['edges']['right']['a'], tmp['status']['a'], tmp['status']['left']['a'], + tmp['status']['right']['a'], tmp['att']['left']['a'], tmp['att']['right']['a'], tmp['err']['a'], + layeruse, settings['StartX2Ana']['ovrvwmem'], IN_a, detail_a) = xray2000_ana_m(rawIntensity['x'], settings, errnormX, settings['StartX2Ana']['ovrvwmem']) + + (tmp['results']['dmOut']['a'], tmp['results']['left']['osc']['a'], tmp['results']['right']['osc']['a'], + tmp['results']['left']['iso']['a'], tmp['results']['right']['iso']['a'], tmp['results']['left']['isc']['a'], + tmp['results']['right']['isc']['a'], tmp['results']['coreDm']['a'], tmp['results']['left']['wth']['a'], + tmp['results']['right']['wth']['a'], tmp['results']['a']) = axis_result( + tmp['edges']['left']['a'], tmp['edges']['right']['a'], tmp['status']['a'], + tmp['status']['left']['a'], tmp['status']['right']['a'], 1, layeruse) + + if (settings.get('cableType', 0) == 62) or (settings.get('cableType', 0) == 63): + tmp['results']['left']['osc']['a'] = tmp['results']['left']['iso']['a'] + tmp['results']['right']['osc']['a'] = tmp['results']['left']['osc']['a'] + if settings.get('dm_laser_core') is not None and len(settings.get('dm_laser_core', [])) > 0: + if settings['dm_laser_core'] > 0: + temp = 0.5 * (tmp['results']['dmOut']['a'][0, 0] - settings['dm_laser_core']) + if temp < 0: + tmp['results']['left']['wth']['a'][0, 0] = 0 + tmp['results']['left']['wth']['a'][1, 0] = 84 + tmp['results']['left']['osc']['a'][0, 0] = 0 + tmp['results']['left']['osc']['a'][1, 0] = 84 + tmp['results']['coreDm']['a'][0, 0] = 0 + tmp['results']['coreDm']['a'][1, 0] = 84 + settings['avgData']['init'] = 1 + else: + tmp['results']['left']['wth']['a'][0, 0] = temp + tmp['results']['left']['wth']['a'][1, 0] = 0 + tmp['results']['left']['osc']['a'][0, 0] = temp + tmp['results']['left']['osc']['a'][1, 0] = 0 + tmp['results']['coreDm']['a'][0, 0] = settings['dm_laser_core'] + tmp['results']['coreDm']['a'][1, 0] = 0 + elif settings['dm_laser_core'] == 0: + tmp['results']['left']['wth']['a'][0, 0] = 0 + tmp['results']['left']['wth']['a'][1, 0] = 81 + tmp['results']['left']['osc']['a'][0, 0] = 0 + tmp['results']['left']['osc']['a'][1, 0] = 81 + tmp['results']['coreDm']['a'][0, 0] = 0 + tmp['results']['coreDm']['a'][1, 0] = 81 + settings['avgData']['init'] = 1 + elif settings['dm_laser_core'] == -1: + tmp['results']['left']['wth']['a'][0, 0] = 0 + tmp['results']['left']['wth']['a'][1, 0] = 82 + tmp['results']['left']['osc']['a'][0, 0] = 0 + tmp['results']['left']['osc']['a'][1, 0] = 82 + tmp['results']['coreDm']['a'][0, 0] = 0 + tmp['results']['coreDm']['a'][1, 0] = 82 + settings['avgData']['init'] = 1 + elif settings['dm_laser_core'] == -2: + tmp['results']['left']['wth']['a'][0, 0] = 0 + tmp['results']['left']['wth']['a'][1, 0] = 102 + tmp['results']['left']['osc']['a'][0, 0] = 0 + tmp['results']['left']['osc']['a'][1, 0] = 102 + tmp['results']['coreDm']['a'][0, 0] = 0 + tmp['results']['coreDm']['a'][1, 0] = 102 + settings['avgData']['init'] = 1 + elif settings['dm_laser_core'] < 0: + tmp['results']['left']['wth']['a'][0, 0] = 0 + tmp['results']['left']['wth']['a'][1, 0] = 81 + tmp['results']['left']['osc']['a'][0, 0] = 0 + tmp['results']['left']['osc']['a'][1, 0] = 81 + tmp['results']['coreDm']['a'][0, 0] = 0 + tmp['results']['coreDm']['a'][1, 0] = 81 + settings['avgData']['init'] = 1 + else: + tmp['results']['left']['wth']['a'][0, 0] = 0 + tmp['results']['left']['wth']['a'][1, 0] = 83 + tmp['results']['left']['osc']['a'][0, 0] = 0 + tmp['results']['left']['osc']['a'][1, 0] = 83 + tmp['results']['coreDm']['a'][0, 0] = 0 + tmp['results']['coreDm']['a'][1, 0] = 83 + settings['avgData']['init'] = 1 + tmp['results']['left']['wth']['a'][:, 1] = tmp['results']['left']['wth']['a'][:, 0] + tmp['results']['right']['wth']['a'] = tmp['results']['left']['wth']['a'] + tmp['results']['left']['osc']['a'][:, 1] = tmp['results']['left']['osc']['a'][:, 0] + tmp['results']['right']['osc']['a'] = tmp['results']['left']['osc']['a'] + tmp['results']['coreDm']['a'][:, 1] = tmp['results']['coreDm']['a'][:, 0] + + sp = senPair[0] - 1 + if 'ovrvwmem' not in settings['StartX8Ana'][sp] or not isinstance(settings['StartX8Ana'][sp]['ovrvwmem'], dict): + settings['StartX8Ana'][sp]['ovrvwmem'] = {} + if 'plot_uebergaenge' not in settings['StartX8Ana'][sp]['ovrvwmem']: + settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'] = [] + while len(settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge']) < senPair[1]: + settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'].append({}) + pu_idx = senPair[0] - 1 + if 'normvideo' not in settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'][pu_idx]: + settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'][pu_idx]['normvideo'] = {} + if 'settings' not in settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'][pu_idx]: + settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'][pu_idx]['settings'] = {} + settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'][pu_idx]['normvideo']['x'] = rawIntensity['x'] / I0x + settings_snapshot_x = copy.deepcopy(settings) + settings_snapshot_x.pop('StartX8Ana', None) + settings_snapshot_x.pop('StartX2Ana', None) + settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'][pu_idx]['settings']['x'] = settings_snapshot_x + + confData[92] = 0 + + (tmp['edges']['left']['b'], tmp['edges']['right']['b'], tmp['status']['b'], tmp['status']['left']['b'], + tmp['status']['right']['b'], tmp['att']['left']['b'], tmp['att']['right']['b'], tmp['err']['b'], + layeruse, settings['StartX2Ana']['ovrvwmem'], IN_b, detail_b) = xray2000_ana_m(rawIntensity['y'], settings, errnormY, settings['StartX2Ana']['ovrvwmem']) + + (tmp['results']['dmOut']['b'], tmp['results']['left']['osc']['b'], tmp['results']['right']['osc']['b'], + tmp['results']['left']['iso']['b'], tmp['results']['right']['iso']['b'], tmp['results']['left']['isc']['b'], + tmp['results']['right']['isc']['b'], tmp['results']['coreDm']['b'], tmp['results']['left']['wth']['b'], + tmp['results']['right']['wth']['b'], tmp['results']['b']) = axis_result( + tmp['edges']['left']['b'], tmp['edges']['right']['b'], tmp['status']['b'], + tmp['status']['left']['b'], tmp['status']['right']['b'], 1, layeruse) + + if (settings.get('cableType', 0) == 62) or (settings.get('cableType', 0) == 63): + tmp['results']['left']['osc']['b'] = tmp['results']['left']['iso']['b'] + tmp['results']['right']['osc']['b'] = tmp['results']['left']['osc']['b'] + if settings.get('dm_laser_core') is not None and len(settings.get('dm_laser_core', [])) > 0: + if settings['dm_laser_core'] > 0: + temp = 0.5 * (tmp['results']['dmOut']['b'][0, 0] - settings['dm_laser_core']) + if temp < 0: + tmp['results']['left']['wth']['b'][0, 0] = 0 + tmp['results']['left']['wth']['b'][1, 0] = 84 + tmp['results']['left']['osc']['b'][0, 0] = 0 + tmp['results']['left']['osc']['b'][1, 0] = 84 + tmp['results']['coreDm']['b'][0, 0] = 0 + tmp['results']['coreDm']['b'][1, 0] = 84 + settings['avgData']['init'] = 1 + else: + tmp['results']['left']['wth']['b'][0, 0] = temp + tmp['results']['left']['wth']['b'][1, 0] = 0 + tmp['results']['left']['osc']['b'][0, 0] = temp + tmp['results']['left']['osc']['b'][1, 0] = 0 + tmp['results']['coreDm']['b'][0, 0] = settings['dm_laser_core'] + tmp['results']['coreDm']['b'][1, 0] = 0 + elif settings['dm_laser_core'] == 0: + tmp['results']['left']['wth']['b'][0, 0] = 0 + tmp['results']['left']['wth']['b'][1, 0] = 81 + tmp['results']['left']['osc']['b'][0, 0] = 0 + tmp['results']['left']['osc']['b'][1, 0] = 81 + tmp['results']['coreDm']['b'][0, 0] = 0 + tmp['results']['coreDm']['b'][1, 0] = 81 + settings['avgData']['init'] = 1 + elif settings['dm_laser_core'] == -1: + tmp['results']['left']['wth']['b'][0, 0] = 0 + tmp['results']['left']['wth']['b'][1, 0] = 82 + tmp['results']['left']['osc']['b'][0, 0] = 0 + tmp['results']['left']['osc']['b'][1, 0] = 82 + tmp['results']['coreDm']['b'][0, 0] = 0 + tmp['results']['coreDm']['b'][1, 0] = 82 + settings['avgData']['init'] = 1 + elif settings['dm_laser_core'] == -2: + tmp['results']['left']['wth']['b'][0, 0] = 0 + tmp['results']['left']['wth']['b'][1, 0] = 102 + tmp['results']['left']['osc']['b'][0, 0] = 0 + tmp['results']['left']['osc']['b'][1, 0] = 102 + tmp['results']['coreDm']['b'][0, 0] = 0 + tmp['results']['coreDm']['b'][1, 0] = 102 + settings['avgData']['init'] = 1 + elif settings['dm_laser_core'] < 0: + tmp['results']['left']['wth']['b'][0, 0] = 0 + tmp['results']['left']['wth']['b'][1, 0] = 81 + tmp['results']['left']['osc']['b'][0, 0] = 0 + tmp['results']['left']['osc']['b'][1, 0] = 81 + tmp['results']['coreDm']['b'][0, 0] = 0 + tmp['results']['coreDm']['b'][1, 0] = 81 + settings['avgData']['init'] = 1 + else: + tmp['results']['left']['wth']['b'][0, 0] = 0 + tmp['results']['left']['wth']['b'][1, 0] = 83 + tmp['results']['left']['osc']['b'][0, 0] = 0 + tmp['results']['left']['osc']['b'][1, 0] = 83 + tmp['results']['coreDm']['b'][0, 0] = 0 + tmp['results']['coreDm']['b'][1, 0] = 83 + settings['avgData']['init'] = 1 + tmp['results']['left']['wth']['b'][:, 1] = tmp['results']['left']['wth']['b'][:, 0] + tmp['results']['right']['wth']['b'] = tmp['results']['left']['wth']['b'] + tmp['results']['left']['osc']['b'][:, 1] = tmp['results']['left']['osc']['b'][:, 0] + tmp['results']['right']['osc']['b'] = tmp['results']['left']['osc']['b'] + tmp['results']['coreDm']['b'][:, 1] = tmp['results']['coreDm']['b'][:, 0] + + settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'][pu_idx]['normvideo']['y'] = rawIntensity['y'] / I0y + settings_snapshot_y = copy.deepcopy(settings) + settings_snapshot_y.pop('StartX8Ana', None) + settings_snapshot_y.pop('StartX2Ana', None) + settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'][pu_idx]['settings']['y'] = settings_snapshot_y + settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'][pu_idx]['edges'] = tmp['edges'] + settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'][pu_idx]['status'] = tmp['status'] + settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'][pu_idx]['att'] = tmp['att'] + settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'][pu_idx]['err'] = tmp['err'] + settings['StartX8Ana'][sp]['ovrvwmem']['plot_uebergaenge'][pu_idx]['results'] = tmp['results'] + + confData[92] = conf93 + + anzedge = int(np.sum(layeruse == 1)) + 1 + + edges = settings['StartX8Ana'][sp].get('edges', {}) + if not isinstance(edges, dict) or 'left' not in edges or not isinstance(edges['left'], dict) or 'x' not in edges['left']: + if not isinstance(edges, dict): + edges = {} + if 'left' not in edges or not isinstance(edges['left'], dict): + edges['left'] = {} + if 'right' not in edges or not isinstance(edges['right'], dict): + edges['right'] = {} + edges['left']['x'] = np.zeros(anzedge) + edges['right']['x'] = np.zeros(anzedge) + if 'status' not in settings['StartX8Ana'][sp] or not isinstance(settings['StartX8Ana'][sp]['status'], dict): + settings['StartX8Ana'][sp]['status'] = {} + settings['StartX8Ana'][sp]['status']['x'] = np.zeros((2, 1)) + settings['StartX8Ana'][sp]['status']['x'][0, :] = 249 + settings['StartX8Ana'][sp]['status']['left'] = {} + settings['StartX8Ana'][sp]['status']['left']['x'] = np.zeros((2, anzedge)) + settings['StartX8Ana'][sp]['status']['left']['x'][0, :] = 249 + settings['StartX8Ana'][sp]['status']['right'] = {} + settings['StartX8Ana'][sp]['status']['right']['x'] = np.zeros((2, anzedge)) + settings['StartX8Ana'][sp]['status']['right']['x'][0, :] = 249 + if 'att' not in settings['StartX8Ana'][sp] or not isinstance(settings['StartX8Ana'][sp]['att'], dict): + settings['StartX8Ana'][sp]['att'] = {} + settings['StartX8Ana'][sp]['att']['left'] = {} + settings['StartX8Ana'][sp]['att']['left']['x'] = {} + settings['StartX8Ana'][sp]['att']['left']['x']['att'] = np.zeros(anzedge - 1) + settings['StartX8Ana'][sp]['att']['left']['x']['gra'] = np.zeros(anzedge - 1) + settings['StartX8Ana'][sp]['att']['right']['x'] = {} + settings['StartX8Ana'][sp]['att']['right']['x']['att'] = np.zeros(anzedge - 1) + settings['StartX8Ana'][sp]['att']['right']['x']['gra'] = np.zeros(anzedge - 1) + settings['StartX8Ana'][sp]['att']['right']['x']['con'] = np.zeros(anzedge - 1) + settings['StartX8Ana'][sp]['att']['left']['x']['con'] = np.zeros(anzedge - 1) + if 'err' not in settings['StartX8Ana'][sp] or not isinstance(settings['StartX8Ana'][sp]['err'], dict): + settings['StartX8Ana'][sp]['err'] = {} + settings['StartX8Ana'][sp]['err']['x'] = np.zeros((2, 28)) + + if not isinstance(edges, dict) or 'left' not in edges or not isinstance(edges['left'], dict) or 'y' not in edges['left']: + if not isinstance(edges, dict): + edges = {} + if 'left' not in edges or not isinstance(edges['left'], dict): + edges['left'] = {} + if 'right' not in edges or not isinstance(edges['right'], dict): + edges['right'] = {} + edges['left']['y'] = np.zeros(anzedge) + edges['right']['y'] = np.zeros(anzedge) + if 'status' not in settings['StartX8Ana'][sp] or not isinstance(settings['StartX8Ana'][sp]['status'], dict): + settings['StartX8Ana'][sp]['status'] = {} + settings['StartX8Ana'][sp]['status']['y'] = np.zeros((2, 1)) + settings['StartX8Ana'][sp]['status']['y'][0, :] = 249 + if 'left' not in settings['StartX8Ana'][sp]['status'] or not isinstance(settings['StartX8Ana'][sp]['status']['left'], dict): + settings['StartX8Ana'][sp]['status']['left'] = {} + settings['StartX8Ana'][sp]['status']['left']['y'] = np.zeros((2, anzedge)) + settings['StartX8Ana'][sp]['status']['left']['y'][0, :] = 249 + if 'right' not in settings['StartX8Ana'][sp]['status'] or not isinstance(settings['StartX8Ana'][sp]['status']['right'], dict): + settings['StartX8Ana'][sp]['status']['right'] = {} + settings['StartX8Ana'][sp]['status']['right']['y'] = np.zeros((2, anzedge)) + settings['StartX8Ana'][sp]['status']['right']['y'][0, :] = 249 + if 'att' not in settings['StartX8Ana'][sp] or not isinstance(settings['StartX8Ana'][sp]['att'], dict): + settings['StartX8Ana'][sp]['att'] = {} + if 'left' not in settings['StartX8Ana'][sp]['att'] or not isinstance(settings['StartX8Ana'][sp]['att']['left'], dict): + settings['StartX8Ana'][sp]['att']['left'] = {} + settings['StartX8Ana'][sp]['att']['left']['y'] = {} + settings['StartX8Ana'][sp]['att']['left']['y']['att'] = np.zeros(anzedge - 1) + settings['StartX8Ana'][sp]['att']['left']['y']['gra'] = np.zeros(anzedge - 1) + settings['StartX8Ana'][sp]['att']['left']['y']['con'] = np.zeros(anzedge - 1) + if 'right' not in settings['StartX8Ana'][sp]['att'] or not isinstance(settings['StartX8Ana'][sp]['att']['right'], dict): + settings['StartX8Ana'][sp]['att']['right'] = {} + settings['StartX8Ana'][sp]['att']['right']['y'] = {} + settings['StartX8Ana'][sp]['att']['right']['y']['att'] = np.zeros(anzedge - 1) + settings['StartX8Ana'][sp]['att']['right']['y']['gra'] = np.zeros(anzedge - 1) + settings['StartX8Ana'][sp]['att']['right']['y']['con'] = np.zeros(anzedge - 1) + if 'err' not in settings['StartX8Ana'][sp] or not isinstance(settings['StartX8Ana'][sp]['err'], dict): + settings['StartX8Ana'][sp]['err'] = {} + settings['StartX8Ana'][sp]['err']['y'] = np.zeros((2, 28)) + + edges = settings['StartX8Ana'][sp]['edges'] + edges['left']['x'] = tmp['edges']['left']['b'] + edges['right']['x'] = tmp['edges']['right']['b'] + edges['left']['y'] = tmp['edges']['left']['a'] + edges['right']['y'] = tmp['edges']['right']['a'] + status = settings['StartX8Ana'][sp]['status'] + status['left']['x'] = tmp['status']['left']['b'] + status['right']['x'] = tmp['status']['right']['b'] + status['left']['y'] = tmp['status']['left']['a'] + status['right']['y'] = tmp['status']['right']['a'] + + att = settings['StartX8Ana'][sp]['att'] + err = settings['StartX8Ana'][sp]['err'] + last93 = settings['StartX8Ana'][sp].get('conf93', []) + counter = settings['StartX8Ana'][sp].get('counter', 0) + + ScanWay = np.asarray(settings['StartX8Ana'][sp].get('scanway', np.zeros(4)), dtype=np.float64).copy().ravel() + noterrordia = np.zeros(4, dtype=np.float64) + + if axis == 1: + prev_sp = max(0, sp - 1) + ScanWay[1] = settings['StartX8Ana'][prev_sp].get('scanway', np.zeros(4))[1] + ScanWay[3] = settings['StartX8Ana'][prev_sp].get('scanway', np.zeros(4))[3] + noterrordia[1] = settings['StartX8Ana'][prev_sp].get('noterrordia', np.zeros(4))[1] + noterrordia[3] = settings['StartX8Ana'][prev_sp].get('noterrordia', np.zeros(4))[3] + + (results['dmOut'][:, 0], results['left']['osc'][:, 0], results['right']['osc'][:, 0], + results['left']['iso'][:, 0], results['right']['iso'][:, 0], results['left']['isc'][:, 0], + results['right']['isc'][:, 0], results['coreDm'][:, 0], results['left']['wth'][:, 0], + results['right']['wth'][:, 0], results['x']) = avg_ab(tmp, confData) + + noterrordia_al = (_scalar(tmp['results']['dmOut']['a'][1, 0]) == 0) if isinstance(tmp['results']['dmOut'].get('a'), np.ndarray) and tmp['results']['dmOut']['a'].shape[0] > 1 else False + noterrordia_bl = (_scalar(tmp['results']['dmOut']['b'][1, 0]) == 0) if isinstance(tmp['results']['dmOut'].get('b'), np.ndarray) and tmp['results']['dmOut']['b'].shape[0] > 1 else False + if noterrordia_al and ((not ScanWay[1]) or senPair[0] == 1): + ScanWay[1] = ((count - 1) * dx - _scalar(tmp['edges']['left']['a'][0, 0]) + (2 * senPair[0] - 2) * DistI0 + Dist01) + noterrordia[1] = noterrordia[1] + 1 + elif (not noterrordia_al) and noterrordia_bl and ((not ScanWay[1]) or senPair[0] == 1): + ScanWay[1] = ((count - 1) * dx - _scalar(tmp['edges']['left']['b'][0, 0]) + (2 * senPair[0] - 1) * DistI0 + Dist01) + noterrordia[1] = noterrordia[1] + 1 + elif senPair[0] == 1: + ScanWay[1] = 0 + noterrordia_ar = (_scalar(tmp['results']['dmOut']['a'][1, 0]) == 0) if isinstance(tmp['results']['dmOut'].get('a'), np.ndarray) and tmp['results']['dmOut']['a'].shape[0] > 1 else False + noterrordia_br = (_scalar(tmp['results']['dmOut']['b'][1, 0]) == 0) if isinstance(tmp['results']['dmOut'].get('b'), np.ndarray) and tmp['results']['dmOut']['b'].shape[0] > 1 else False + if noterrordia_br: + ScanWay[3] = (_scalar(tmp['edges']['right']['b'][0, 0]) + (2 * senPair[1] - (2 * senPair[0] - 1)) * DistI0 + Dist01) + noterrordia[3] = noterrordia[3] + 1 + elif noterrordia_ar and (not noterrordia_br): + ScanWay[3] = (_scalar(tmp['edges']['right']['a'][0, 0]) + (2 * senPair[1] - (2 * senPair[0] - 2)) * DistI0 + Dist01) + noterrordia[3] = noterrordia[3] + 1 + if (senPair[0] == senPair[1]) and (not np.floor(noterrordia[3] / np.ceil(senPair[1] / 2))): + ScanWay[3] = 0 + if err_meas_head[0] == 253 or np.any(ScanWay[1:4:2] <= 0): + ScanWay[1] = 0 + ScanWay[3] = 0 + + tmpAll = {} + tmpAll['results'] = {} + tmpAll['results']['dmOut'] = {} + tmpAll['results']['left'] = {} + tmpAll['results']['left']['osc'] = {} + tmpAll['results']['right'] = {} + tmpAll['results']['right']['osc'] = {} + tmpAll['results']['left']['iso'] = {} + tmpAll['results']['right']['iso'] = {} + tmpAll['results']['left']['isc'] = {} + tmpAll['results']['right']['isc'] = {} + tmpAll['results']['coreDm'] = {} + tmpAll['results']['left']['wth'] = {} + tmpAll['results']['right']['wth'] = {} + + tmpAll['results']['dmOut']['a'] = resultsAll['dmOut'][:, 0] + tmpAll['results']['left']['osc']['a'] = resultsAll['left']['osc'][:, 0] + tmpAll['results']['right']['osc']['a'] = resultsAll['right']['osc'][:, 0] + tmpAll['results']['left']['iso']['a'] = resultsAll['left']['iso'][:, 0] + tmpAll['results']['right']['iso']['a'] = resultsAll['right']['iso'][:, 0] + tmpAll['results']['left']['isc']['a'] = resultsAll['left']['isc'][:, 0] + tmpAll['results']['right']['isc']['a'] = resultsAll['right']['isc'][:, 0] + tmpAll['results']['coreDm']['a'] = resultsAll['coreDm'][:, 0] + tmpAll['results']['left']['wth']['a'] = resultsAll['left']['wth'][:, 0] + tmpAll['results']['right']['wth']['a'] = resultsAll['right']['wth'][:, 0] + tmpAll['results']['a'] = resultsAll['x'] + + tmpAll['results']['dmOut']['b'] = results['dmOut'][:, 0] + tmpAll['results']['left']['osc']['b'] = results['left']['osc'][:, 0] + tmpAll['results']['right']['osc']['b'] = results['right']['osc'][:, 0] + tmpAll['results']['left']['iso']['b'] = results['left']['iso'][:, 0] + tmpAll['results']['right']['iso']['b'] = results['right']['iso'][:, 0] + tmpAll['results']['left']['isc']['b'] = results['left']['isc'][:, 0] + tmpAll['results']['right']['isc']['b'] = results['right']['isc'][:, 0] + tmpAll['results']['coreDm']['b'] = results['coreDm'][:, 0] + tmpAll['results']['left']['wth']['b'] = results['left']['wth'][:, 0] + tmpAll['results']['right']['wth']['b'] = results['right']['wth'][:, 0] + tmpAll['results']['b'] = results['x'] + + (resultsAll['dmOut'][:, 0], resultsAll['left']['osc'][:, 0], resultsAll['right']['osc'][:, 0], + resultsAll['left']['iso'][:, 0], resultsAll['right']['iso'][:, 0], resultsAll['left']['isc'][:, 0], + resultsAll['right']['isc'][:, 0], resultsAll['coreDm'][:, 0], resultsAll['left']['wth'][:, 0], + resultsAll['right']['wth'][:, 0], resultsAll['x']) = avg_ab(tmpAll, confData) + + elif axis == 0: + prev_sp = max(0, sp - 1) + ScanWay[0] = settings['StartX8Ana'][prev_sp].get('scanway', np.zeros(4))[0] + ScanWay[2] = settings['StartX8Ana'][prev_sp].get('scanway', np.zeros(4))[2] + noterrordia[0] = settings['StartX8Ana'][prev_sp].get('noterrordia', np.zeros(4))[0] + noterrordia[2] = settings['StartX8Ana'][prev_sp].get('noterrordia', np.zeros(4))[2] + + (results['dmOut'][:, 1], results['left']['osc'][:, 1], results['right']['osc'][:, 1], + results['left']['iso'][:, 1], results['right']['iso'][:, 1], results['left']['isc'][:, 1], + results['right']['isc'][:, 1], results['coreDm'][:, 1], results['left']['wth'][:, 1], + results['right']['wth'][:, 1], results['y']) = avg_ab(tmp, confData) + + noterrordia_al = (_scalar(tmp['results']['dmOut']['a'][1, 0]) == 0) if isinstance(tmp['results']['dmOut'].get('a'), np.ndarray) and tmp['results']['dmOut']['a'].shape[0] > 1 else False + noterrordia_bl = (_scalar(tmp['results']['dmOut']['b'][1, 0]) == 0) if isinstance(tmp['results']['dmOut'].get('b'), np.ndarray) and tmp['results']['dmOut']['b'].shape[0] > 1 else False + if noterrordia_al and ((not ScanWay[0]) or senPair[0] == 1): + ScanWay[0] = float(((count - 1) * dx - _scalar(tmp['edges']['left']['a'][0, 0]) + (2 * senPair[0] - 2) * DistI0 + Dist01)) + noterrordia[0] = noterrordia[0] + 1 + elif (not noterrordia_al) and noterrordia_bl and ((not ScanWay[0]) or senPair[0] == 1): + ScanWay[0] = float(((count - 1) * dx - _scalar(tmp['edges']['left']['b'][0, 0]) + (2 * senPair[0] - 1) * DistI0 + Dist01)) + noterrordia[0] = noterrordia[0] + 1 + elif senPair[0] == 1: + ScanWay[0] = 0.0 + noterrordia_ar = (_scalar(tmp['results']['dmOut']['a'][1, 0]) == 0) if isinstance(tmp['results']['dmOut'].get('a'), np.ndarray) and tmp['results']['dmOut']['a'].shape[0] > 1 else False + noterrordia_br = (_scalar(tmp['results']['dmOut']['b'][1, 0]) == 0) if isinstance(tmp['results']['dmOut'].get('b'), np.ndarray) and tmp['results']['dmOut']['b'].shape[0] > 1 else False + if noterrordia_br: + ScanWay[2] = float((_scalar(tmp['edges']['right']['b'][0, 0]) + (2 * senPair[1] - (2 * senPair[0])) * DistI0 + Dist01)) + noterrordia[2] = noterrordia[2] + 1 + elif noterrordia_ar and (not noterrordia_br): + ScanWay[2] = float((_scalar(tmp['edges']['right']['a'][0, 0]) + (2 * senPair[1] - (2 * senPair[0] - 1)) * DistI0 + Dist01)) + noterrordia[2] = noterrordia[2] + 1 + if (senPair[0] == senPair[1]) and (not np.floor(noterrordia[2] / np.ceil(senPair[1] / 2))): + ScanWay[2] = 0 + if err_meas_head[0] == 253 or np.any(ScanWay[0:3:2] <= 0): + ScanWay[0] = 0 + ScanWay[2] = 0 + + tmpAll = {} + tmpAll['results'] = {} + tmpAll['results']['dmOut'] = {} + tmpAll['results']['left'] = {} + tmpAll['results']['left']['osc'] = {} + tmpAll['results']['right'] = {} + tmpAll['results']['right']['osc'] = {} + tmpAll['results']['left']['iso'] = {} + tmpAll['results']['right']['iso'] = {} + tmpAll['results']['left']['isc'] = {} + tmpAll['results']['right']['isc'] = {} + tmpAll['results']['coreDm'] = {} + tmpAll['results']['left']['wth'] = {} + tmpAll['results']['right']['wth'] = {} + + tmpAll['results']['dmOut']['a'] = resultsAll['dmOut'][:, 1] + tmpAll['results']['left']['osc']['a'] = resultsAll['left']['osc'][:, 1] + tmpAll['results']['right']['osc']['a'] = resultsAll['right']['osc'][:, 1] + tmpAll['results']['left']['iso']['a'] = resultsAll['left']['iso'][:, 1] + tmpAll['results']['right']['iso']['a'] = resultsAll['right']['iso'][:, 1] + tmpAll['results']['left']['isc']['a'] = resultsAll['left']['isc'][:, 1] + tmpAll['results']['right']['isc']['a'] = resultsAll['right']['isc'][:, 1] + tmpAll['results']['coreDm']['a'] = resultsAll['coreDm'][:, 1] + tmpAll['results']['left']['wth']['a'] = resultsAll['left']['wth'][:, 1] + tmpAll['results']['right']['wth']['a'] = resultsAll['right']['wth'][:, 1] + tmpAll['results']['a'] = resultsAll['y'] + + tmpAll['results']['dmOut']['b'] = results['dmOut'][:, 1] + tmpAll['results']['left']['osc']['b'] = results['left']['osc'][:, 1] + tmpAll['results']['right']['osc']['b'] = results['right']['osc'][:, 1] + tmpAll['results']['left']['iso']['b'] = results['left']['iso'][:, 1] + tmpAll['results']['right']['iso']['b'] = results['right']['iso'][:, 1] + tmpAll['results']['left']['isc']['b'] = results['left']['isc'][:, 1] + tmpAll['results']['right']['isc']['b'] = results['right']['isc'][:, 1] + tmpAll['results']['coreDm']['b'] = results['coreDm'][:, 1] + tmpAll['results']['left']['wth']['b'] = results['left']['wth'][:, 1] + tmpAll['results']['right']['wth']['b'] = results['right']['wth'][:, 1] + tmpAll['results']['b'] = results['y'] + + (resultsAll['dmOut'][:, 1], resultsAll['left']['osc'][:, 1], resultsAll['right']['osc'][:, 1], + resultsAll['left']['iso'][:, 1], resultsAll['right']['iso'][:, 1], resultsAll['left']['isc'][:, 1], + resultsAll['right']['isc'][:, 1], resultsAll['coreDm'][:, 1], resultsAll['left']['wth'][:, 1], + resultsAll['right']['wth'][:, 1], resultsAll['y']) = avg_ab(tmpAll, confData) + else: + print('conf(93): Achse nicht definiert!') + + settings['StartX8Ana'][sp]['edges'] = edges + settings['StartX8Ana'][sp]['status'] = status + settings['StartX8Ana'][sp]['att'] = att + settings['StartX8Ana'][sp]['err'] = err + settings['StartX8Ana'][sp]['conf93'] = conf93 + settings['StartX8Ana'][sp]['counter'] = not counter + settings['StartX8Ana'][sp]['scanway'] = ScanWay + settings['StartX8Ana'][sp]['results'] = results + settings['StartX8Ana'][sp]['noterrordia'] = noterrordia + + def _calib_valid(c): + if isinstance(c, dict): + return len(c) > 0 + if isinstance(c, np.ndarray): + return c.size > 0 + return False + + calib_int = settings.get('calib_struct', {}).get('int', []) + if _calib_valid(calib_int): + results = layer_correct(results, calib_int, layeruse, settings.get('cableType', 0)) + else: + defaultval = np.array([[0, 0], [191, 191], [0, 0]]) + results['dmOut'] = defaultval.copy() + results['coreDm'] = defaultval.copy() + results['left']['wth'] = defaultval.copy() + results['left']['osc'] = defaultval.copy() + results['left']['iso'] = defaultval.copy() + results['left']['isc'] = defaultval.copy() + results['right']['wth'] = defaultval.copy() + results['right']['osc'] = defaultval.copy() + results['right']['iso'] = defaultval.copy() + results['right']['isc'] = defaultval.copy() + + calib_ext = settings.get('calib_struct', {}).get('ext', []) + if _calib_valid(calib_ext): + results = layer_correct(results, calib_ext, layeruse, settings.get('cableType', 0)) + + tolchkactive = chk_tolchksettings(settings.get('tolchk', {})) + if not tolchkactive: + results = plausi2000(results, settings['StartX2Ana'].get('avgresults', {}), settings) + + if settings['StartX8Ana'][sp].get('init', 1) == 1: + eval_axis = 2 + else: + eval_axis = axis + + avgmem = settings['StartX2Ana'].get('avgmem', {}) + + def _true_st_empty(avgmem, path): + node = avgmem + for key in path: + if not isinstance(node, dict) or key not in node: + return True + node = node[key] + if isinstance(node, np.ndarray): + return node.size == 0 + if isinstance(node, list): + return len(node) == 0 + return not node + + if axis and avgmem and _true_st_empty(avgmem, ['dm', 'x', 'true_st']): + in_struct = {} + in_struct['startup_percent'] = 0 + in_struct['loop'] = [] + in_struct['xold'] = [] + in_struct['yold'] = [] + in_struct['xstold'] = [] + in_struct['ystold'] = [] + in_struct['true_st'] = [] + in_struct['oldsinglestatus'] = [] + + avgmem['dm']['x'] = in_struct.copy() + if 'eightPT' not in avgmem: + avgmem['eightPT'] = {} + if 'dm' not in avgmem['eightPT']: + avgmem['eightPT']['dm'] = {} + avgmem['eightPT']['dm']['x'] = in_struct.copy() + avgmem['left']['osc']['x'] = in_struct.copy() + avgmem['right']['osc']['x'] = in_struct.copy() + if 'eightPT' not in avgmem['left']: + avgmem['left']['eightPT'] = {} + avgmem['eightPT']['left']['osc']['x'] = in_struct.copy() + avgmem['eightPT']['right']['osc']['x'] = in_struct.copy() + avgmem['left']['isc']['x'] = in_struct.copy() + avgmem['right']['isc']['x'] = in_struct.copy() + avgmem['eightPT']['left']['isc']['x'] = in_struct.copy() + avgmem['eightPT']['right']['isc']['x'] = in_struct.copy() + avgmem['left']['iso']['x'] = in_struct.copy() + avgmem['right']['iso']['x'] = in_struct.copy() + avgmem['eightPT']['left']['iso']['x'] = in_struct.copy() + avgmem['eightPT']['right']['iso']['x'] = in_struct.copy() + avgmem['left']['wth']['x'] = in_struct.copy() + avgmem['right']['wth']['x'] = in_struct.copy() + avgmem['eightPT']['left']['wth']['x'] = in_struct.copy() + avgmem['eightPT']['right']['wth']['x'] = in_struct.copy() + elif (not axis) and avgmem and _true_st_empty(avgmem, ['dm', 'y', 'true_st']): + in_struct = {} + in_struct['startup_percent'] = 0 + in_struct['loop'] = [] + in_struct['xold'] = [] + in_struct['yold'] = [] + in_struct['xstold'] = [] + in_struct['ystold'] = [] + in_struct['true_st'] = [] + in_struct['oldsinglestatus'] = [] + + avgmem['dm']['y'] = in_struct.copy() + if 'eightPT' not in avgmem: + avgmem['eightPT'] = {} + if 'dm' not in avgmem['eightPT']: + avgmem['eightPT']['dm'] = {} + avgmem['eightPT']['dm']['y'] = in_struct.copy() + avgmem['left']['osc']['y'] = in_struct.copy() + avgmem['right']['osc']['y'] = in_struct.copy() + avgmem['eightPT']['left']['osc']['y'] = in_struct.copy() + avgmem['eightPT']['right']['osc']['y'] = in_struct.copy() + avgmem['left']['isc']['y'] = in_struct.copy() + avgmem['right']['isc']['y'] = in_struct.copy() + avgmem['eightPT']['left']['isc']['y'] = in_struct.copy() + avgmem['eightPT']['right']['isc']['y'] = in_struct.copy() + avgmem['left']['iso']['y'] = in_struct.copy() + avgmem['right']['iso']['y'] = in_struct.copy() + avgmem['eightPT']['left']['iso']['y'] = in_struct.copy() + avgmem['eightPT']['right']['iso']['y'] = in_struct.copy() + avgmem['left']['wth']['y'] = in_struct.copy() + avgmem['right']['wth']['y'] = in_struct.copy() + avgmem['eightPT']['left']['wth']['y'] = in_struct.copy() + avgmem['eightPT']['right']['wth']['y'] = in_struct.copy() + + if avgmem.get('right', {}).get('osc', {}).get('x'): + x = avgmem['right']['osc']['x'] + avgresults_tmp, avgmem_tmp = avg_mval(results, settings.get('avgData', {}), avgmem, eval_axis, settings.get('cableType', 0), err_meas_head) + + if 'eightPT' not in avgmem: + avgmem['eightPT'] = _auto_dict() + if axis and avgmem.get('eightPT') and _true_st_empty(avgmem, ['eightPT', 'dm', 'x', 'true_st']): + in_struct = {} + in_struct['startup_percent'] = 0 + in_struct['loop'] = [] + in_struct['xold'] = [] + in_struct['yold'] = [] + in_struct['xstold'] = [] + in_struct['ystold'] = [] + in_struct['true_st'] = [] + in_struct['oldsinglestatus'] = [] + + avgmem['eightPT']['dm']['x'] = in_struct.copy() + if 'eightPT' not in avgmem['eightPT']: + avgmem['eightPT']['eightPT'] = _auto_dict() + if 'dm' not in avgmem['eightPT']['eightPT']: + avgmem['eightPT']['eightPT']['dm'] = _auto_dict() + avgmem['eightPT']['eightPT']['dm']['x'] = in_struct.copy() + avgmem['eightPT']['left']['osc']['x'] = in_struct.copy() + avgmem['eightPT']['right']['osc']['x'] = in_struct.copy() + avgmem['eightPT']['eightPT']['left']['osc']['x'] = in_struct.copy() + avgmem['eightPT']['eightPT']['right']['osc']['x'] = in_struct.copy() + avgmem['eightPT']['left']['isc']['x'] = in_struct.copy() + avgmem['eightPT']['right']['isc']['x'] = in_struct.copy() + avgmem['eightPT']['eightPT']['left']['isc']['x'] = in_struct.copy() + avgmem['eightPT']['eightPT']['right']['isc']['x'] = in_struct.copy() + avgmem['eightPT']['left']['iso']['x'] = in_struct.copy() + avgmem['eightPT']['right']['iso']['x'] = in_struct.copy() + avgmem['eightPT']['eightPT']['left']['iso']['x'] = in_struct.copy() + avgmem['eightPT']['eightPT']['right']['iso']['x'] = in_struct.copy() + avgmem['eightPT']['left']['wth']['x'] = in_struct.copy() + avgmem['eightPT']['right']['wth']['x'] = in_struct.copy() + avgmem['eightPT']['eightPT']['left']['wth']['x'] = in_struct.copy() + avgmem['eightPT']['eightPT']['right']['wth']['x'] = in_struct.copy() + elif (not axis) and avgmem.get('eightPT') and _true_st_empty(avgmem, ['eightPT', 'dm', 'y', 'true_st']): + in_struct = {} + in_struct['startup_percent'] = 0 + in_struct['loop'] = [] + in_struct['xold'] = [] + in_struct['yold'] = [] + in_struct['xstold'] = [] + in_struct['ystold'] = [] + in_struct['true_st'] = [] + in_struct['oldsinglestatus'] = [] + + avgmem['eightPT']['dm']['y'] = in_struct.copy() + if 'eightPT' not in avgmem['eightPT']: + avgmem['eightPT']['eightPT'] = _auto_dict() + if 'dm' not in avgmem['eightPT']['eightPT']: + avgmem['eightPT']['eightPT']['dm'] = _auto_dict() + avgmem['eightPT']['eightPT']['dm']['y'] = in_struct.copy() + avgmem['eightPT']['left']['osc']['y'] = in_struct.copy() + avgmem['eightPT']['right']['osc']['y'] = in_struct.copy() + avgmem['eightPT']['eightPT']['left']['osc']['y'] = in_struct.copy() + avgmem['eightPT']['eightPT']['right']['osc']['y'] = in_struct.copy() + avgmem['eightPT']['left']['isc']['y'] = in_struct.copy() + avgmem['eightPT']['right']['isc']['y'] = in_struct.copy() + avgmem['eightPT']['eightPT']['left']['isc']['y'] = in_struct.copy() + avgmem['eightPT']['eightPT']['right']['isc']['y'] = in_struct.copy() + avgmem['eightPT']['left']['iso']['y'] = in_struct.copy() + avgmem['eightPT']['right']['iso']['y'] = in_struct.copy() + avgmem['eightPT']['eightPT']['left']['iso']['y'] = in_struct.copy() + avgmem['eightPT']['eightPT']['right']['iso']['y'] = in_struct.copy() + avgmem['eightPT']['left']['wth']['y'] = in_struct.copy() + avgmem['eightPT']['right']['wth']['y'] = in_struct.copy() + avgmem['eightPT']['eightPT']['left']['wth']['y'] = in_struct.copy() + avgmem['eightPT']['eightPT']['right']['wth']['y'] = in_struct.copy() + + eightPT_avgmem = avgmem.get('eightPT', {}) + eightPT_res, eightPT_mem = avg_mval_8pt(results, settings.get('avgData', {}), eightPT_avgmem, eval_axis, settings.get('cableType', 0), err_meas_head) + avgresults_tmp['eightPT'] = eightPT_res + avgmem_tmp['eightPT'] = eightPT_mem + + if (settings.get('cableType', 0) == 62 or settings.get('cableType', 0) == 63) and (settings.get('dm_laser_core') is None or len(settings.get('dm_laser_core', [])) == 0 or settings.get('dm_laser_core', 0) <= 0): + if axis == 1: + avgresults_tmp['left']['osc'][1, 0] = results['coreDm'][1, 0] + avgresults_tmp['right']['osc'][1, 0] = results['coreDm'][1, 0] + avgresults_tmp['left']['wth'][1, 0] = results['coreDm'][1, 0] + avgresults_tmp['right']['wth'][1, 0] = results['coreDm'][1, 0] + + avgresults_tmp['eightPT']['left']['osc'][1, 0] = results['coreDm'][1, 0] + avgresults_tmp['eightPT']['right']['osc'][1, 0] = results['coreDm'][1, 0] + avgresults_tmp['eightPT']['left']['wth'][1, 0] = results['coreDm'][1, 0] + avgresults_tmp['eightPT']['right']['wth'][1, 0] = results['coreDm'][1, 0] + elif axis == 0: + avgresults_tmp['left']['osc'][1, 1] = results['coreDm'][1, 1] + avgresults_tmp['right']['osc'][1, 1] = results['coreDm'][1, 1] + avgresults_tmp['left']['wth'][1, 1] = results['coreDm'][1, 1] + avgresults_tmp['right']['wth'][1, 1] = results['coreDm'][1, 1] + + avgresults_tmp['eightPT']['left']['osc'][1, 1] = results['coreDm'][1, 1] + avgresults_tmp['eightPT']['right']['osc'][1, 1] = results['coreDm'][1, 1] + avgresults_tmp['eightPT']['left']['wth'][1, 1] = results['coreDm'][1, 1] + avgresults_tmp['eightPT']['right']['wth'][1, 1] = results['coreDm'][1, 1] + + if settings['StartX8Ana'][sp].get('init', 1) == 1: + avgresults = avgresults_tmp + avgmem = avgmem_tmp + settings['StartX8Ana'][sp]['init'] = 0 + else: + avgresults = settings['StartX2Ana'].get('avgresults', {}) + avgmem = settings['StartX2Ana'].get('avgmem', {}) + if axis == 1: + avgresults['dmOut'][:, 0] = avgresults_tmp['dmOut'][:, 0] + avgresults['coreDm'][:, 0] = avgresults_tmp['coreDm'][:, 0] + avgresults['left']['osc'][:, 0] = avgresults_tmp['left']['osc'][:, 0] + avgresults['right']['osc'][:, 0] = avgresults_tmp['right']['osc'][:, 0] + avgresults['left']['isc'][:, 0] = avgresults_tmp['left']['isc'][:, 0] + avgresults['right']['isc'][:, 0] = avgresults_tmp['right']['isc'][:, 0] + avgresults['left']['iso'][:, 0] = avgresults_tmp['left']['iso'][:, 0] + avgresults['right']['iso'][:, 0] = avgresults_tmp['right']['iso'][:, 0] + avgresults['left']['wth'][:, 0] = avgresults_tmp['left']['wth'][:, 0] + avgresults['right']['wth'][:, 0] = avgresults_tmp['right']['wth'][:, 0] + + avgresults['eightPT']['dmOut'][:, 0] = avgresults_tmp['eightPT']['dmOut'][:, 0] + avgresults['eightPT']['coreDm'][:, 0] = avgresults_tmp['eightPT']['coreDm'][:, 0] + avgresults['eightPT']['left']['osc'][:, 0] = avgresults_tmp['eightPT']['left']['osc'][:, 0] + avgresults['eightPT']['right']['osc'][:, 0] = avgresults_tmp['eightPT']['right']['osc'][:, 0] + avgresults['eightPT']['left']['isc'][:, 0] = avgresults_tmp['eightPT']['left']['isc'][:, 0] + avgresults['eightPT']['right']['isc'][:, 0] = avgresults_tmp['eightPT']['right']['isc'][:, 0] + avgresults['eightPT']['left']['iso'][:, 0] = avgresults_tmp['eightPT']['left']['iso'][:, 0] + avgresults['eightPT']['right']['iso'][:, 0] = avgresults_tmp['eightPT']['right']['iso'][:, 0] + avgresults['eightPT']['left']['wth'][:, 0] = avgresults_tmp['eightPT']['left']['wth'][:, 0] + avgresults['eightPT']['right']['wth'][:, 0] = avgresults_tmp['eightPT']['right']['wth'][:, 0] + + avgmem['dm']['x'] = avgmem_tmp['dm']['x'] + avgmem['left']['osc']['x'] = avgmem_tmp['left']['osc']['x'] + avgmem['left']['isc']['x'] = avgmem_tmp['left']['isc']['x'] + avgmem['left']['iso']['x'] = avgmem_tmp['left']['iso']['x'] + avgmem['left']['wth']['x'] = avgmem_tmp['left']['wth']['x'] + avgmem['right']['osc']['x'] = avgmem_tmp['right']['osc']['x'] + avgmem['right']['isc']['x'] = avgmem_tmp['right']['isc']['x'] + avgmem['right']['iso']['x'] = avgmem_tmp['right']['iso']['x'] + avgmem['right']['wth']['x'] = avgmem_tmp['right']['wth']['x'] + + avgmem['eightPT']['dm']['x'] = avgmem_tmp['eightPT']['dm']['x'] + avgmem['eightPT']['left']['osc']['x'] = avgmem_tmp['eightPT']['left']['osc']['x'] + avgmem['eightPT']['left']['isc']['x'] = avgmem_tmp['eightPT']['left']['isc']['x'] + avgmem['eightPT']['left']['iso']['x'] = avgmem_tmp['eightPT']['left']['iso']['x'] + avgmem['eightPT']['left']['wth']['x'] = avgmem_tmp['eightPT']['left']['wth']['x'] + avgmem['eightPT']['right']['osc']['x'] = avgmem_tmp['eightPT']['right']['osc']['x'] + avgmem['eightPT']['right']['isc']['x'] = avgmem_tmp['eightPT']['right']['isc']['x'] + avgmem['eightPT']['right']['iso']['x'] = avgmem_tmp['eightPT']['right']['iso']['x'] + avgmem['eightPT']['right']['wth']['x'] = avgmem_tmp['eightPT']['right']['wth']['x'] + elif axis == 0: + avgresults['dmOut'][:, 1] = avgresults_tmp['dmOut'][:, 1] + avgresults['coreDm'][:, 1] = avgresults_tmp['coreDm'][:, 1] + avgresults['left']['osc'][:, 1] = avgresults_tmp['left']['osc'][:, 1] + avgresults['right']['osc'][:, 1] = avgresults_tmp['right']['osc'][:, 1] + avgresults['left']['isc'][:, 1] = avgresults_tmp['left']['isc'][:, 1] + avgresults['right']['isc'][:, 1] = avgresults_tmp['right']['isc'][:, 1] + avgresults['left']['iso'][:, 1] = avgresults_tmp['left']['iso'][:, 1] + avgresults['right']['iso'][:, 1] = avgresults_tmp['right']['iso'][:, 1] + avgresults['left']['wth'][:, 1] = avgresults_tmp['left']['wth'][:, 1] + avgresults['right']['wth'][:, 1] = avgresults_tmp['right']['wth'][:, 1] + + avgresults['eightPT']['dmOut'][:, 1] = avgresults_tmp['eightPT']['dmOut'][:, 1] + avgresults['eightPT']['coreDm'][:, 1] = avgresults_tmp['eightPT']['coreDm'][:, 1] + avgresults['eightPT']['left']['osc'][:, 1] = avgresults_tmp['eightPT']['left']['osc'][:, 1] + avgresults['eightPT']['right']['osc'][:, 1] = avgresults_tmp['eightPT']['right']['osc'][:, 1] + avgresults['eightPT']['left']['isc'][:, 1] = avgresults_tmp['eightPT']['left']['isc'][:, 1] + avgresults['eightPT']['right']['isc'][:, 1] = avgresults_tmp['eightPT']['right']['isc'][:, 1] + avgresults['eightPT']['left']['iso'][:, 1] = avgresults_tmp['eightPT']['left']['iso'][:, 1] + avgresults['eightPT']['right']['iso'][:, 1] = avgresults_tmp['eightPT']['right']['iso'][:, 1] + avgresults['eightPT']['left']['wth'][:, 1] = avgresults_tmp['eightPT']['left']['wth'][:, 1] + avgresults['eightPT']['right']['wth'][:, 1] = avgresults_tmp['eightPT']['right']['wth'][:, 1] + + avgmem['dm']['y'] = avgmem_tmp['dm']['y'] + avgmem['left']['osc']['y'] = avgmem_tmp['left']['osc']['y'] + avgmem['left']['isc']['y'] = avgmem_tmp['left']['isc']['y'] + avgmem['left']['iso']['y'] = avgmem_tmp['left']['iso']['y'] + avgmem['left']['wth']['y'] = avgmem_tmp['left']['wth']['y'] + avgmem['right']['osc']['y'] = avgmem_tmp['right']['osc']['y'] + avgmem['right']['isc']['y'] = avgmem_tmp['right']['isc']['y'] + avgmem['right']['iso']['y'] = avgmem_tmp['right']['iso']['y'] + avgmem['right']['wth']['y'] = avgmem_tmp['right']['wth']['y'] + + avgmem['eightPT']['dm']['y'] = avgmem_tmp['eightPT']['dm']['y'] + avgmem['eightPT']['left']['osc']['y'] = avgmem_tmp['eightPT']['left']['osc']['y'] + avgmem['eightPT']['left']['isc']['y'] = avgmem_tmp['eightPT']['left']['isc']['y'] + avgmem['eightPT']['left']['iso']['y'] = avgmem_tmp['eightPT']['left']['iso']['y'] + avgmem['eightPT']['left']['wth']['y'] = avgmem_tmp['eightPT']['left']['wth']['y'] + avgmem['eightPT']['right']['osc']['y'] = avgmem_tmp['eightPT']['right']['osc']['y'] + avgmem['eightPT']['right']['isc']['y'] = avgmem_tmp['eightPT']['right']['isc']['y'] + avgmem['eightPT']['right']['iso']['y'] = avgmem_tmp['eightPT']['right']['iso']['y'] + avgmem['eightPT']['right']['wth']['y'] = avgmem_tmp['eightPT']['right']['wth']['y'] + + if settings.get('cableType', 0) == 53: + avgresults['coreDm'][0, 0:2] = 0 + avgresults['coreDm'][1, 0:2] = 45 + avgresults['coreDm'][2, 0:2] = 0 + + avgresults['eightPT']['coreDm'][0, 0:2] = 0 + avgresults['eightPT']['coreDm'][1, 0:2] = 45 + avgresults['eightPT']['coreDm'][2, 0:2] = 0 + + avgmem_x = avgmem.get('left', {}).get('wth', {}).get('x', {}) + avgmem_y = avgmem.get('left', {}).get('wth', {}).get('y', {}) + avgmem_rx = avgmem.get('right', {}).get('wth', {}).get('x', {}) + avgmem_ry = avgmem.get('right', {}).get('wth', {}).get('y', {}) + if (avgmem and avgresults and + isinstance(avgmem_x, dict) and 'xold' in avgmem_x and isinstance(avgmem_x['xold'], np.ndarray) and avgmem_x['xold'].size > 0 and + isinstance(avgmem_y, dict) and 'xold' in avgmem_y and isinstance(avgmem_y['xold'], np.ndarray) and avgmem_y['xold'].size > 0 and + isinstance(avgmem_rx, dict) and 'xold' in avgmem_rx and isinstance(avgmem_rx['xold'], np.ndarray) and avgmem_rx['xold'].size > 0 and + isinstance(avgmem_ry, dict) and 'xold' in avgmem_ry and isinstance(avgmem_ry['xold'], np.ndarray) and avgmem_ry['xold'].size > 0 and + 'paraECClimit' in settings and settings['paraECClimit'] > 1 and 'paraECCmin' in settings): + + ECCnx = (results['left']['wth'][0, 0] - results['right']['wth'][0, 0]) / (results['left']['wth'][0, 0] + results['right']['wth'][0, 0]) + ECCny = (results['left']['wth'][0, 1] - results['right']['wth'][0, 1]) / (results['left']['wth'][0, 1] + results['right']['wth'][0, 1]) + + ECCnxold = (avgmem['left']['wth']['x']['xold'][0, 0] - avgmem['right']['wth']['x']['xold'][0, 0]) / (avgmem['left']['wth']['x']['xold'][0, 0] + avgmem['right']['wth']['x']['xold'][0, 0]) + ECCnyold = (avgmem['left']['wth']['y']['xold'][0, 0] - avgmem['right']['wth']['y']['xold'][0, 0]) / (avgmem['left']['wth']['y']['xold'][0, 0] + avgmem['right']['wth']['y']['xold'][0, 0]) + + ECCnxmold = (avgresults['left']['wth'][0, 0] - avgresults['right']['wth'][0, 0]) / (avgresults['left']['wth'][0, 0] + avgresults['right']['wth'][0, 0]) + ECCnymold = (avgresults['left']['wth'][0, 1] - avgresults['right']['wth'][0, 1]) / (avgresults['left']['wth'][0, 1] + avgresults['right']['wth'][0, 1]) + + if ECCnxmold and (abs(ECCnx) >= abs(ECCnxmold * settings['paraECClimit'])) and axis == 1 and (abs(np.diff([ECCnx, ECCnxmold])) >= settings['paraECCmin']): + results['left']['wth'][2, 0] = 101 + results['right']['wth'][2, 0] = 101 + avgresults['left']['wth'][2, 0] = 101 + avgresults['right']['wth'][2, 0] = 101 + avgresults['eightPT']['left']['wth'][2, 0] = 101 + avgresults['eightPT']['right']['wth'][2, 0] = 101 + if ECCnymold and (abs(ECCny) >= abs(ECCnymold * settings['paraECClimit'])) and axis == 0 and (abs(np.diff([ECCny, ECCnymold])) >= settings['paraECCmin']): + results['left']['wth'][2, 1] = 101 + results['right']['wth'][2, 1] = 101 + avgresults['left']['wth'][2, 1] = 101 + avgresults['right']['wth'][2, 1] = 101 + avgresults['eightPT']['left']['wth'][2, 1] = 101 + avgresults['eightPT']['right']['wth'][2, 1] = 101 + + avgresults = plausi_layer(avgresults, settings) + + + settings['StartX2Ana']['avgresults'] = avgresults + settings['StartX2Ana']['avgmem'] = avgmem + settings['StartX2Ana']['results'] = resultsAll + + AttCoeff = [] + AttCoeffSt = [] + Void = [] + AutoDet = np.zeros(4) + + return (avgresults, results, edges, status, att, err, layeruse, + AttCoeff, AttCoeffSt, Void, AutoDet, ScanWay, + NormVideoX, NormVideoY, detail_a, detail_b) diff --git a/algorithm/reconstr_utils.py b/algorithm/reconstr_utils.py new file mode 100644 index 0000000..ef2f680 --- /dev/null +++ b/algorithm/reconstr_utils.py @@ -0,0 +1,346 @@ +import numpy as np +from scipy.signal import butter, filtfilt + +try: + from .math_utils import equal, lininter + from .edge_detection_utils import i0detect + from .filtering_utils import hendfilt +except ImportError: + from math_utils import equal, lininter + from edge_detection_utils import i0detect + from filtering_utils import hendfilt + + +SCAN_LENGTH_NE_ERROR = 20 +VIB_DETECT_ERROR = 24 +RECON_ERROR = 24 + + +def _timtab1(INf, pegel, count, dt, minpegel, errorlevel): + print("暂不支持: timtab1") + return np.array([]), errorlevel + + +def _speed2(Timetaba, Timetabb, Tab2, Sensab, Anzpara, + Mustsperr, pegel_i, NTimetaba, NTimetabb, Tab2ind, errorlevel): + print("暂不支持: speed2") + return Tab2, Tab2ind, NTimetaba, NTimetabb, errorlevel + + +def _materw2(Tab2, Sensab): + print("暂不支持: materw2") + return Tab2 + + +def _vfunc(Tab2, Anzpara, dt, vscan, Sensab, reconstruct, t): + print("暂不支持: vfunc") + return np.zeros(5), np.zeros((2, 1)), 0 + + +def _pause3(): + pass + + +def pegeldef(INfa, reconstruct, errorlevel): + minpegel2 = np.min(INfa) + reconstruct['offminpeg'] + if minpegel2 > reconstruct['minpegel']: + m = (reconstruct['deltapegel1'] - reconstruct['deltapegel2']) / \ + (reconstruct['pegelanf'] - reconstruct['minpegel']) + reconstruct['deltapegel2'] = m * minpegel2 - m * reconstruct['minpegel'] + reconstruct['deltapegel2'] + reconstruct['minpegel'] = minpegel2 + + startindex_arr = np.where(INfa < reconstruct['maxpegel'])[0] + startindex = startindex_arr[0] if len(startindex_arr) > 0 else None + stopindex = startindex_arr[-1] if len(startindex_arr) > 0 else None + + if startindex is not None and stopindex is not None and startindex < stopindex: + seg = INfa[startindex:stopindex + 1] + diff_seg = np.diff(seg) + medpegel_l_index = np.argmin(diff_seg) + medpegel_l_wert = seg[medpegel_l_index] + medpegel_r_index = np.argmax(diff_seg) + medpegel_r_wert = seg[medpegel_r_index] + + medpegel = (medpegel_l_wert + medpegel_r_wert) / 2.0 + + anz1 = int(reconstruct['anzpegel1']) + log_start = np.log(reconstruct['pegelanf']) + log_end = np.log(medpegel / reconstruct['pegelanf']) + log_step = log_end / (anz1 - 1) + tmp_pegel2 = np.exp(np.arange(log_start, log_start + log_step * anz1, log_step)) + if len(tmp_pegel2) != anz1: + tmp_pegel2 = np.concatenate([tmp_pegel2, [tmp_pegel2[-1] - np.diff(tmp_pegel2[-2:])[0]]]) + pegel = np.zeros(anz1 + int(reconstruct['anzpegel2'])) + pegel[:anz1] = tmp_pegel2[:anz1] + + anz2 = int(reconstruct['anzpegel2']) + log_start2 = np.log(medpegel) + log_end2 = np.log(reconstruct['minpegel'] / medpegel) + log_step2 = log_end2 / anz2 + tmp_pegel = np.exp(np.arange(log_start2, log_start2 + log_step2 * (anz2 + 1), log_step2)) + if len(tmp_pegel) == anz2 + 1: + tmp_pegel = tmp_pegel[1:] + pegel[anz1:anz1 + anz2] = tmp_pegel[:anz2] + else: + pegel = np.array([]) + errorlevel[0, 0] = 14 + + return pegel, errorlevel + + +def recon(INa, INb, v, dt): + counta = len(v) + x = np.zeros(counta) + x[0] = dt * v[0] + for i in range(1, counta): + x[i] = x[i - 1] + dt * v[i] + + Index = np.argsort(x) + xr = x[Index] + INar = np.zeros(counta) + INbr = np.zeros(counta) + for i in range(counta): + INar[i] = INa[Index[i]] + INbr[i] = INb[Index[i]] + return INar, INbr, xr + + +def unist(INar, INbr, xr, dx): + counta = len(xr) + k = 0 + Ia1 = np.zeros(counta) + Ib1 = np.zeros(counta) + x1 = np.zeros(counta) + Ia1[0] = INar[0] + Ib1[0] = INbr[0] + x1[0] = xr[0] + for i in range(1, counta): + if abs(xr[i] - x1[k]) < 1e-7: + Ia1[k] = (Ia1[k] + INar[i]) / 2.0 + Ib1[k] = (Ib1[k] + INbr[i]) / 2.0 + else: + k = k + 1 + Ia1[k] = INar[i] + Ib1[k] = INbr[i] + x1[k] = xr[i] + + x = np.arange(x1[0] + dx, x1[k] - dx + dx, dx) + + INa = lininter(x1[:k + 1], Ia1[:k + 1], x) + INb = lininter(x1[:k + 1], Ib1[:k + 1], x) + return INa, INb, x + + +def reconstr(x_data, y_data, settings, errorin): + Ia = np.asarray(x_data, dtype=np.float64).ravel() + Ib = np.asarray(y_data, dtype=np.float64).ravel() + errorin = np.asarray(errorin, dtype=np.float64).reshape(-1, 1) + if errorin.shape[0] < 2: + errorin = np.pad(errorin, ((0, 2 - errorin.shape[0]), (0, 0))) + + confData = settings.get('confData', np.array([])) + + def _conf(idx): + return confData[idx - 1] if len(confData) >= idx else 0.0 + + dt = _conf(31) + vscan = _conf(32) + dx = vscan * dt + + if equal(_conf(14), 1): + if equal(_conf(7), 0): + Sensab = _conf(33) + else: + Sensab = _conf(7) + else: + if equal(_conf(8), 0): + Sensab = _conf(33) + else: + Sensab = _conf(8) + + DistI0 = _conf(35) + Dist01 = _conf(36) + Lowrad = _conf(37) + + reconstruct = {} + reconstruct['pegelanf'] = 0.94 + reconstruct['deltapegel1'] = 0.002 + reconstruct['deltapegel2'] = 0.0005 + reconstruct['minpegel'] = 0.01 + reconstruct['maxpegel'] = 0.9 + reconstruct['fgv'] = vscan / Sensab * 1.9 + reconstruct['ord'] = 2 + reconstruct['deltt'] = 0.005 + reconstruct['maxt'] = 0.75 + reconstruct['deltatstep'] = 0.1 + reconstruct['deltat'] = 0.1 + reconstruct['deltav'] = 0.1 + reconstruct['verhtmitt'] = 4 + reconstruct['deltv'] = 70 + reconstruct['maxv'] = vscan + reconstruct['deltv'] + reconstruct['minv'] = vscan - reconstruct['deltv'] + reconstruct['Funkt'] = 0 + reconstruct['verlt'] = 0.02 + reconstruct['fgvscan'] = 70 + reconstruct['ordscan'] = 2 + reconstruct['Anzfilt'] = 1 + reconstruct['Mustsperr'] = 0 + reconstruct['pegdiff'] = 0.03 + reconstruct['tdiff'] = 0.05 + reconstruct['offminpeg'] = 0.05 + reconstruct['anzpegel1'] = 450 + reconstruct['anzpegel2'] = 50 + reconstruct['r_squared_min'] = 0.85 + reconstruct['r_squared_vib'] = 0.55 + reconstruct['minproz'] = 0.04 + reconstruct['defproz'] = 0.2 + reconstruct['active'] = settings.get('Reconstruct', 0) + reconstruct['minamp'] = 0.5 + reconstruct['maxamp'] = 2.5 + reconstruct['minfreq'] = 0.1 + reconstruct['maxfreq'] = 12.0 + reconstruct['vibwarning'] = settings.get('vibwarning', 0) + + vibration_detected = 0 + + Ic = Ia.copy() + Ia = Ib.copy() + Ib = Ic.copy() + + errorlevel = np.zeros((2, 1), dtype=np.float64) + + Anzpara = _conf(11) + + counta = len(Ia) + countb = len(Ib) + if counta != countb: + errorlevel[0, 0] = SCAN_LENGTH_NE_ERROR + + INa = 0 + INb = 0 + + I0a, errorlevel_1d = i0detect(Ia, DistI0, dx, Lowrad, errorin.ravel()) + errorlevel[:, 0] = errorlevel_1d[:2] + if errorlevel.shape[0] < 2: + errorlevel = np.pad(errorlevel, ((0, 2 - errorlevel.shape[0]), (0, 0))) + + I0b, errorlevel_1d = i0detect(Ib, DistI0, dx, Lowrad, errorin.ravel()) + errorlevel_tmp = errorlevel_1d[:2] + for i in range(min(2, len(errorlevel_tmp))): + if errorlevel_tmp[i] != 0 and errorlevel[i, 0] == 0: + errorlevel[i, 0] = errorlevel_tmp[i] + + if (errorlevel[0, 0] == 0) and ((Ia[-1] / I0a < reconstruct['maxpegel']) or (Ib[-1] / I0b < reconstruct['maxpegel'])): + errorlevel[1, 0] = 10 + + if (errorlevel[0, 0] == 0) and (errorlevel[1, 0] != 10): + INa = Ia / I0a + INb = Ib / I0b + + INaorig = INa.copy() + INborig = INb.copy() + t_arr = np.arange(1, counta + 1) + t_arr = (t_arr - 1) * dt + + fgn = 2 * reconstruct['fgvscan'] * dt * (vscan / 26.0) + + BFilt, AFilt = butter(int(round(reconstruct['ordscan'])), fgn) + + INfa = filtfilt(BFilt, AFilt, INa) + INfb = filtfilt(BFilt, AFilt, INb) + + pegel, errorlevel = pegeldef(INfa, reconstruct, errorlevel) + + if Anzpara > 0: + pass + + if errorlevel[0, 0] == 0: + Timetaba, errorlevel = _timtab1(INfa, pegel, counta, dt, + reconstruct['minpegel'], errorlevel) + + if errorlevel[0, 0] == 0: + Timetabb, errorlevel = _timtab1(INfb, pegel, countb, dt, + reconstruct['minpegel'], errorlevel) + if errorlevel[0, 0] == 0: + Tab2ind = 0 + Npegel = len(pegel) + NTimetaba = len(Timetaba) + NTimetabb = len(Timetabb) + Tab2size = 5000 + Tab2 = np.zeros((5, Tab2size)) + for i in range(Npegel): + if NTimetaba > 0 and NTimetabb > 0: + Tab2, Tab2ind, NTimetaba, NTimetabb, errorlevel = _speed2( + Timetaba, Timetabb, Tab2, Sensab, Anzpara, + reconstruct['Mustsperr'], pegel[i], NTimetaba, + NTimetabb, Tab2ind, errorlevel) + + if (Tab2ind) < Tab2size: + Tab2 = Tab2[:, :Tab2ind] + else: + print(f'Arraysize Tab2 too low: modul speed; size: {Tab2.shape}') + errorlevel[0, 0] = RECON_ERROR + INa = Ia * I0a + INb = Ib * I0b + return y_data, x_data, errorlevel, vibration_detected + + if errorlevel[0, 0] == 0: + if not equal(reconstruct['pegdiff'], 0): + Tab2 = hendfilt(Tab2, reconstruct['pegdiff'], reconstruct['tdiff']) + + Tab2 = _materw2(Tab2, Sensab) + + index = np.array([0]) + while len(index) > 0: + diff_tab6 = np.diff(Tab2[5, :]) if Tab2.shape[0] > 5 else np.array([]) + index = np.where(diff_tab6 == 0)[0] + + if len(index) > 0: + idx = index[0] + Tab2[:, idx] = (Tab2[:, idx] + Tab2[:, idx + 1]) / 2.0 + Tab2 = np.delete(Tab2, idx + 1, axis=1) + + v, errorv, vibration_detected = _vfunc( + Tab2, Anzpara, dt, vscan, Sensab, reconstruct, t_arr) + + if vibration_detected: + try: + vibdir = 'C:\\XRAYDATA\\vibdata\\' + import os + if not os.path.exists(vibdir): + os.makedirs(vibdir) + + liste = os.listdir(vibdir) + if len(liste) > 1000: + try: + full_paths = [os.path.join(vibdir, f) for f in liste] + full_paths.sort(key=lambda p: os.path.getmtime(p)) + if len(full_paths) > 0: + os.remove(full_paths[0]) + except Exception: + pass + except Exception: + pass + + if (errorv[0, 0] == 0) and (reconstruct['active'] > 1) and vibration_detected: + INa, INb, xr = recon(INa, INb, v, dt) + INa, INb, xr = unist(INa, INb, xr, dx) + + if Anzpara > 0: + pass + + errorlevel = errorv.copy() + else: + if vibration_detected and errorv[0, 0] and not errorin[0, 0]: + errorlevel[0, 0] = errorv[0, 0] + else: + errorlevel[0, 0] = errorin[0, 0] + errorlevel[1, 0] = errorv[1, 0] if len(errorv) > 1 else errorlevel[1, 0] + + INa = INa * I0a + INb = INb * I0b + else: + INa = Ia.copy() + INb = Ib.copy() + + return INb, INa, errorlevel, vibration_detected diff --git a/algorithm/requirements.txt b/algorithm/requirements.txt new file mode 100644 index 0000000..3b2eb15 --- /dev/null +++ b/algorithm/requirements.txt @@ -0,0 +1,2 @@ +numpy==2.4.1 +scipy==1.17.1 diff --git a/algorithm/signal_utils.py b/algorithm/signal_utils.py new file mode 100644 index 0000000..e69edd6 --- /dev/null +++ b/algorithm/signal_utils.py @@ -0,0 +1,383 @@ +import numpy as np + +try: + from .validation_utils import limit +except ImportError: + from validation_utils import limit + + +def _lfilter(b, a, x, zi=None): + b = np.asarray(b, dtype=np.float64) + a = np.asarray(a, dtype=np.float64) + x = np.asarray(x, dtype=np.float64) + if a[0] != 1.0: + b = b / a[0] + a = a / a[0] + nb = len(b) + na = len(a) + n = max(nb, na) + if nb < n: + b = np.pad(b, (0, n - nb)) + if na < n: + a = np.pad(a, (0, n - na)) + y = np.zeros_like(x) + if zi is None: + zi = np.zeros(n - 1) + else: + zi = np.asarray(zi, dtype=np.float64).copy() + for i in range(len(x)): + xi = x[i] + yi = b[0] * xi + zi[0] + for j in range(n - 2): + zi[j] = b[j + 1] * xi + zi[j + 1] - a[j + 1] * yi + zi[n - 2] = b[n - 1] * xi - a[n - 1] * yi + y[i] = yi + if zi is not None and len(zi) > 0: + return y, zi + return y + + +def filter2k3(filtpara, x, mode=0): + filtpara = np.asarray(filtpara, dtype=np.float64) + x = np.asarray(x, dtype=np.float64) + N2 = int(np.round(0.5 * (len(filtpara) - 1))) + Nx = len(x) + if len(filtpara) > len(x): + return x.copy(), 0 + if mode > 0: + filtpara = filtpara[::-1] + y = np.convolve(x, filtpara, mode='full') + y = np.concatenate([y[N2:Nx], y[:N2]]) + if mode == 2: + y[:N2] = y[N2] + y[-N2:] = y[-N2 - 1] + else: + y[:N2] = x[:N2] + y[Nx - N2:Nx] = x[Nx - N2:Nx] + return y, N2 + + +def fifi(b, a, x): + b = np.asarray(b, dtype=np.float64).ravel() + a = np.asarray(a, dtype=np.float64).ravel() + x = np.asarray(x, dtype=np.float64) + if len(b) == 0 or len(a) == 0 or len(x) == 0: + return np.array([]) + orig_shape = x.shape + if x.ndim > 1 and min(x.shape) > 1: + raise ValueError('Only works for vector input.') + x_flat = x.ravel() + len_x = len(x_flat) + nb = len(b) + na = len(a) + nfilt = max(nb, na) + if nb < nfilt: + b = np.pad(b, (0, nfilt - nb)) + if na < nfilt: + a = np.pad(a, (0, nfilt - na)) + nfact = 3 * (nfilt - 1) + if len_x <= nfact: + raise ValueError('Data must have length more than 3 times filter order.') + zi = np.linalg.solve( + np.eye(nfilt - 1) - np.column_stack([ + -a[1:nfilt], + np.row_stack([np.eye(nfilt - 2), np.zeros(nfilt - 2)]) + ]), + b[1:nfilt] - a[1:nfilt] * b[0] + ) + y_padded = np.concatenate([ + 2 * x_flat[0] - x_flat[nfact:0:-1], + x_flat, + 2 * x_flat[-1] - x_flat[-2:-nfact - 2:-1] + ]) + y_padded, _ = _lfilter(b, a, y_padded, zi=zi * y_padded[0]) + y_padded = y_padded[::-1] + y_padded, _ = _lfilter(b, a, y_padded, zi=zi * y_padded[0]) + y_padded = y_padded[::-1] + y_out = y_padded[nfact:len_x + nfact] + if orig_shape[0] == 1 and x.ndim > 1: + y_out = y_out.reshape(1, -1) + return y_out + + +def dilate1(x, N): + x = np.asarray(x, dtype=np.float64) + y = x.copy() + N = int(np.round(N)) + if N >= 3: + filtvek = np.array([1, 0, 0, 0, 1], dtype=np.float64) + y2, _ = filter2k3(filtvek, y.astype(float)) + y2 = (y2 >= 2) + y = np.logical_or(y.astype(bool), y2).astype(float) + N = 2 + if N == 2: + filtvek = np.array([1, 0, 0, 1, 0], dtype=np.float64) + y2, _ = filter2k3(filtvek, y.astype(float)) + y2 = (y2 >= 2) + y = np.logical_or(y.astype(bool), y2).astype(float) + filtvek = np.array([0, 1, 0, 0, 1], dtype=np.float64) + y2, _ = filter2k3(filtvek, y.astype(float)) + y2 = (y2 >= 2) + y = np.logical_or(y.astype(bool), y2).astype(float) + N = 1 + if N == 1: + filtvek = np.array([1, 0, 1], dtype=np.float64) + y2, _ = filter2k3(filtvek, y.astype(float)) + y2 = (y2 >= 2) + y = np.logical_or(y.astype(bool), y2).astype(float) + return y + + +def videochk(video, errnorm, rawxycount, maxrawxycount, memerror, + minlevel1, maxlevel1, minlevel2, maxlevel2, + errmssmin_start, errmssmax_start, errmssmin_end, errmssmax_end): + errfac = 0.80 + + errnorm = np.atleast_2d(np.asarray(errnorm, dtype=np.float64)) + if errnorm.shape[0] < 2: + errnorm = np.vstack([errnorm, np.zeros((1, errnorm.shape[1]))]) + + video = np.atleast_2d(np.asarray(video, dtype=np.float64)) + + if not errnorm[0, 0] and rawxycount < (maxrawxycount - 2): + sorted_vid = np.sort(video, axis=1)[:, ::-1] + if sorted_vid.shape[1] >= 25: + meanmax = np.mean(sorted_vid[:, 5:25]) + elif sorted_vid.shape[1] > 5: + meanmax = np.mean(sorted_vid[:, 5:]) + else: + meanmax = np.mean(sorted_vid) + + if minlevel1 is not None and len(np.atleast_1d(minlevel1)) > 0 and meanmax < minlevel1: + errnorm[0, 0] = errmssmin_start + if maxlevel1 is not None and len(np.atleast_1d(maxlevel1)) > 0 and meanmax > maxlevel1: + errnorm[0, 0] = errmssmax_start + + elif rawxycount == maxrawxycount - 2 or rawxycount == maxrawxycount - 1 or memerror: + sorted_vid = np.sort(video, axis=1)[:, ::-1] + if sorted_vid.shape[1] >= 25: + meanmax = np.mean(sorted_vid[:, 5:25]) + elif sorted_vid.shape[1] > 5: + meanmax = np.mean(sorted_vid[:, 5:]) + else: + meanmax = np.mean(sorted_vid) + + if minlevel2 is not None and len(np.atleast_1d(minlevel2)) > 0: + if meanmax < minlevel2 * errfac: + if not errnorm[0, 0]: + errnorm[0, 0] = errmssmin_end + memerror = errmssmin_end + elif meanmax < minlevel2: + if not errnorm[1, 0]: + errnorm[1, 0] = errmssmin_end + memerror = errmssmin_end + + if maxlevel2 is not None and len(np.atleast_1d(maxlevel2)) > 0 and meanmax > maxlevel2: + if not errnorm[0, 0]: + errnorm[0, 0] = errmssmax_end + memerror = errmssmax_end + + return errnorm, memerror + + +def scan_norm(in_sig, in0bright, in0darkStatic, in0darkDynamic, dxZeile, gap, videoOffs, + errsettings, mem, init, video_req_time): + mmPixel = 0 + maxrawxycount = 210 + + inbright_minlevel1 = 5000 + inbright_maxlevel1 = 12000 + inbright_minlevel2 = 4000 + inbright_maxlevel2 = 12000 + inbright_too_low = 196 + inbright_too_high = 197 + + raw_minlevel1 = [] + raw_maxlevel1 = 12000 + raw_minlevel2 = [] + raw_maxlevel2 = 12000 + raw_too_low = 194 + raw_too_high = 195 + raw_Contr = 193 + + dark_maxwarnlevel = 5000 + dark_maxerrlevel = 6000 + dark_minerrlevel = 1 + darkdyn_too_low = 198 + darkdyn_too_high = 199 + darkdyntimeout = 600 + + maxdarkdyncount = 2 * darkdyntimeout / video_req_time + + rad_minlevel1 = 5000 + rad_maxlevel1 = [] + rad_minlevel2 = 4000 + rad_maxlevel2 = [] + rad_too_low = 200 + rad_too_high = 195 + + in_sig = np.asarray(in_sig, dtype=np.float64).ravel() + in0bright = np.asarray(in0bright, dtype=np.float64).ravel() + in0darkStatic = np.asarray(in0darkStatic, dtype=np.float64).ravel() + in0darkDynamic = np.asarray(in0darkDynamic, dtype=np.float64).ravel() + + start = int(videoOffs) + stop = len(in_sig) - int(videoOffs) - 1 + + if mem is None or not mem or init: + mem = {} + mem['rawxycount'] = 0 + mem['darkdyncount'] = 0 + mem['ref_error'] = 0 + mem['raw_error'] = 0 + mem['rad_error'] = 0 + + if mem['rawxycount'] < maxrawxycount: + mem['rawxycount'] += 1 + if mem['darkdyncount'] < maxdarkdyncount: + mem['darkdyncount'] += 1 + + errnorm = np.atleast_2d(np.asarray(errsettings, dtype=np.float64)).copy() + if errnorm.shape[0] < 2: + errnorm = np.vstack([errnorm, np.zeros((1, max(1, errnorm.shape[1])))]) + + if not errnorm[0, 0]: + if (len(in_sig) != len(in0darkDynamic) or len(in_sig) != len(in0bright) or + len(in_sig) != len(in0darkStatic)): + errnorm[0, 0] = 186 + elif len(in_sig) < 200: + errnorm[0, 0] = 186 + + bright_seg = in0bright[start:stop + 1] + errref, mem['ref_error'] = videochk( + bright_seg, np.array([[0], [0]]), mem['rawxycount'], maxrawxycount, + mem['ref_error'], + inbright_minlevel1, inbright_maxlevel1, + inbright_minlevel2, inbright_maxlevel2, + inbright_too_low, inbright_too_high, inbright_too_low, inbright_too_high + ) + + if not errnorm[1, 0]: + if errref[0, 0]: + errnorm[1, 0] = errref[0, 0] + elif errref[1, 0]: + errnorm[1, 0] = errref[1, 0] + + raw_seg = in_sig[start:stop + 1] + errnorm, mem['raw_error'] = videochk( + raw_seg, errnorm, mem['rawxycount'], maxrawxycount, + mem['raw_error'], + raw_minlevel1, raw_maxlevel1, + raw_minlevel2, raw_maxlevel2, + raw_Contr, raw_Contr, raw_too_low, raw_too_high + ) + + if mem['darkdyncount'] >= maxdarkdyncount: + dark_dyn_seg = in0darkDynamic[start:stop + 1] + if not errnorm[0, 0]: + if np.mean(dark_dyn_seg) > dark_maxerrlevel: + errnorm[0, 0] = darkdyn_too_high + elif np.mean(dark_dyn_seg) < dark_minerrlevel: + errnorm[0, 0] = darkdyn_too_low + + if np.all(errnorm[:, 0] == 0): + if np.mean(dark_dyn_seg) > dark_maxwarnlevel: + errnorm[1, 0] = darkdyn_too_high + + rad_seg = in_sig[start:stop + 1] - in0darkDynamic[start:stop + 1] + errnorm, mem['rad_error'] = videochk( + rad_seg, errnorm, mem['rawxycount'], maxrawxycount, + mem['rad_error'], + rad_minlevel1, rad_maxlevel1, + rad_minlevel2, rad_maxlevel2, + raw_Contr, raw_Contr, rad_too_low, rad_too_high + ) + + normvideo = np.zeros(stop - start + 1) + + if not errnorm[0, 0]: + intsOffset = 100.0 + intsFactor = 40000 + + in_norm = intsFactor * ((in_sig[start:stop + 1] - in0darkDynamic[start:stop + 1]) / + (in0bright[start:stop + 1] - in0darkStatic[start:stop + 1])) + in_norm, _, _ = limit(in_norm, np.array([]), 1) + in_norm = in_norm + intsOffset + + if gap is not None and len(np.atleast_1d(gap)) > 0: + gap_arr = np.asarray(gap, dtype=np.float64) + if gap_arr.ndim == 1: + gap_arr = gap_arr.reshape(-1, 1) + + sort_idx = np.argsort(gap_arr[0, :]) + gap_arr[0, :] = gap_arr[0, sort_idx] + gap_arr[0, :] = np.round(gap_arr[0, :]) + gap_arr[1, :] = gap_arr[1, sort_idx] + if gap_arr.shape[0] >= 3: + gap_arr[2, :] = np.round(gap_arr[2, sort_idx]) + if gap_arr.shape[0] >= 4: + gap_arr[3, :] = np.round(gap_arr[3, sort_idx]) + + gap_arr[0, :] = np.round(gap_arr[0, :] - videoOffs) + + valid_idx = np.where((gap_arr[0, :] > 1) & (gap_arr[0, :] < len(in_norm)))[0] + gap_arr = gap_arr[:, valid_idx] + else: + gap_arr = np.array([]) + + if gap_arr.size == 0: + normvideo = in_norm + else: + normvideo_list = [] + startind = 0 + mmstart1 = 0.0 + mmstart2 = 0.0 + + for ii in range(gap_arr.shape[1]): + stopind = int(gap_arr[0, ii] - gap_arr[2, ii]) - 1 + x1 = mmstart1 + np.arange(0, stopind - startind + 1) * dxZeile + x2 = np.arange(mmstart2, x1[-1] + dxZeile, dxZeile) + + if stopind > startind: + if startind == 0: + secvideo = in_norm[startind:stopind + 1] + else: + secvideo = np.interp(x2, x1, in_norm[startind:stopind + 1]) + normvideo_list.append(secvideo) + + mmstart1 = x1[-1] + if len(x2) > 0: + mmstart2 = x2[-1] + dxZeile + + numdisablepix = int(gap_arr[2, ii] + gap_arr[3, ii]) + startind = stopind + 1 + stopind = startind + numdisablepix + + if stopind < len(in_norm): + x1 = mmstart1 + np.array([0, gap_arr[1, ii] + numdisablepix * dxZeile]) + x2 = np.arange(mmstart2, x1[-1] + dxZeile, dxZeile) + secvideo = np.interp(x2, x1, in_norm[[startind, min(stopind, len(in_norm) - 1)]]) + normvideo_list.append(secvideo) + + mmstart1 = x1[-1] + if len(x2) > 0: + mmstart2 = x2[-1] + dxZeile + + startind = stopind + 1 + + stopind = len(in_norm) - 1 + if startind <= stopind: + x1 = mmstart1 + np.arange(0, stopind - startind + 1) * dxZeile + x2 = np.arange(mmstart2, x1[-1] + dxZeile, dxZeile) + secvideo = np.interp(x2, x1, in_norm[startind:stopind + 1]) + normvideo_list.append(secvideo) + + if normvideo_list: + normvideo = np.concatenate(normvideo_list) + else: + normvideo = in_norm + + mmPixel = -0.5 * dxZeile * (len(normvideo) - 1) + + return normvideo, mmPixel, errnorm, mem + diff --git a/algorithm/thickness_utils.py b/algorithm/thickness_utils.py new file mode 100644 index 0000000..857f49e --- /dev/null +++ b/algorithm/thickness_utils.py @@ -0,0 +1,371 @@ +import numpy as np + + +def warnlogic(warnvek): + warnvek = np.asarray(warnvek, dtype=np.float64).ravel() + halfN = int(np.round(0.5 * len(warnvek))) + + wind1 = np.where(warnvek > 0)[0] + wind2 = np.where(warnvek != 0)[0] + wind = np.concatenate([wind1, wind2]) if (len(wind1) > 0 or len(wind2) > 0) else np.array([], dtype=int) + + if len(wind) == 0: + warnall = 0 + warnx = 0 + warny = 0 + elif np.all(wind < halfN): + warnall = warnvek[wind[0]] + warnx = warnall + warny = 0 + elif np.all(wind >= halfN): + warnall = warnvek[wind[0]] + warnx = 0 + warny = warnall + else: + warnall = warnvek[wind[0]] + idx_x = np.where(wind < halfN)[0] + idx_y = np.where(wind >= halfN)[0] + warnx = warnvek[wind[idx_x[0]]] if len(idx_x) > 0 else 0 + warny = warnvek[wind[idx_y[0]]] if len(idx_y) > 0 else 0 + + if len(warnvek) % 2 == 1: + warnx = np.array([]) + warny = np.array([]) + + return warnall, warnx, warny + + +def _calcellintersect(a, b, x0i, y0i, m, b0, phi, err_in): + phi_tmp = phi % (2 * np.pi) + + radix = np.sqrt(a**2 * (b**4 - (b * (m * x0i - y0i + b0))**2) + (a**4 * (b * m)**2)) + denom = b**2 + (m * a)**2 + x1 = (a**2 * m * (y0i - b0) - radix + x0i * b**2) / denom + y1 = m * x1 + b0 + x2 = (a**2 * m * (y0i - b0) + radix + x0i * b**2) / denom + y2 = m * x2 + b0 + + x = 0.0 + y = 0.0 + err = err_in + + if x1 != x2: + if ((phi_tmp < np.pi / 2) and (phi_tmp > 0)) or ((phi_tmp > 3 * np.pi / 2) and (phi_tmp < 2 * np.pi)): + if x1 > 0: + x = x1 + y = y1 + else: + x = x2 + y = y2 + err = 0 + elif (phi_tmp < 3 * np.pi / 2) and (phi_tmp > np.pi / 2): + if x1 < 0: + x = x1 + y = y1 + else: + x = x2 + y = y2 + err = 0 + + if not np.isreal(radix): + err = 91 + + return x, y, err + + +def calcminmaxwth(Layer, DMOuter, MinMaxAng, conf, EPFlag): + Layer = np.asarray(Layer, dtype=np.float64).copy() + DMOuter = np.asarray(DMOuter, dtype=np.float64).copy() + MinMaxAng = np.asarray(MinMaxAng, dtype=np.float64).copy() + + minwthflag = conf[196] if len(conf) > 196 else 0 + nangle = int(2 ** np.floor(np.log2(conf[197] if len(conf) > 197 else 16))) + dangle = 360.0 / nangle + addangle = np.arange(0, 360, dangle) + + if EPFlag: + mask = (addangle % 45) != 0 + addangle = addangle[mask] + else: + mask = (addangle % 90) != 0 + addangle = addangle[mask] + + addangle = addangle / 180.0 * np.pi + + InitStepL = 0.1 + MINWTHERROR = 92 + + aa = DMOuter[0, 1] / 2.0 + ba = DMOuter[0, 2] / 2.0 + + ai = aa - (Layer[0, 0] + Layer[0, 1]) / 2.0 + bi = ba - (Layer[0, 2] + Layer[0, 3]) / 2.0 + + x0i = Layer[0, 11] + y0i = Layer[0, 12] + + phi = (addangle - np.pi / 2) % (2 * np.pi) + lenphi = len(phi) + err = np.ones(lenphi) * 255 + + if (aa == 0) or (ba == 0) or (ai == 0) or (bi == 0): + Layer[1, 5:7] = MINWTHERROR + MinMaxAng[1, 0:2] = MINWTHERROR + return Layer, MinMaxAng + + t = np.arctan(aa / ba * np.tan(phi)) + mask_phi = (phi > np.pi / 2) & (phi < 3 * np.pi / 2) + t[mask_phi] = t[mask_phi] + np.pi + + ag = np.tan(phi) + xa = aa * np.cos(t) + ya = ba * np.sin(t) + ra = np.sqrt(xa * xa + ya * ya) + + xi = np.zeros(lenphi) + yi = np.zeros(lenphi) + ri = np.zeros(lenphi) + + for k in range(lenphi): + xi[k], yi[k], err[k] = _calcellintersect(ai, bi, x0i, y0i, ag[k], 0, phi[k], err[k]) + ri[k] = np.sqrt(xi[k]**2 + yi[k]**2) + + Wt = ra - ri + + WtMin = np.min(Wt) + idxmin = np.argmin(Wt) + errmin = err[idxmin] + + if not np.all(np.isreal(Wt)): + errmin = 91 + + if errmin == 0: + xi_min = xi[idxmin] + yi_min = yi[idxmin] + + if yi[idxmin] < y0i: + sig = -1 + else: + sig = 1 + + run = 1 + StepL = InitStepL + + while (run == 1) and np.isreal(np.sqrt(1 - ((xi[idxmin] - StepL - x0i) / ai)**2)): + yWtMin = y0i + bi * sig * np.sqrt(1 - ((xi[idxmin] - StepL - x0i) / ai)**2) + WtMin_tmp = np.sqrt((xa[idxmin] - (xi[idxmin] - StepL))**2 + (ya[idxmin] - yWtMin)**2) + if WtMin_tmp < WtMin: + WtMin = WtMin_tmp + xi_min = xi[idxmin] - StepL + yi_min = yWtMin + StepL = StepL + StepL / 2.0 + else: + StepL = StepL / 4.0 + if StepL < 1e-3: + run = 0 + + if not (WtMin < Wt[idxmin]): + run = 1 + StepL = InitStepL + WtMin = Wt[idxmin] + while (run == 1) and np.isreal(np.sqrt(1 - ((xi[idxmin] + StepL - x0i) / ai)**2)): + yWtMin = y0i + bi * sig * np.sqrt(1 - ((xi[idxmin] + StepL - x0i) / ai)**2) + WtMin_tmp = np.sqrt((xa[idxmin] - (xi[idxmin] + StepL))**2 + (ya[idxmin] - yWtMin)**2) + if WtMin_tmp < WtMin: + WtMin = WtMin_tmp + xi_min = xi[idxmin] + StepL + yi_min = yWtMin + StepL = StepL + StepL / 2.0 + else: + StepL = StepL / 4.0 + if StepL < 1e-3: + run = 0 + + if WtMin < Layer[0, 5]: + MinMaxAng[0, 0] = ((phi[idxmin] + np.pi / 2) * 180.0 / np.pi) % 360 + if minwthflag: + Layer[0, 5] = WtMin + else: + MinMaxAng[1, 0] = MINWTHERROR + Layer[1, 5] = MINWTHERROR + + WtMax = np.max(Wt) + idxmax = np.argmax(Wt) + errmax = err[idxmax] + + if errmax == 0: + if WtMax > Layer[0, 6]: + MinMaxAng[0, 1] = ((phi[idxmax] + np.pi / 2) * 180.0 / np.pi) % 360 + if minwthflag: + Layer[0, 6] = WtMax + else: + MinMaxAng[1, 1] = MINWTHERROR + Layer[1, 6] = MINWTHERROR + + return Layer, MinMaxAng + + +def updateMinMaxWTH(Layer, DMOuter, DMInner, BisectionWith, StOK, StDefault, StNovalue, reduceavgon, StWait=249): + Layer = np.asarray(Layer, dtype=np.float64).copy() + DMOuter = np.asarray(DMOuter, dtype=np.float64).copy() + DMInner = np.asarray(DMInner, dtype=np.float64).copy() + BisectionWith = np.asarray(BisectionWith, dtype=np.float64).copy() + + def _ok(s): + return s in (StOK, StWait) + + MinMaxAng = StDefault * np.ones((3, 2), dtype=np.float64) + + warnvek = np.array([DMOuter[2, 0], DMInner[2, 0], Layer[2, 4]]) + warnall, _, _ = warnlogic(warnvek) + MinMaxAng[2, :] = warnall + + if (_ok(DMOuter[1, 1]) and _ok(DMOuter[1, 2]) and + _ok(DMInner[1, 1]) and _ok(DMInner[1, 2]) and + _ok(Layer[1, 11]) and _ok(Layer[1, 12])): + + if (_ok(Layer[1, 0]) and _ok(Layer[1, 1]) and + _ok(Layer[1, 2]) and _ok(Layer[1, 3])): + + if (_ok(BisectionWith[1, 0]) and _ok(BisectionWith[1, 1]) and + _ok(BisectionWith[1, 2]) and _ok(BisectionWith[1, 3])): + + vals = np.array([Layer[0, 2], BisectionWith[0, 0], Layer[0, 1], BisectionWith[0, 1], + Layer[0, 3], BisectionWith[0, 2], Layer[0, 0], BisectionWith[0, 3]]) + WtMin = np.min(vals) + IndMin = np.argmin(vals) + MinMaxAng[0, 0] = 45 * IndMin + MinMaxAng[1, 0] = StOK + + WtMax = np.max(vals) + IndMax = np.argmax(vals) + MinMaxAng[0, 1] = 45 * IndMax + MinMaxAng[1, 1] = StOK + else: + vals = np.array([Layer[0, 2], Layer[0, 1], Layer[0, 3], Layer[0, 0]]) + WtMin = np.min(vals) + IndMin = np.argmin(vals) + MinMaxAng[0, 0] = 90 * IndMin + MinMaxAng[1, 0] = StOK + + WtMax = np.max(vals) + IndMax = np.argmax(vals) + MinMaxAng[0, 1] = 90 * IndMax + MinMaxAng[1, 1] = StOK + + Layer[0, 5] = WtMin + Layer[1, 5] = StOK + Layer[0, 6] = WtMax + Layer[1, 6] = StOK + else: + Layer[0, 5] = 0 + Layer[1, 5] = StNovalue + Layer[0, 6] = 0 + Layer[1, 6] = StNovalue + MinMaxAng[0, 0] = 0 + MinMaxAng[1, 0] = StNovalue + MinMaxAng[0, 1] = 0 + MinMaxAng[1, 1] = StNovalue + else: + if not _ok(DMOuter[1, 1]): + TempSt = DMOuter[1, 1] + elif not _ok(DMOuter[1, 2]): + TempSt = DMOuter[1, 2] + elif not _ok(DMInner[1, 1]): + TempSt = DMInner[1, 1] + elif not _ok(DMInner[1, 2]): + TempSt = DMInner[1, 2] + elif not _ok(Layer[1, 11]): + TempSt = Layer[1, 11] + elif not _ok(Layer[1, 12]): + TempSt = Layer[1, 12] + else: + TempSt = StDefault + + BisectionWith[0, 0] = 0 + BisectionWith[1, 0] = TempSt + BisectionWith[0, 1] = 0 + BisectionWith[1, 1] = TempSt + BisectionWith[0, 2] = 0 + BisectionWith[1, 2] = TempSt + BisectionWith[0, 3] = 0 + BisectionWith[1, 3] = TempSt + + if not reduceavgon: + Layer[0, 5] = 0 + Layer[1, 5] = TempSt + Layer[0, 6] = 0 + Layer[1, 6] = TempSt + MinMaxAng[0, 0] = 0 + MinMaxAng[1, 0] = TempSt + MinMaxAng[0, 1] = 0 + MinMaxAng[1, 1] = TempSt + + return Layer, BisectionWith, MinMaxAng + + +def updateMinMaxWTHall(Layer, Wt, MinMaxAng, conf, phi, Err): + minwthflag = conf[196] if len(conf) > 196 else 0 + MINWTHERROR = 92 + + Wt = np.asarray(Wt, dtype=np.float64).copy() + Err = np.asarray(Err, dtype=np.float64) + if Err.shape == Wt.shape: + Wt[Err != 0] = np.nan + + MinMaxAng = np.asarray(MinMaxAng, dtype=np.float64).copy() + Layer = np.asarray(Layer, dtype=np.float64).copy() + + if Wt.ndim == 1: + Wt = Wt.reshape(-1, 1) + n_phi, n_col = Wt.shape + + WtMin1 = np.full(n_col, np.nan) + idxmin1 = np.zeros(n_col, dtype=int) + for j in range(n_col): + col = Wt[:, j] + valid = ~np.isnan(col) + if np.any(valid): + idx = np.argmin(col[valid]) + orig_idx = np.where(valid)[0][idx] + WtMin1[j] = col[orig_idx] + idxmin1[j] = orig_idx + + valid_min = ~np.isnan(WtMin1) + if np.any(valid_min): + idxmin = np.argmin(WtMin1[valid_min]) + col_idx = np.where(valid_min)[0][idxmin] + WtMin = WtMin1[col_idx] + phi_idx = idxmin1[col_idx] + + if WtMin < Layer[0, 5]: + angle_rad = phi[phi_idx] + col_idx * np.pi / 2 + MinMaxAng[0, 0] = np.mod(angle_rad * 180 / np.pi, 360) + if minwthflag: + Layer[0, 5] = WtMin + + WtMax1 = np.full(n_col, np.nan) + idxmax1 = np.zeros(n_col, dtype=int) + for j in range(n_col): + col = Wt[:, j] + valid = ~np.isnan(col) + if np.any(valid): + idx = np.argmax(col[valid]) + orig_idx = np.where(valid)[0][idx] + WtMax1[j] = col[orig_idx] + idxmax1[j] = orig_idx + + valid_max = ~np.isnan(WtMax1) + if np.any(valid_max): + idxmax = np.argmax(WtMax1[valid_max]) + col_idx = np.where(valid_max)[0][idxmax] + WtMax = WtMax1[col_idx] + phi_idx = idxmax1[col_idx] + + if WtMax > Layer[0, 6]: + angle_rad = phi[phi_idx] + col_idx * np.pi / 2 + MinMaxAng[0, 1] = np.mod(angle_rad * 180 / np.pi, 360) + if minwthflag: + Layer[0, 6] = WtMax + + return Layer, MinMaxAng diff --git a/algorithm/validation_utils.py b/algorithm/validation_utils.py new file mode 100644 index 0000000..1bea546 --- /dev/null +++ b/algorithm/validation_utils.py @@ -0,0 +1,660 @@ +import numpy as np +import copy + +try: + from .math_utils import ind, polyfit2 + from .geometry_utils import strng2 +except ImportError: + from math_utils import ind, polyfit2 + from geometry_utils import strng2 + +try: + from .layer_calibration_utils import isofit, corefit +except ImportError: + from layer_calibration_utils import isofit, corefit + + +def statuscheck2(avgvalue, avgstatus, singlestatus, insens, + filterr, startup_percent, warninginsens, setupfailure, avgmem): + StWait = 249 + StDefault = 255 + StFilterr = 70 + + avgvalue = np.asarray(avgvalue, dtype=np.float64) + avgstatus = np.atleast_1d(np.asarray(avgstatus, dtype=np.float64)).ravel() + singlestatus = np.atleast_1d(np.asarray(singlestatus, dtype=np.float64)).ravel() + + avgoutvalue = np.zeros_like(avgvalue) + avgoutstatus = np.zeros(3, dtype=np.float64) + + if len(avgstatus) >= 1: + pct = (1.0 - avgstatus[0]) * 100.0 + avgoutstatus[2] = max(0.0, min(100.0, pct)) + + if warninginsens is None or (isinstance(warninginsens, (list, np.ndarray)) and len(warninginsens) == 0): + warninginsens = insens + + if 'oldsinglestatus' not in avgmem or avgmem['oldsinglestatus'] is None or ( + isinstance(avgmem['oldsinglestatus'], (list, np.ndarray)) and len(avgmem['oldsinglestatus']) == 0): + avgmem['oldsinglestatus'] = singlestatus.copy() + + if len(singlestatus) >= 1 and singlestatus[0]: + avgmem['oldsinglestatus'][0] = singlestatus[0] + if len(singlestatus) >= 2 and singlestatus[1]: + if len(avgmem['oldsinglestatus']) < 2: + avgmem['oldsinglestatus'] = np.pad(avgmem['oldsinglestatus'], (0, 1)) + avgmem['oldsinglestatus'][1] = singlestatus[1] + + if avgstatus[0] > (1.0 - insens / 100.0): + avgoutvalue = avgvalue.copy() + avgoutstatus[0] = 0 + else: + if setupfailure: + avgoutstatus[0] = avgmem['oldsinglestatus'][0] + elif startup_percent < 100: + avgoutvalue[:] = np.round(startup_percent) + avgoutstatus[0] = StWait + else: + if avgmem['oldsinglestatus'][0]: + avgoutstatus[0] = avgmem['oldsinglestatus'][0] + else: + avgoutstatus[0] = StDefault + + avgoutstatus[1] = 0 + + has_two = (len(avgstatus) == 2) and (len(avgmem['oldsinglestatus']) == 2) + + if startup_percent > 98: + if avgstatus[0] < (1.0 - warninginsens / 100.0) and not avgoutstatus[0]: + avgoutstatus[1] = avgmem['oldsinglestatus'][0] + elif has_two and avgstatus[1] < (1.0 - warninginsens / 100.0) and avgmem['oldsinglestatus'][1]: + avgoutstatus[1] = -avgmem['oldsinglestatus'][1] + elif filterr: + avgoutstatus[1] = -StFilterr + + return avgoutvalue, avgoutstatus, avgmem + + +def symlimit(symj, symj2, NOMJACK1, NOMJACK2): + if NOMJACK1 > 0 and NOMJACK2 > 0: + NOMJACK = min(NOMJACK1, NOMJACK2) + elif NOMJACK1 > 0: + NOMJACK = NOMJACK1 + elif NOMJACK2 > 0: + NOMJACK = NOMJACK2 + else: + NOMJACK = 0 + + if NOMJACK > 0: + if symj > NOMJACK: + symj = NOMJACK + if symj2 > NOMJACK: + symj2 = NOMJACK + + return symj, symj2 + + +def kcheck(IN, x0, x0r, xmeas, Dl, Dr, dx, Anzpara, Typ): + IN = np.asarray(IN, dtype=np.float64).ravel() + d0 = x0r - x0 + + if Typ == 'OSCL': + rr = int(ind(xmeas, dx)) + ll = rr - 1 + else: + rr = int(ind(xmeas, dx)) + ll = int(ind(Dl, dx)) + + kl = 0.0 + + if Typ == 'DIAM': + if rr >= ll and ll >= 1 and rr <= len(IN): + seg = IN[ll - 1:rr] + seg = seg[seg > 0] + if len(seg) > 0: + kl = np.mean(-np.log(seg)) + else: + x = (np.arange(ll - 1, rr) - 0) * dx + if len(x) >= 2 and x[0] > x0 and x[0] < x0r and x[-1] > x0 and x[-1] < x0r: + s1 = strng2(x, x0, x0r, 1) + seg = IN[ll - 1:rr] + valid = (seg > 0) & (s1 > 0) + if np.any(valid): + kl = np.mean(-np.log(seg[valid]) / s1[valid]) + + kr = None + if abs(kl) > 0: + if Typ == 'OSCR': + ll = int(ind(xmeas, dx)) + rr = ll + 1 + else: + ll = int(ind(xmeas, dx)) + rr = int(ind(Dr, dx)) + + if Typ == 'DIAM': + if rr >= ll and ll >= 1 and rr <= len(IN): + seg = IN[ll - 1:rr] + seg = seg[seg > 0] + if len(seg) > 0: + kr = np.mean(-np.log(seg)) + else: + x = (np.arange(ll - 1, rr)) * dx + if len(x) >= 2 and x[0] > x0 and x[0] < x0r and x[-1] > x0 and x[-1] < x0r: + s1 = strng2(x, x0, x0r, 1) + seg = IN[ll - 1:rr] + valid = (seg > 0) & (s1 > 0) + if np.any(valid): + kr = np.mean(-np.log(seg[valid]) / s1[valid]) + + if kr is not None: + Kontrast = kl - kr + else: + Kontrast = 0.0 + + return Kontrast + + +def kcheck2(IN, x0, x0r, xmeas, Dl, Dr, dx, Anzpara, Typ, xshift=0): + IN = np.asarray(IN, dtype=np.float64).ravel() + + Kontrast = 0.0 + Dae = 0.0 + DaeGrad = 0.0 + Apol = np.zeros(3, dtype=np.float64) + + ll = int(ind(Dl, dx, xshift)) + rr = int(ind(Dr, dx, xshift)) + mitt = int(ind(xmeas, dx, xshift)) + rangeflag = 0 + + d0 = x0r - x0 + + kl = 0.0 + kr = 0.0 + + if ((mitt - ll) > 4) and ((rr - mitt) > 4) and (Dl > x0) and (Dl < x0r) and (Dr > x0) and (Dr < x0r): + + if (Dl < (x0 + 0.5 * d0)) and (Dr < (x0 + 0.5 * d0)): + rangeflag = -1 + + rr_left = int(ind(xmeas, dx, xshift)) + ll_left = int(ind(Dl, dx, xshift)) + + ivek = np.arange(1, rr_left - ll_left + 2) + jvek = ivek + (ll_left - 1) + jvek = jvek[jvek <= len(IN)] + + xl2 = (jvek - 1) * dx + xshift + s1 = strng2(xl2, x0, x0r, 1) + + seg_in = IN[jvek.astype(int) - 1] + valid = (seg_in > 0) & (s1 > 0) + if np.any(valid): + kl2 = -(np.log(seg_in[valid])) / s1[valid] + xl2_valid = xl2[valid] + + if len(xl2_valid) >= 3: + A = polyfit2(xl2_valid, kl2, 2) + try: + kl = np.polyval(A, xmeas) + except Exception: + kl = np.mean(kl2) + + A_lin = polyfit2(xl2_valid, kl2, 1) + DaeGrad = A_lin[0] if len(A_lin) >= 1 else 0.0 + else: + kl = np.mean(kl2) + DaeGrad = 0.0 + + ll_right = int(ind(xmeas + dx, dx, xshift)) + rr_right = int(ind(Dr, dx, xshift)) + x1 = xmeas + x1r = x0r - (xmeas - x0) + + ivek_r = np.arange(1, rr_right - ll_right + 2) + jvek_r = ivek_r + (ll_right - 1) + jvek_r = jvek_r[jvek_r <= len(IN)] + + xr2 = (jvek_r - 1) * dx + xshift + s1_r = strng2(xr2, x0, x0r, 1) + s2_r = strng2(xr2, x1, x1r, 1) + + seg_in_r = IN[jvek_r.astype(int) - 1] + valid_r = (seg_in_r > 0) & (s2_r > 0) + if np.any(valid_r): + kr2 = -(np.log(seg_in_r[valid_r]) + kl * (s1_r[valid_r] - s2_r[valid_r])) / s2_r[valid_r] + kr = np.mean(kr2) + Kontrast = kr - kl + Dae = kl + + elif (Dl > (x0 + 0.5 * d0)) and (Dr > (x0 + 0.5 * d0)): + rangeflag = 1 + + rr_right = int(ind(Dr, dx, xshift)) + ll_right = int(ind(xmeas, dx, xshift)) + + ivek_r = np.arange(1, rr_right - ll_right + 2) + jvek_r = ivek_r + (ll_right - 1) + jvek_r = jvek_r[jvek_r <= len(IN)] + + xr2 = (jvek_r - 1) * dx + xshift + s1_r = strng2(xr2, x0, x0r, 1) + + seg_in_r = IN[jvek_r.astype(int) - 1] + valid_r = (seg_in_r > 0) & (s1_r > 0) + if np.any(valid_r): + kr2 = -(np.log(seg_in_r[valid_r])) / s1_r[valid_r] + xr2_valid = xr2[valid_r] + + if len(xr2_valid) >= 3: + A = polyfit2(xr2_valid, kr2, 2) + try: + kr = np.polyval(A, xmeas) + except Exception: + kr = np.mean(kr2) + Dae = kr + + A_lin = polyfit2(xr2_valid, kr2, 1) + DaeGrad = -A_lin[0] if len(A_lin) >= 1 else 0.0 + else: + kr = np.mean(kr2) + Dae = kr + DaeGrad = 0.0 + + ll_left = int(ind(Dl, dx, xshift)) + rr_left = int(ind(xmeas - dx, dx, xshift)) + x1 = x0 + (x0r - xmeas) + x1r = xmeas + + ivek_l = np.arange(1, rr_left - ll_left + 2) + jvek_l = ivek_l + (ll_left - 1) + jvek_l = jvek_l[jvek_l <= len(IN)] + + xl2 = (jvek_l - 1) * dx + xshift + s1_l = strng2(xl2, x0, x0r, 1) + s2_l = strng2(xl2, x1, x1r, 1) + + seg_in_l = IN[jvek_l.astype(int) - 1] + valid_l = (seg_in_l > 0) & (s2_l > 0) + if np.any(valid_l): + kl2 = -(np.log(seg_in_l[valid_l]) + kr * (s1_l[valid_l] - s2_l[valid_l])) / s2_l[valid_l] + kl = np.mean(kl2) + Kontrast = kl - kr + Dae = kr + + return Kontrast, Dae, DaeGrad, Apol + + +def _plausi_layer_sub(layer, minwarning, minerror, errornumber): + layer = np.asarray(layer, dtype=np.float64).ravel() + if layer[1] == 0: + if layer[0] < minerror: + layer[1] = errornumber + elif layer[0] < minwarning: + layer[2] = errornumber + return layer + + +def _errordep_layer_sub(indep_layer, dep_layer, errornumber): + indep_layer = np.asarray(indep_layer, dtype=np.float64).ravel() + dep_layer = np.asarray(dep_layer, dtype=np.float64).ravel() + + if dep_layer[1] == 0 and indep_layer[1] == errornumber: + dep_layer[1] = indep_layer[1] + elif dep_layer[2] == 0 and indep_layer[2] == errornumber: + dep_layer[2] = indep_layer[2] + return dep_layer + + +def plausi_layer(inresults, settings): + ERR_OSC = 89 + ERR_ISO = 88 + ERR_ISC = 87 + + OSC_WARNING = 0.0 + OSC_ERROR = 0.0 + ISO_WARNING = 0.0 + ISO_ERROR = 0.0 + ISC_WARNING = 0.0 + ISC_ERROR = 0.0 + + devicetype = None + try: + devicetype = settings.get('version', {}).get('devicetype', None) + except Exception: + pass + + confData20 = None + try: + confData = settings.get('confData', None) + if confData is not None and len(np.atleast_1d(confData)) >= 20: + confData20 = float(np.atleast_1d(confData)[19]) + except Exception: + pass + + if devicetype in [8000, 8001, 8100, 8101]: + if confData20 == 111: + ISC_WARNING = 0.3 + ISC_ERROR = 0.25 + elif confData20 == 109: + ISO_WARNING = 0.7 + ISO_ERROR = 0.6 + elif confData20 in [115, 118]: + ISC_WARNING = 0.4 + ISC_ERROR = 0.3 + else: + if confData20 == 111: + ISC_WARNING = 0.5 + ISC_ERROR = 0.4 + elif confData20 == 109: + ISO_WARNING = 0.7 + ISO_ERROR = 0.6 + elif confData20 in [115, 118]: + ISC_WARNING = 0.4 + ISC_ERROR = 0.3 + + try: + left_osc = inresults.get('left', {}).get('osc', np.zeros((3, 2))) + right_osc = inresults.get('right', {}).get('osc', np.zeros((3, 2))) + left_iso = inresults.get('left', {}).get('iso', np.zeros((3, 2))) + right_iso = inresults.get('right', {}).get('iso', np.zeros((3, 2))) + left_isc = inresults.get('left', {}).get('isc', np.zeros((3, 2))) + right_isc = inresults.get('right', {}).get('isc', np.zeros((3, 2))) + + all_osc = np.concatenate([np.asarray(left_osc)[1, :], np.asarray(right_osc)[1, :]]) + all_iso = np.concatenate([np.asarray(left_iso)[1, :], np.asarray(right_iso)[1, :]]) + all_isc = np.concatenate([np.asarray(left_isc)[1, :], np.asarray(right_isc)[1, :]]) + + layeruse = [ + not np.any(all_osc == 45), + not np.any(all_iso == 45), + not np.any(all_isc == 45) + ] + except Exception: + layeruse = [True, True, True] + + if OSC_WARNING > 0 or OSC_ERROR > 0: + for side in ['left', 'right']: + for col in range(2): + key = f'{side}_osc_{col}' + try: + layer = inresults[side]['osc'][:, col] + layer = _plausi_layer_sub(layer, OSC_WARNING, OSC_ERROR, ERR_OSC) + inresults[side]['osc'][:, col] = layer + except Exception: + pass + + if ISO_WARNING > 0 or ISO_ERROR > 0: + for side in ['left', 'right']: + for col in range(2): + try: + layer = inresults[side]['iso'][:, col] + layer = _plausi_layer_sub(layer, ISO_WARNING, ISO_ERROR, ERR_ISO) + inresults[side]['iso'][:, col] = layer + except Exception: + pass + + if ISC_WARNING > 0 or ISC_ERROR > 0: + for side in ['left', 'right']: + for col in range(2): + try: + layer = inresults[side]['isc'][:, col] + layer = _plausi_layer_sub(layer, ISC_WARNING, ISC_ERROR, ERR_ISC) + inresults[side]['isc'][:, col] = layer + except Exception: + pass + + if layeruse[0] and layeruse[1]: + for side in ['left', 'right']: + for col in range(2): + try: + osc_col = inresults[side]['osc'][:, col] + iso_col = inresults[side]['iso'][:, col] + if col == 0 and any(osc_col[1:3] == ERR_OSC): + inresults[side]['iso'][:, col] = _errordep_layer_sub(osc_col, iso_col, ERR_OSC) + except Exception: + pass + + if layeruse[1] and layeruse[2]: + for side in ['left', 'right']: + for col in range(2): + try: + isc_col = inresults[side]['isc'][:, col] + iso_col = inresults[side]['iso'][:, col] + if col == 0 and any(isc_col[1:3] == ERR_ISC): + inresults[side]['iso'][:, col] = _errordep_layer_sub(isc_col, iso_col, ERR_ISC) + except Exception: + pass + + return inresults + + +def mcoldef2(errorl): + errorl = np.asarray(errorl, dtype=np.float64).ravel() + if errorl[0]: + return 'r' + elif len(errorl) > 1 and errorl[1]: + return 'm' + else: + return 'g' + + +def mcoldefline(errorl): + return mcoldef2(errorl) + + +def limit(x, uplimit, lowlimit, limitflag=None): + x = np.asarray(x, dtype=np.float64) + uplimit = np.asarray(uplimit, dtype=np.float64) + lowlimit = np.asarray(lowlimit, dtype=np.float64) + + if limitflag is None: + limitflag = np.ones_like(x, dtype=np.float64) + else: + limitflag = np.asarray(limitflag, dtype=np.float64) + + y = x.copy() + errorl = 0 + lflag = 0 + + if uplimit.size == 1: + uplimit = uplimit * np.ones_like(x) + if lowlimit.size == 1: + lowlimit = lowlimit * np.ones_like(x) + + uplimiterused = 0 + if x.shape == uplimit.shape and x.shape == limitflag.shape: + uplimiterused = 1 + ind = np.where((x > uplimit) & (limitflag > 0))[0] + if len(ind) > 0: + y[ind] = uplimit[ind] + lflag = 1 + + lowlimiterused = 0 + if x.shape == lowlimit.shape and x.shape == limitflag.shape: + lowlimiterused = 1 + ind = np.where((x < lowlimit) & (limitflag > 0))[0] + if len(ind) > 0: + y[ind] = lowlimit[ind] + lflag = 1 + + if not uplimiterused and not lowlimiterused: + errorl = 1 + + return y, errorl, lflag + + +def validchk(x, minval, maxval, defaultval, defaultflag, + errorin=0, errorlow=0, errorhigh=0): + y = x + errorout = errorin + + if x is None or (isinstance(x, np.ndarray) and x.size == 0): + y = defaultval + elif isinstance(x, (int, float, np.floating, np.integer)) and x < minval: + if defaultflag: + y = defaultval + else: + y = minval + if not errorin: + errorout = errorlow + elif isinstance(x, (int, float, np.floating, np.integer)) and x > maxval: + if defaultflag: + y = defaultval + else: + y = maxval + if not errorin: + errorout = errorhigh + + return y, errorout + + +def chksettings(settings, errin, xray8k=0): + nomlengthconf = 1339 + actualconftype = 3.020 + + if errin is None or (isinstance(errin, (float, int)) and np.isnan(errin)): + errin = np.zeros(2) + + errsettings = np.atleast_1d(np.asarray(errin, dtype=np.float64)).ravel() + if len(errsettings) < 2: + errsettings = np.pad(errsettings, (0, 2 - len(errsettings))) + + if errsettings[0] == 0: + confData = settings.get('confData', None) + if confData is None or len(np.atleast_1d(confData)) == 0: + errsettings[0] = 180 + settings['confData'] = np.zeros(nomlengthconf) + elif len(np.atleast_1d(confData)) < nomlengthconf: + errsettings[0] = 181 + settings['confData'] = np.zeros(nomlengthconf) + elif len(np.atleast_1d(confData)) > 119 and np.atleast_1d(confData)[119] < actualconftype: + errsettings[0] = 182 + elif not xray8k: + geom_x = settings.get('geometryData', {}).get('x', {}) + geom_y = settings.get('geometryData', {}).get('y', {}) + x0 = geom_x.get('x0', 0) + y0 = geom_y.get('y0', 0) + xCCD = geom_x.get('xCCD', 0) + yCCD = geom_y.get('yCCD', 0) + + if x0 <= 0 or y0 <= 0 or xCCD >= 0 or yCCD >= 0: + errsettings[0] = 184 + geom_x['x0'] = 600 + geom_y['y0'] = 600 + else: + xgamma = geom_x.get('gamma') + ygamma = geom_y.get('gamma') + if xgamma is not None and ygamma is not None and len(np.atleast_1d(xgamma)) > 0 and len(np.atleast_1d(ygamma)) > 0: + xgamma_val = float(np.atleast_1d(xgamma)[0]) + ygamma_val = float(np.atleast_1d(ygamma)[0]) + if (xgamma_val < 80 or xgamma_val > 110 or + ygamma_val < 80 or ygamma_val > 110): + if xgamma_val == 0 and ygamma_val == 0: + geom_x['gamma'] = None + geom_y['gamma'] = None + errsettings[1] = 184 + else: + errsettings[0] = 184 + else: + calib_int = settings.get('calib_struct', {}).get('int', {}) + calib_ext = settings.get('calib_struct', {}).get('ext', {}) + calib_int_valid = isinstance(calib_int, dict) and len(calib_int) > 0 + calib_ext_valid = isinstance(calib_ext, dict) and len(calib_ext) > 0 + if (calib_int_valid and calib_int.get('err', 0) > 0 and + not calib_int.get('calibrationoff', 1)): + errsettings[0] = calib_int['err'] + elif (calib_ext_valid and calib_ext.get('err', 0) > 0 and + not calib_ext.get('calibrationoff', 1)): + errsettings[0] = calib_ext['err'] + elif not calib_int_valid: + errsettings[0] = 191 + + if not xray8k: + gap_dxCCD = settings.get('gap', {}).get('dxCCD', {}) + dx_x = gap_dxCCD.get('x') + dx_y = gap_dxCCD.get('y') + if dx_x is not None and dx_y is not None and len(np.atleast_1d(dx_x)) > 0 and len(np.atleast_1d(dx_y)) > 0: + dx_x_val = float(np.atleast_1d(dx_x)[0]) + dx_y_val = float(np.atleast_1d(dx_y)[0]) + if dx_x_val == 0 and dx_y_val == 0: + gap_dxCCD['x'] = None + gap_dxCCD['y'] = None + errsettings[1] = 183 + elif dx_x_val < 0 or dx_y_val < 0: + gap_dxCCD['x'] = 1e-6 + gap_dxCCD['y'] = 1e-6 + errsettings[0] = 183 + + return settings, errsettings + + +def plausi2000(results, avgresults, settings): + results_out = copy.deepcopy(results) + + check_dm = settings.get('plausiData', {}).get('check_dm', 0) + check_lay = settings.get('plausiData', {}).get('check_lay', 0) + + if check_dm and avgresults is not None: + dm_out_avg = avgresults.get('dmOut', np.zeros((4, 2))) + if np.all(dm_out_avg[1, 0:2] == 0): + val_in = results['dmOut'][0, 0:2].copy() + limitflag = results['dmOut'][1, 0:2] == 0 + rel_limit_dm = settings['plausiData'].get('rel_limit_dm', 0) + abs_limit_dm = settings['plausiData'].get('abs_limit_dm', 0) + uplimit = (1 + rel_limit_dm) * dm_out_avg[0, 0:2] + abs_limit_dm + lowlimit = (1 - rel_limit_dm) * dm_out_avg[0, 0:2] - abs_limit_dm + val_out, _, _ = limit(val_in, uplimit, lowlimit, limitflag) + results_out['dmOut'][0, 0:2] = val_out + + if check_lay and avgresults is not None: + for layer in ['wth', 'osc', 'isc']: + avg_left = avgresults.get('left', {}).get(layer, np.zeros((4, 2))) + avg_right = avgresults.get('right', {}).get(layer, np.zeros((4, 2))) + if np.all(avg_left[1, 0:2] == 0) and np.all(avg_right[1, 0:2] == 0): + val_in = np.concatenate([results['left'][layer][0, 0:2], results['right'][layer][0, 0:2]]) + limitflag = np.concatenate([results['left'][layer][1, 0:2] == 0, results['right'][layer][1, 0:2] == 0]) + rel_limit_lay = settings['plausiData'].get('rel_limit_lay', 0) + abs_limit_lay = settings['plausiData'].get('abs_limit_lay', 0) + avg_all = np.concatenate([avg_left[0, 0:2], avg_right[0, 0:2]]) + uplimit = (1 + rel_limit_lay) * avg_all + abs_limit_lay + lowlimit = (1 - rel_limit_lay) * avg_all - abs_limit_lay + val_out, _, _ = limit(val_in, uplimit, lowlimit, limitflag) + results_out['left'][layer][0, 0:2] = val_out[0:2] + results_out['right'][layer][0, 0:2] = val_out[2:4] + + if (check_dm and avgresults is not None) or (check_lay and avgresults is not None): + results_out = isofit(results_out) + results_out = corefit(results_out) + + return results_out + + +def chk_tolchksettings(tchkstrct): + if not isinstance(tchkstrct, dict): + return False + + fields = [ + 'PtolDMmean', 'PtolDM', + 'PtolOSCmean', 'PtolOSC', + 'PtolISOmean', 'PtolISO', + 'PtolISCmean', 'PtolISC', + 'PtolWTHmean', 'PtolWTH', + 'PtolCoremean', 'PtolCore', + 'NtolDMmean', 'NtolDM', + 'NtolOSCmean', 'NtolOSC', + 'NtolISOmean', 'NtolISO', + 'NtolISCmean', 'NtolISC', + 'NtolWTHmean', 'NtolWTH', + 'NtolCoremean', 'NtolCore', + ] + + vals = [] + for f in fields: + v = tchkstrct.get(f, 0) + if isinstance(v, (list, np.ndarray)): + vals.extend(np.atleast_1d(v).tolist()) + else: + vals.append(float(v)) + + return any(v > 0 for v in vals) diff --git a/compute_service.py b/compute_service.py index 709c802..b16d545 100644 --- a/compute_service.py +++ b/compute_service.py @@ -434,7 +434,17 @@ class ComputeService: try: # 通过UDP发送计算命令 start_time = datetime.now() - out_path = self.udp_handler.compute(mat_path, timeout) + if config_manager.get('alg_caller', "UDP") == "UDP": + out_path = self.udp_handler.compute(mat_path, timeout) + else: + try: + from algorithm.gateway import cpyAlgorithm + + out_path = cpyAlgorithm(mat_path) + except Exception as e: + logger.error(f"Failed to compute: {e}") + return None, None + end_time = datetime.now() logger.info(f"---------------Computing used time: {end_time - start_time}---------------") diff --git a/config.py b/config.py index b1728dd..80becfa 100644 --- a/config.py +++ b/config.py @@ -24,6 +24,7 @@ DEFAULT_HTTP_HOST = "0.0.0.0" DEFAULT_HTTP_PORT = 5000 DEFAULT_UDP_SERVER = ("127.0.0.1", 15000) DEFAULT_UDP_PORT_NUM = 10 +DEFAULT_ALG_CALLER = "UDP" class ConfigManager: """配置管理器""" @@ -79,7 +80,8 @@ class ConfigManager: }, 'udp_map': { - } + }, + 'alg_caller': DEFAULT_ALG_CALLER } def get(self, key, default=None):