添加对python算法的支持
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
from .config_reader import config_read_double
|
||||
from .geometry_utils import strng2, strngellips
|
||||
|
||||
__all__ = ['config_read_double', 'strng2', 'strngellips']
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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([])
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
@@ -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
|
||||
@@ -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]
|
||||
])
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
@@ -0,0 +1,2 @@
|
||||
numpy==2.4.1
|
||||
scipy==1.17.1
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
+11
-1
@@ -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}---------------")
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user