1092 lines
47 KiB
Python
1092 lines
47 KiB
Python
import time
|
|
import numpy as np
|
|
import scipy
|
|
import os
|
|
import copy
|
|
import math
|
|
|
|
|
|
_global_mem = None
|
|
_Lsq_LM_on = 0
|
|
_Unsharpness = 0
|
|
|
|
|
|
def get_user_data():
|
|
global _global_mem
|
|
return copy.deepcopy(_global_mem) if _global_mem is not None else None
|
|
|
|
|
|
def set_user_data(mem):
|
|
global _global_mem
|
|
_global_mem = copy.deepcopy(mem)
|
|
|
|
|
|
def reset_user_data():
|
|
global _global_mem
|
|
_global_mem = None
|
|
|
|
|
|
def _convert_cable_type(cableTypeOrg):
|
|
"""四位数cableType转换为标准类型,并返回sectorAna标志"""
|
|
sectorAna = 0
|
|
cableType = cableTypeOrg
|
|
|
|
digits = int(math.floor(math.log10(cableTypeOrg))) + 1 if cableTypeOrg > 0 else 0
|
|
if digits == 4:
|
|
if cableTypeOrg in (1111, 1112, 1113, 1114):
|
|
cableType = 111
|
|
elif cableTypeOrg in (2100, 2200, 2300, 2400):
|
|
cableType = 2
|
|
elif cableTypeOrg in (2210, 2220, 2230, 2240):
|
|
cableType = 22
|
|
elif cableTypeOrg in (1181, 1182, 1183):
|
|
cableType = 118
|
|
elif cableTypeOrg in (1110, 1120, 1130, 1140):
|
|
cableType = 11
|
|
elif cableTypeOrg in (1210, 1220, 1230, 1240):
|
|
cableType = 12
|
|
elif cableTypeOrg in (1231, 11232, 1233, 1234):
|
|
cableType = 123
|
|
elif cableTypeOrg in (1161, 1162, 1163, 1164):
|
|
cableType = 116
|
|
|
|
if cableType == 11:
|
|
cableType = 1
|
|
sectorAna = 1
|
|
elif cableType == 12:
|
|
cableType = 2
|
|
sectorAna = 1
|
|
|
|
return cableType, sectorAna
|
|
|
|
|
|
def _parse_settings(settings_arr, in_struct, mem):
|
|
"""完整解析Settings数组,对应MATLAB第586-1194行"""
|
|
s = mem['MatlabGateway']['settings']
|
|
n = len(settings_arr)
|
|
|
|
if n > 17:
|
|
s['videoOffs'] = int(settings_arr[17])
|
|
else:
|
|
s['videoOffs'] = 0
|
|
|
|
if n >= 7:
|
|
s['nominalData'] = settings_arr[1:7].copy()
|
|
else:
|
|
s['nominalData'] = np.zeros(6)
|
|
|
|
if 'tolchk' not in s:
|
|
s['tolchk'] = {}
|
|
if len(s['nominalData']) >= 6:
|
|
s['tolchk']['NomDM'] = s['nominalData'][4]
|
|
s['tolchk']['NomOSC'] = s['nominalData'][3]
|
|
s['tolchk']['NomISO'] = s['nominalData'][2]
|
|
s['tolchk']['NomISC'] = s['nominalData'][1]
|
|
s['tolchk']['NomCore'] = s['nominalData'][5]
|
|
|
|
if 'avgData' not in s:
|
|
s['avgData'] = {}
|
|
if n > 9:
|
|
s['avgData']['init'] = int(settings_arr[9])
|
|
if n > 10:
|
|
s['avgData']['video_req_time'] = settings_arr[10]
|
|
if n > 11:
|
|
s['avgData']['dia_insens'] = settings_arr[11]
|
|
mean_time_fac = 1
|
|
if n > 12:
|
|
s['avgData']['mean_time_dm'] = settings_arr[12] * mean_time_fac
|
|
if n > 13:
|
|
s['avgData']['lay_insens'] = settings_arr[13]
|
|
if n > 14:
|
|
s['avgData']['mean_time_lay'] = settings_arr[14] * mean_time_fac
|
|
if n > 15:
|
|
s['unit'] = int(settings_arr[15])
|
|
if n > 16:
|
|
s['bRotateXDir'] = int(settings_arr[16])
|
|
|
|
if 'plausiData' not in s:
|
|
s['plausiData'] = {}
|
|
if n > 19:
|
|
s['plausiData']['check_dm'] = int(settings_arr[19])
|
|
s['plausiData']['abs_limit_dm'] = settings_arr[20]
|
|
s['plausiData']['rel_limit_dm'] = settings_arr[21]
|
|
if n > 22:
|
|
s['plausiData']['check_lay'] = int(settings_arr[22])
|
|
s['plausiData']['abs_limit_lay'] = settings_arr[23]
|
|
s['plausiData']['rel_limit_lay'] = settings_arr[24]
|
|
|
|
if n >= 32:
|
|
gmd = settings_arr[24:32]
|
|
if 'geometryData' not in s:
|
|
s['geometryData'] = {'x': {}, 'y': {}}
|
|
s['geometryData']['x']['x0'] = gmd[0]
|
|
s['geometryData']['y']['x0'] = gmd[1]
|
|
s['geometryData']['x']['y0'] = gmd[2]
|
|
s['geometryData']['y']['y0'] = gmd[3]
|
|
s['geometryData']['x']['xCCD'] = gmd[4]
|
|
s['geometryData']['y']['xCCD'] = gmd[5]
|
|
s['geometryData']['x']['yCCD'] = gmd[6]
|
|
s['geometryData']['y']['yCCD'] = gmd[7]
|
|
|
|
if 'correctionData' not in s:
|
|
s['correctionData'] = {'x': np.array([]), 'y': np.array([])}
|
|
if 'gap' not in s:
|
|
s['gap'] = {'x': np.array([]), 'y': np.array([]),
|
|
'dxCCD': {'x': 0, 'y': 0}}
|
|
|
|
if n > 33:
|
|
devicetype = int(settings_arr[33])
|
|
if devicetype < 500 or devicetype > 8101:
|
|
devicetype = 8000
|
|
s['version']['devicetype'] = devicetype
|
|
|
|
if n > 35:
|
|
s['cableStructure'] = int(settings_arr[35])
|
|
|
|
ind = 36
|
|
if ind < n:
|
|
anz = int(settings_arr[ind])
|
|
if anz > 0 and ind + anz < n:
|
|
s['correctionData']['x'] = settings_arr[ind + 1:ind + anz + 1].copy()
|
|
ind = ind + anz + 1
|
|
|
|
if ind < n:
|
|
anz = int(settings_arr[ind])
|
|
if anz > 0 and ind + anz < n:
|
|
s['correctionData']['y'] = settings_arr[ind + 1:ind + anz + 1].copy()
|
|
ind = ind + anz + 1
|
|
|
|
if ind < n:
|
|
s['gap']['dxCCD']['x'] = settings_arr[ind]
|
|
ind += 1
|
|
if ind < n:
|
|
Ngapx = int(settings_arr[ind])
|
|
ind += 1
|
|
if Ngapx > 0 and ind + 2 * Ngapx <= n:
|
|
gap_x = np.zeros((4, Ngapx))
|
|
gap_x[0, :] = settings_arr[ind:ind + Ngapx]
|
|
ind += Ngapx
|
|
gap_x[1, :] = settings_arr[ind:ind + Ngapx]
|
|
ind += Ngapx
|
|
s['gap']['x'] = gap_x
|
|
else:
|
|
ind += 2 * Ngapx
|
|
|
|
if ind < n:
|
|
s['gap']['dxCCD']['y'] = settings_arr[ind]
|
|
ind += 1
|
|
if ind < n:
|
|
Ngapy = int(settings_arr[ind])
|
|
ind += 1
|
|
if Ngapy > 0 and ind + 2 * Ngapy <= n:
|
|
gap_y = np.zeros((4, Ngapy))
|
|
gap_y[0, :] = settings_arr[ind:ind + Ngapy]
|
|
ind += Ngapy
|
|
gap_y[1, :] = settings_arr[ind:ind + Ngapy]
|
|
ind += Ngapy
|
|
s['gap']['y'] = gap_y
|
|
else:
|
|
ind += 2 * Ngapy
|
|
|
|
if 'geometryData' not in s:
|
|
s['geometryData'] = {'x': {}, 'y': {}}
|
|
s['geometryData']['x']['gamma'] = np.array([])
|
|
s['geometryData']['y']['gamma'] = np.array([])
|
|
if ind + 1 < n:
|
|
s['geometryData']['x']['gamma'] = settings_arr[ind]
|
|
ind += 1
|
|
s['geometryData']['y']['gamma'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
if 'cableData' not in s:
|
|
s['cableData'] = {}
|
|
s['cableData']['baseAngle'] = np.array([])
|
|
s['cableData']['orientation'] = np.array([])
|
|
if ind + 1 < n:
|
|
s['cableData']['baseAngle'] = settings_arr[ind]
|
|
ind += 1
|
|
s['cableData']['orientation'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
s['cableData']['nomHeight'] = np.array([])
|
|
s['cableData']['nomWidth'] = np.array([])
|
|
s['cableData']['threshold'] = np.array([])
|
|
if ind + 2 < n:
|
|
s['cableData']['nomHeight'] = settings_arr[ind]
|
|
ind += 1
|
|
s['cableData']['nomWidth'] = settings_arr[ind]
|
|
ind += 1
|
|
s['cableData']['threshold'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
s['eightpoint'] = np.array([])
|
|
if ind < n:
|
|
s['eightpoint'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
s['cableData']['nomR1'] = np.array([])
|
|
s['cableData']['nomR2'] = np.array([])
|
|
s['cableData']['twistMaximum'] = np.array([])
|
|
if 'attprofsett' not in s:
|
|
s['attprofsett'] = {}
|
|
s['attprofsett']['mode'] = np.array([])
|
|
s['attprofsett']['outer_margin'] = np.array([])
|
|
s['attprofsett']['inner_margin'] = np.array([])
|
|
s['attprofsett']['ringsize'] = np.array([])
|
|
s['attprofsett']['meantime'] = np.array([])
|
|
s['attprofsett']['refattfactor'] = np.array([])
|
|
if ind + 8 < n:
|
|
s['cableData']['nomR1'] = settings_arr[ind]
|
|
ind += 1
|
|
s['cableData']['nomR2'] = settings_arr[ind]
|
|
ind += 1
|
|
s['cableData']['twistMaximum'] = settings_arr[ind]
|
|
ind += 1
|
|
s['attprofsett']['mode'] = int(settings_arr[ind])
|
|
ind += 1
|
|
s['attprofsett']['outer_margin'] = settings_arr[ind]
|
|
ind += 1
|
|
s['attprofsett']['inner_margin'] = settings_arr[ind]
|
|
ind += 1
|
|
s['attprofsett']['ringsize'] = settings_arr[ind]
|
|
ind += 1
|
|
s['attprofsett']['meantime'] = settings_arr[ind]
|
|
ind += 1
|
|
s['attprofsett']['refattfactor'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
s['avgData']['mean_time_vw'] = np.array([])
|
|
if ind < n:
|
|
s['avgData']['mean_time_vw'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
mem['MatlabGateway']['err_meas_head'] = np.zeros((2, 1))
|
|
s['avgData']['dia_warninsens'] = np.array([])
|
|
s['avgData']['lay_warninsens'] = np.array([])
|
|
if ind + 3 < n:
|
|
mem['MatlabGateway']['err_meas_head'][0, 0] = settings_arr[ind]
|
|
ind += 1
|
|
mem['MatlabGateway']['err_meas_head'][1, 0] = settings_arr[ind]
|
|
ind += 1
|
|
s['avgData']['dia_warninsens'] = settings_arr[ind]
|
|
ind += 1
|
|
s['avgData']['lay_warninsens'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
devicetype = s['version'].get('devicetype', 8000)
|
|
s['avgData']['xray8k'] = (devicetype >= 8000 and devicetype <= 8101)
|
|
|
|
if 'voiddetectsett' not in s:
|
|
s['voiddetectsett'] = {}
|
|
s['voiddetectsett']['on'] = np.array([])
|
|
s['voiddetectsett']['maxerrdiam'] = np.array([])
|
|
if ind + 1 < n:
|
|
s['voiddetectsett']['on'] = int(settings_arr[ind])
|
|
ind += 1
|
|
s['voiddetectsett']['maxerrdiam'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
s['avgData']['reduceavgon'] = np.array([])
|
|
if ind < n:
|
|
s['avgData']['reduceavgon'] = int(settings_arr[ind])
|
|
ind += 1
|
|
|
|
s['dm_laser_core'] = np.array([])
|
|
if ind < n:
|
|
s['dm_laser_core'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
s['avgData']['determine_distance'] = np.array([])
|
|
if ind < n:
|
|
s['avgData']['determine_distance'] = int(settings_arr[ind])
|
|
ind += 1
|
|
|
|
s['tolchk']['NomWTH'] = np.array([])
|
|
s['tolchk']['PtolDMmean'] = np.array([])
|
|
s['tolchk']['NtolDMmean'] = np.array([])
|
|
s['tolchk']['PtolDM'] = np.array([])
|
|
s['tolchk']['NtolDM'] = np.array([])
|
|
s['tolchk']['PtolOSCmean'] = np.array([])
|
|
s['tolchk']['NtolOSCmean'] = np.array([])
|
|
s['tolchk']['PtolOSC'] = np.array([])
|
|
s['tolchk']['NtolOSC'] = np.array([])
|
|
s['tolchk']['PtolOSCecc'] = np.array([])
|
|
s['tolchk']['PtolISOmean'] = np.array([])
|
|
s['tolchk']['NtolISCmean'] = np.array([])
|
|
s['tolchk']['PtolISO'] = np.array([])
|
|
s['tolchk']['NtolISO'] = np.array([])
|
|
s['tolchk']['PtolISOecc'] = np.array([])
|
|
s['tolchk']['NtolISOmean'] = np.array([])
|
|
s['tolchk']['PtolISCmean'] = np.array([])
|
|
s['tolchk']['PtolISC'] = np.array([])
|
|
s['tolchk']['NtolISC'] = np.array([])
|
|
s['tolchk']['PtolISCecc'] = np.array([])
|
|
s['tolchk']['PtolWTHmean'] = np.array([])
|
|
s['tolchk']['NtolWTHmean'] = np.array([])
|
|
s['tolchk']['PtolWTH'] = np.array([])
|
|
s['tolchk']['NtolWTH'] = np.array([])
|
|
s['tolchk']['PtolWTHecc'] = np.array([])
|
|
s['tolchk']['PtolCoremean'] = np.array([])
|
|
s['tolchk']['NtolCoremean'] = np.array([])
|
|
s['tolchk']['PtolCore'] = np.array([])
|
|
s['tolchk']['NtolCore'] = np.array([])
|
|
|
|
if ind + 28 <= n:
|
|
s['tolchk']['NomWTH'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolDMmean'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['NtolDMmean'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolDM'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['NtolDM'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolOSCmean'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['NtolOSCmean'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolOSC'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['NtolOSC'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolOSCecc'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolISOmean'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['NtolISCmean'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolISO'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['NtolISO'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolISOecc'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['NtolISOmean'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolISCmean'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolISC'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['NtolISC'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolISCecc'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolWTHmean'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['NtolWTHmean'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolWTH'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['NtolWTH'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolWTHecc'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolCoremean'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['NtolCoremean'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['PtolCore'] = settings_arr[ind]
|
|
ind += 1
|
|
s['tolchk']['NtolCore'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
s['AutoDetHVon'] = np.array([])
|
|
if ind < n:
|
|
s['AutoDetHVon'] = int(settings_arr[ind])
|
|
ind += 1
|
|
|
|
s['ProdType'] = np.array([])
|
|
if ind < n:
|
|
s['ProdType'] = int(settings_arr[ind])
|
|
ind += 1
|
|
|
|
s['VideoRec'] = np.array([])
|
|
if ind < n:
|
|
s['VideoRec'] = int(settings_arr[ind])
|
|
ind += 1
|
|
|
|
s['VideoRecNr'] = np.array([])
|
|
if ind < n:
|
|
s['VideoRecNr'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
s['voltage'] = np.array([])
|
|
if ind < n:
|
|
s['voltage'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
s['TwistAngle'] = 0
|
|
if ind < n:
|
|
s['TwistAngle'] = settings_arr[ind] * np.pi / 180
|
|
ind += 1
|
|
|
|
s['RiffleHeight'] = 0
|
|
if ind < n:
|
|
s['RiffleHeight'] = settings_arr[ind]
|
|
if s['RiffleHeight'] <= 0:
|
|
s['RiffleHeight'] = 0
|
|
ind += 1
|
|
|
|
s['RiffleTopWidth'] = 0
|
|
if ind < n:
|
|
s['RiffleTopWidth'] = settings_arr[ind]
|
|
if s['RiffleTopWidth'] <= 0:
|
|
s['RiffleTopWidth'] = 0
|
|
ind += 1
|
|
|
|
s['RiffleBaseWidth'] = 0
|
|
if ind < n:
|
|
s['RiffleBaseWidth'] = settings_arr[ind]
|
|
if s['RiffleBaseWidth'] <= 0:
|
|
s['RiffleBaseWidth'] = 0
|
|
ind += 1
|
|
|
|
s['RiffleCount'] = 0
|
|
if ind < n:
|
|
s['RiffleCount'] = int(settings_arr[ind])
|
|
if s['RiffleCount'] <= 0:
|
|
s['RiffleCount'] = 0
|
|
ind += 1
|
|
|
|
s['Reconstruct'] = 0
|
|
if ind < n:
|
|
s['Reconstruct'] = int(settings_arr[ind])
|
|
if s['Reconstruct'] < 0 or s['Reconstruct'] > 4:
|
|
s['Reconstruct'] = 0
|
|
ind += 1
|
|
|
|
s['rest'] = np.array([])
|
|
if ind + 2 < n:
|
|
s['rest'] = settings_arr[ind:ind + 3].copy()
|
|
ind += 3
|
|
|
|
s['paraECClimit'] = np.array([])
|
|
if ind < n:
|
|
s['paraECClimit'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
s['paraECCmin'] = np.array([])
|
|
if ind < n:
|
|
s['paraECCmin'] = settings_arr[ind]
|
|
ind += 1
|
|
|
|
if ind < n:
|
|
rest_arr = settings_arr[ind:].copy()
|
|
if len(rest_arr) > 0:
|
|
if isinstance(s.get('rest'), np.ndarray) and s['rest'].size > 0:
|
|
s['rest'] = np.concatenate([s['rest'], rest_arr])
|
|
else:
|
|
s['rest'] = rest_arr
|
|
|
|
return mem
|
|
|
|
|
|
def _init_mem(settings_arr, in_struct):
|
|
mem = {'MatlabGateway': {}, 'Unsharpness': {}}
|
|
mem['MatlabGateway']['settings'] = {}
|
|
mem['MatlabGateway']['settings']['confData'] = np.array([])
|
|
mem['MatlabGateway']['settings']['geometryData'] = {'x': {}, 'y': {}}
|
|
|
|
if len(settings_arr) >= 32:
|
|
gmd = settings_arr[24:32]
|
|
mem['MatlabGateway']['settings']['geometryData']['x']['x0'] = gmd[0]
|
|
mem['MatlabGateway']['settings']['geometryData']['y']['x0'] = gmd[1]
|
|
mem['MatlabGateway']['settings']['geometryData']['x']['y0'] = gmd[2]
|
|
mem['MatlabGateway']['settings']['geometryData']['y']['y0'] = gmd[3]
|
|
mem['MatlabGateway']['settings']['geometryData']['x']['xCCD'] = gmd[4]
|
|
mem['MatlabGateway']['settings']['geometryData']['y']['xCCD'] = gmd[5]
|
|
mem['MatlabGateway']['settings']['geometryData']['x']['yCCD'] = gmd[6]
|
|
mem['MatlabGateway']['settings']['geometryData']['y']['yCCD'] = gmd[7]
|
|
|
|
mem['MatlabGateway']['rawIntensity'] = {'x': np.array([]), 'y': np.array([])}
|
|
mem['MatlabGateway']['refIntensity'] = {
|
|
'bright': {'x': np.array([]), 'y': np.array([])},
|
|
'dark': {'static': {'x': np.array([]), 'y': np.array([])},
|
|
'dynamic': {'x': np.array([]), 'y': np.array([])}},
|
|
}
|
|
mem['MatlabGateway']['StoreOption'] = 0
|
|
mem['MatlabGateway']['restartRefVideo'] = settings_arr[32] if len(settings_arr) > 32 else 0
|
|
mem['MatlabGateway']['settings']['calib_struct'] = {'int': np.array([]), 'ext': np.array([])}
|
|
mem['Unsharpness']['FiltMatrix_X'] = np.array([])
|
|
mem['Unsharpness']['FiltMatrix_Y'] = np.array([])
|
|
mem['MatlabGateway']['Debugdata'] = {'Errorcounter': 0}
|
|
|
|
mem['MatlabGateway']['settings']['version'] = {'NXT': in_struct.get('NXT', 0)}
|
|
mem['MatlabGateway']['settings']['cableTypeOrg'] = settings_arr[7] if len(settings_arr) > 7 else 0
|
|
|
|
mem = _parse_settings(settings_arr, in_struct, mem)
|
|
|
|
return mem
|
|
|
|
|
|
def _safe_get(obj, key, default=None):
|
|
"""安全获取字段,支持 dict 和 mat_struct"""
|
|
if isinstance(obj, dict):
|
|
return obj.get(key, default)
|
|
if hasattr(obj, key):
|
|
val = getattr(obj, key)
|
|
if isinstance(val, np.ndarray) and val.size == 1:
|
|
return val.flat[0]
|
|
return val
|
|
return default
|
|
|
|
|
|
def _safe_has(obj, key):
|
|
"""安全检查字段是否存在,支持 dict 和 mat_struct"""
|
|
if isinstance(obj, dict):
|
|
return key in obj
|
|
return hasattr(obj, key)
|
|
|
|
|
|
def matlabgateway(in_struct):
|
|
# 转换 mat_struct 为 dict(如果需要)
|
|
if not isinstance(in_struct, dict) and (
|
|
hasattr(in_struct, '_fieldnames') or
|
|
(isinstance(in_struct, np.ndarray) and in_struct.size > 0 and
|
|
hasattr(in_struct.flat[0], '_fieldnames'))):
|
|
in_struct = _mat_struct_to_dict(in_struct)
|
|
|
|
OutStruct = {}
|
|
memStruct = {}
|
|
|
|
OutStruct['GatewayStatus'] = np.array([])
|
|
OutStruct['AnaVersion'] = np.array([])
|
|
OutStruct['WtOSC'] = np.array([])
|
|
OutStruct['WtINS'] = np.array([])
|
|
OutStruct['WtISC'] = np.array([])
|
|
OutStruct['WtALL'] = np.array([])
|
|
OutStruct['DmCORE'] = np.array([])
|
|
OutStruct['DmALL'] = np.array([])
|
|
OutStruct['DmINS'] = np.array([])
|
|
OutStruct['DmISC'] = np.array([])
|
|
OutStruct['WtBis'] = np.array([])
|
|
OutStruct['MMAng'] = np.array([])
|
|
OutStruct['AttCoeff'] = np.array([])
|
|
OutStruct['AttCoeffSt'] = np.array([])
|
|
OutStruct['VW'] = np.array([])
|
|
OutStruct['xyPos'] = np.array([])
|
|
OutStruct['Warning'] = np.array([])
|
|
OutStruct['Void'] = np.array([])
|
|
OutStruct['Edges'] = np.array([])
|
|
OutStruct['Tolcheckout'] = np.array([])
|
|
OutStruct['AutoDet'] = np.array([])
|
|
|
|
has_iIntensX = 'iIntensX' in in_struct
|
|
if has_iIntensX:
|
|
OutStruct['NormVideoX'] = np.array([])
|
|
OutStruct['NormVideoY'] = np.array([])
|
|
OutStruct['EdgesLeftX'] = np.array([])
|
|
OutStruct['EdgesRightX'] = np.array([])
|
|
OutStruct['EdgesLeftY'] = np.array([])
|
|
OutStruct['EdgesRightY'] = np.array([])
|
|
else:
|
|
for i in range(1, 9):
|
|
OutStruct[f'NormVideo1{i}'] = np.array([])
|
|
OutStruct[f'NormVideo2{i}'] = np.array([])
|
|
OutStruct[f'EdgesLeft1{i}'] = np.array([])
|
|
OutStruct[f'EdgesLeft2{i}'] = np.array([])
|
|
OutStruct[f'EdgesRight1{i}'] = np.array([])
|
|
OutStruct[f'EdgesRight2{i}'] = np.array([])
|
|
|
|
OutStruct['ScanWay'] = np.zeros((1, 4))
|
|
OutStruct['Debugdata'] = {'Errorcounter': 0}
|
|
if has_iIntensX:
|
|
OutStruct['Debugdata']['dmOut'] = np.zeros((3, 2))
|
|
else:
|
|
OutStruct['Debugdata']['dmOut'] = np.zeros((3, 14))
|
|
|
|
mem = None
|
|
global _Lsq_LM_on, _Unsharpness
|
|
_Lsq_LM_on = 0
|
|
_Unsharpness = 0
|
|
try:
|
|
from analysis_utils import startx2ana
|
|
from overview_utils import startx8ana, ovrview
|
|
|
|
settings_arr = np.asarray(in_struct.get('Settings', np.zeros(200)), dtype=np.float64)
|
|
|
|
mem = get_user_data()
|
|
is_mem_new = (mem is None or 'MatlabGateway' not in mem)
|
|
if is_mem_new:
|
|
mem = _init_mem(settings_arr, in_struct)
|
|
# 读取配置文件
|
|
config_file = in_struct.get('ConfigFile', '')
|
|
confData = mem['MatlabGateway']['settings'].get('confData', np.array([]))
|
|
if (config_file and len(config_file) > 0 and
|
|
(not isinstance(confData, np.ndarray) or confData.size == 0)):
|
|
import os
|
|
if os.path.isfile(config_file):
|
|
from calibration_utils import floatread
|
|
mem['MatlabGateway']['settings']['confData'] = floatread(config_file, 1)
|
|
else:
|
|
# 尝试在 ConfigFiles 目录中查找
|
|
local_cfg = os.path.join(
|
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
|
'ConfigFiles', 'confx2.prn')
|
|
if os.path.isfile(local_cfg):
|
|
from calibration_utils import floatread
|
|
mem['MatlabGateway']['settings']['confData'] = floatread(local_cfg, 1)
|
|
# 设置 confData[19] = cableType (对应 MATLAB confData(20))
|
|
confData = mem['MatlabGateway']['settings'].get('confData', np.array([]))
|
|
if isinstance(confData, np.ndarray) and confData.size > 19 and len(settings_arr) > 7:
|
|
confData[19] = settings_arr[7]
|
|
# 计算 dx = conf[31] * conf[30],对应 MATLAB chksettings
|
|
if isinstance(confData, np.ndarray) and confData.size > 91:
|
|
confData[89] = confData[31] * confData[30] if confData.size > 31 else 0
|
|
confData[90] = 1
|
|
confData[91] = confData[89] / confData[90] if confData[90] != 0 else 0.048
|
|
if confData[91] == 0:
|
|
confData[91] = 0.048
|
|
|
|
# 加载校准数据(对应 MATLAB matlabgateway.m 第 661-715 行)
|
|
calib_int = mem['MatlabGateway']['settings'].get('calib_struct', {}).get('int', np.array([]))
|
|
config_file = in_struct.get('ConfigFile', '')
|
|
if (not isinstance(calib_int, dict) or len(calib_int) == 0) and len(config_file) > 10:
|
|
import os
|
|
from calibration_utils import read_calibration
|
|
|
|
devicetype = mem['MatlabGateway']['settings'].get('version', {}).get('devicetype', 8000)
|
|
# 对应 MATLAB switch-case 语句(matlabgateway.m 第 663-707 行)
|
|
califile_map = {
|
|
500: 'Internal_Layer_Calibration_2120.cfg',
|
|
501: 'Internal_Layer_Calibration_2120.cfg',
|
|
502: 'Internal_Layer_Calibration_2035.cfg',
|
|
503: 'Internal_Layer_Calibration_2080.cfg',
|
|
504: 'Internal_Layer_Calibration_2300.cfg',
|
|
505: 'Internal_Layer_Calibration_2060.cfg',
|
|
506: 'Internal_Layer_Calibration_2200.cfg',
|
|
507: 'Internal_Layer_Calibration_2120.cfg',
|
|
508: 'Internal_Layer_Calibration_2120.cfg',
|
|
8000: 'Internal_Layer_Calibration_8000.cfg',
|
|
8001: 'Internal_Layer_Calibration_8000.cfg',
|
|
8100: 'Internal_Layer_Calibration_8100.cfg',
|
|
8101: 'Internal_Layer_Calibration_8100.cfg',
|
|
}
|
|
califile_name = califile_map.get(devicetype, 'Internal_Layer_Calibration_xxxx.cfg')
|
|
if devicetype not in califile_map:
|
|
print(f'[matlabgateway] Warning: Unknown measuring head devicetype={devicetype}')
|
|
|
|
# 尝试从 ConfigFile 同目录中查找
|
|
cfg_dir = os.path.dirname(config_file)
|
|
califile = os.path.join(cfg_dir, califile_name)
|
|
if not os.path.isfile(califile):
|
|
# 尝试在项目 ConfigFiles 目录中查找
|
|
local_calib = os.path.join(
|
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
|
'ConfigFiles', califile_name)
|
|
if os.path.isfile(local_calib):
|
|
califile = local_calib
|
|
else:
|
|
califile = ''
|
|
|
|
if califile and os.path.isfile(califile):
|
|
calib_data = read_calibration(califile)
|
|
if isinstance(calib_data, dict) and len(calib_data) > 0:
|
|
mem['MatlabGateway']['settings']['calib_struct']['int'] = calib_data
|
|
else:
|
|
if len(settings_arr) >= 32:
|
|
gmd = settings_arr[24:32]
|
|
if 'geometryData' not in mem['MatlabGateway']['settings']:
|
|
mem['MatlabGateway']['settings']['geometryData'] = {'x': {}, 'y': {}}
|
|
mem['MatlabGateway']['settings']['geometryData']['x']['x0'] = gmd[0]
|
|
mem['MatlabGateway']['settings']['geometryData']['y']['x0'] = gmd[1]
|
|
mem['MatlabGateway']['settings']['geometryData']['x']['y0'] = gmd[2]
|
|
mem['MatlabGateway']['settings']['geometryData']['y']['y0'] = gmd[3]
|
|
mem['MatlabGateway']['settings']['geometryData']['x']['xCCD'] = gmd[4]
|
|
mem['MatlabGateway']['settings']['geometryData']['y']['xCCD'] = gmd[5]
|
|
mem['MatlabGateway']['settings']['geometryData']['x']['yCCD'] = gmd[6]
|
|
mem['MatlabGateway']['settings']['geometryData']['y']['yCCD'] = gmd[7]
|
|
mem['MatlabGateway']['settings']['version'] = {'NXT': in_struct.get('NXT', 0)}
|
|
mem['MatlabGateway']['settings']['cableTypeOrg'] = settings_arr[7] if len(settings_arr) > 7 else 0
|
|
mem = _parse_settings(settings_arr, in_struct, mem)
|
|
|
|
cableTypeOrg = mem['MatlabGateway']['settings'].get('cableTypeOrg', 0)
|
|
cableType, sectorAna = _convert_cable_type(cableTypeOrg)
|
|
mem['MatlabGateway']['settings']['cableType'] = cableType
|
|
mem['MatlabGateway']['settings']['sectorAna'] = sectorAna
|
|
|
|
if _Unsharpness == 1 and (cableTypeOrg < 51 or cableTypeOrg > 53):
|
|
fx = mem['Unsharpness'].get('FiltMatrix_X', np.array([]))
|
|
fy = mem['Unsharpness'].get('FiltMatrix_Y', np.array([]))
|
|
if (not isinstance(fx, np.ndarray) or fx.size == 0 or
|
|
not isinstance(fy, np.ndarray) or fy.size == 0):
|
|
devicetype = settings_arr[33] if len(settings_arr) > 33 else 0
|
|
devicetype_int = int(devicetype)
|
|
print(f'[matlabgateway] Unsharpness enabled but not yet supported '
|
|
f'(device type {devicetype_int}). GenFiltMatrix and FiltPara_*.mat '
|
|
f'loading are not implemented in Python version.')
|
|
|
|
IntensType = int(settings_arr[0]) if len(settings_arr) > 0 else 0
|
|
|
|
if has_iIntensX:
|
|
if IntensType == 0 or IntensType == 4 or IntensType == 5:
|
|
mem['MatlabGateway']['rawIntensity']['x'] = np.asarray(in_struct.get('iIntensX', []), dtype=np.float64)
|
|
mem['MatlabGateway']['rawIntensity']['y'] = np.asarray(in_struct.get('iIntensY', []), dtype=np.float64)
|
|
if IntensType == 1:
|
|
mem['MatlabGateway']['refIntensity']['bright']['x'] = np.asarray(in_struct.get('iIntensX', []), dtype=np.float64)
|
|
mem['MatlabGateway']['refIntensity']['bright']['y'] = np.asarray(in_struct.get('iIntensY', []), dtype=np.float64)
|
|
if IntensType == 2:
|
|
mem['MatlabGateway']['refIntensity']['dark']['static']['x'] = np.asarray(in_struct.get('iIntensX', []), dtype=np.float64)
|
|
mem['MatlabGateway']['refIntensity']['dark']['static']['y'] = np.asarray(in_struct.get('iIntensY', []), dtype=np.float64)
|
|
if IntensType == 3:
|
|
mem['MatlabGateway']['refIntensity']['dark']['dynamic']['x'] = np.asarray(in_struct.get('iIntensX', []), dtype=np.float64)
|
|
mem['MatlabGateway']['refIntensity']['dark']['dynamic']['y'] = np.asarray(in_struct.get('iIntensY', []), dtype=np.float64)
|
|
|
|
if IntensType == 0:
|
|
mem['MatlabGateway']['refIntensity']['bright']['x'] = np.asarray(in_struct.get('iBrightX', []), dtype=np.float64)
|
|
mem['MatlabGateway']['refIntensity']['bright']['y'] = np.asarray(in_struct.get('iBrightY', []), dtype=np.float64)
|
|
mem['MatlabGateway']['refIntensity']['dark']['static']['x'] = np.asarray(in_struct.get('iDarkStaticX', []), dtype=np.float64)
|
|
mem['MatlabGateway']['refIntensity']['dark']['static']['y'] = np.asarray(in_struct.get('iDarkStaticY', []), dtype=np.float64)
|
|
mem['MatlabGateway']['refIntensity']['dark']['dynamic']['x'] = np.asarray(in_struct.get('iDarkDynamicX', []), dtype=np.float64)
|
|
mem['MatlabGateway']['refIntensity']['dark']['dynamic']['y'] = np.asarray(in_struct.get('iDarkDynamicY', []), dtype=np.float64)
|
|
|
|
if IntensType in (7, 8, 9):
|
|
raw_list = []
|
|
prefixes = []
|
|
if IntensType == 7:
|
|
prefixes = ['11', '12', '13', '14', '15', '16', '17', '18']
|
|
elif IntensType == 8:
|
|
prefixes = ['21', '22', '23', '24', '25', '26', '27', '28']
|
|
elif IntensType == 9:
|
|
prefixes = ['11', '12', '13', '14', '15', '16', '17', '18',
|
|
'21', '22', '23', '24', '25', '26', '27', '28']
|
|
for p in prefixes:
|
|
kx = f'iIntens{p[:1]}{p[1:]}' if len(p) == 2 else f'iIntens{p}'
|
|
ky = kx
|
|
x_data = in_struct.get(f'iIntens{p}', np.array([]))
|
|
y_data = in_struct.get(f'iIntens{p}', np.array([]))
|
|
if isinstance(x_data, np.ndarray) and x_data.size > 0:
|
|
raw_list.append({
|
|
'x': np.asarray(x_data, dtype=np.float64),
|
|
'y': np.asarray(y_data, dtype=np.float64)
|
|
})
|
|
if len(raw_list) > 0:
|
|
mem['MatlabGateway']['rawIntensity'] = raw_list
|
|
|
|
new_restartRefVideo = settings_arr[32] if len(settings_arr) > 32 else 0
|
|
if new_restartRefVideo != mem['MatlabGateway'].get('restartRefVideo', 0):
|
|
mem['MatlabGateway']['restartRefVideo'] = new_restartRefVideo
|
|
mem['MatlabGateway']['refIntensity']['bright']['x'] = np.array([])
|
|
mem['MatlabGateway']['refIntensity']['dark']['static']['x'] = np.array([])
|
|
mem['MatlabGateway']['refIntensity']['dark']['dynamic']['x'] = np.array([])
|
|
|
|
gatewayStatus = 0
|
|
|
|
bright_x = mem['MatlabGateway']['refIntensity']['bright'].get('x', np.array([]))
|
|
dark_static_x = mem['MatlabGateway']['refIntensity']['dark']['static'].get('x', np.array([]))
|
|
dark_dynamic_x = mem['MatlabGateway']['refIntensity']['dark']['dynamic'].get('x', np.array([]))
|
|
|
|
if isinstance(bright_x, np.ndarray) and bright_x.size == 0:
|
|
gatewayStatus |= 2
|
|
if isinstance(dark_static_x, np.ndarray) and dark_static_x.size == 0:
|
|
gatewayStatus |= 4
|
|
if isinstance(dark_dynamic_x, np.ndarray) and dark_dynamic_x.size == 0:
|
|
gatewayStatus |= 8
|
|
elif isinstance(dark_dynamic_x, np.ndarray) and np.mean(dark_dynamic_x) < 1:
|
|
gatewayStatus |= 8
|
|
|
|
if IntensType in (4, 5, 7, 8, 9):
|
|
gatewayStatus = 0
|
|
|
|
if not has_iIntensX:
|
|
raw_list = in_struct.get('rawIntensity', [])
|
|
if isinstance(raw_list, list):
|
|
mem['MatlabGateway']['rawIntensity'] = raw_list
|
|
ref_list = in_struct.get('refIntensity', [])
|
|
if isinstance(ref_list, list):
|
|
mem['MatlabGateway']['refIntensity'] = ref_list
|
|
sensorStatus_raw = in_struct.get('sensorStatus', np.zeros((20,)))
|
|
sensorStatus_arr = np.asarray(sensorStatus_raw).flatten()
|
|
sensorStatus_decoded = np.zeros((20, 16), dtype=np.uint16)
|
|
for i in range(min(20, len(sensorStatus_arr))):
|
|
val = int(sensorStatus_arr[i])
|
|
for bit in range(16):
|
|
sensorStatus_decoded[i, bit] = (val >> bit) & 1
|
|
mem['MatlabGateway']['sensorStatus'] = sensorStatus_decoded
|
|
|
|
if IntensType in (0, 4, 5, 7, 8, 9) and gatewayStatus == 0:
|
|
if IntensType == 0 and has_iIntensX:
|
|
rawvideo = [mem['MatlabGateway']['rawIntensity']['x'],
|
|
mem['MatlabGateway']['rawIntensity']['y']]
|
|
rawbrightvideo = [mem['MatlabGateway']['refIntensity']['bright']['x'],
|
|
mem['MatlabGateway']['refIntensity']['bright']['y']]
|
|
rawvideoDark_static = [mem['MatlabGateway']['refIntensity']['dark']['static']['x'],
|
|
mem['MatlabGateway']['refIntensity']['dark']['static']['y']]
|
|
rawvideoDark_dynamic = [mem['MatlabGateway']['refIntensity']['dark']['dynamic']['x'],
|
|
mem['MatlabGateway']['refIntensity']['dark']['dynamic']['y']]
|
|
rawdarkvideo = rawvideoDark_dynamic
|
|
|
|
settings = mem['MatlabGateway']['settings']
|
|
errsettings = mem['MatlabGateway']['err_meas_head']
|
|
mem_local = {}
|
|
init = 1
|
|
|
|
if _Unsharpness == 1:
|
|
print('[matlabgateway] Unsharpness mode for startx2ana is not yet supported. '
|
|
'Falling back to normal mode.')
|
|
|
|
(avgresults, results, edges, status_x, status_y,
|
|
attL_x, attR_x, attL_y, attR_y, errnorm,
|
|
AutoDet, mem_local, IN_x, IN_y, AttCoeff, AttCoeffSt, Void) = startx2ana(
|
|
rawvideo, rawdarkvideo, rawvideoDark_static, rawvideoDark_dynamic,
|
|
rawbrightvideo, settings, errsettings, mem_local, init
|
|
)
|
|
|
|
OutStruct['AutoDet'] = AutoDet
|
|
OutStruct['AttCoeff'] = AttCoeff
|
|
OutStruct['AttCoeffSt'] = AttCoeffSt
|
|
OutStruct['Void'] = Void
|
|
|
|
_fill_outstruct_2k(OutStruct, avgresults, results, edges, status_x, status_y)
|
|
|
|
elif IntensType in (4, 5):
|
|
axis = 0 if IntensType == 4 else 1
|
|
settings = mem['MatlabGateway']['settings']
|
|
err_meas_head = mem['MatlabGateway']['err_meas_head']
|
|
sensorStatus = mem['MatlabGateway'].get('sensorStatus', np.zeros((20, 16)))
|
|
rawInt = mem['MatlabGateway'].get('rawIntensity', {})
|
|
if isinstance(rawInt, list) and len(rawInt) > 0:
|
|
rawInt_single = rawInt[0]
|
|
elif isinstance(rawInt, dict) and 'x' in rawInt:
|
|
rawInt_single = rawInt
|
|
else:
|
|
rawInt_single = {'x': np.array([]), 'y': np.array([])}
|
|
senPair = [1, 1]
|
|
|
|
(avgresults, results, edges, status, att, err, layeruse,
|
|
AttCoeff, AttCoeffSt, Void, AutoDet, ScanWay,
|
|
NormVideoX, NormVideoY, detail_a, detail_b) = startx8ana(
|
|
rawInt_single, settings, err_meas_head, sensorStatus, senPair, axis
|
|
)
|
|
|
|
OutStruct['AutoDet'] = AutoDet
|
|
OutStruct['AttCoeff'] = AttCoeff
|
|
OutStruct['AttCoeffSt'] = AttCoeffSt
|
|
OutStruct['Void'] = Void
|
|
OutStruct['ScanWay'] = ScanWay
|
|
if hasattr(NormVideoX, '__len__'):
|
|
OutStruct['NormVideoX'] = np.asarray(NormVideoX)
|
|
if hasattr(NormVideoY, '__len__'):
|
|
OutStruct['NormVideoY'] = np.asarray(NormVideoY)
|
|
|
|
# 调用 conv2dsp 计算综合结果
|
|
from conv2dsp_utils import conv2dsp
|
|
s = mem['MatlabGateway']['settings']
|
|
factMinWt = settings_arr[34] if len(settings_arr) > 34 else 1
|
|
devicetype_val = s.get('version', {}).get('devicetype', 8000)
|
|
NXT_val = s.get('version', {}).get('NXT', 0)
|
|
bRotateXDir_val = s.get('bRotateXDir', 0)
|
|
unit_val = s.get('unit', 0)
|
|
cableType_val = s.get('cableType', 0)
|
|
eightpoint_val = s.get('eightpoint', 0)
|
|
reduceavgon_val = s.get('avgData', {}).get('reduceavgon', 0)
|
|
twistAngle_val = s.get('TwistAngle', 0)
|
|
sectorAna_val = s.get('sectorAna', 0)
|
|
|
|
(OSC_c, ISO_c, ISC_c, WTH_c, DMTotal_c, DMCore_c, DMINS_c, DMISC_c,
|
|
BisecWTH_c, MinMaxAng_c) = conv2dsp(
|
|
avgresults, bRotateXDir_val, factMinWt, unit_val, layeruse,
|
|
cableType_val, eightpoint_val, reduceavgon_val, twistAngle_val,
|
|
s, devicetype_val, sectorAna_val, NXT_val
|
|
)
|
|
|
|
# 按 MATLAB 格式拼接 [value_row, status_row]
|
|
def _pack_result(val_arr):
|
|
a = np.asarray(val_arr, dtype=np.float64)
|
|
return np.concatenate([a[0, :], a[1, :]])
|
|
|
|
OutStruct['WtOSC'] = _pack_result(OSC_c)
|
|
OutStruct['WtINS'] = _pack_result(ISO_c)
|
|
OutStruct['WtISC'] = _pack_result(ISC_c)
|
|
OutStruct['WtALL'] = _pack_result(WTH_c)
|
|
OutStruct['DmCORE'] = _pack_result(DMCore_c)
|
|
OutStruct['DmALL'] = _pack_result(DMTotal_c)
|
|
OutStruct['DmINS'] = _pack_result(DMINS_c)
|
|
OutStruct['DmISC'] = _pack_result(DMISC_c)
|
|
OutStruct['WtBis'] = _pack_result(BisecWTH_c)
|
|
OutStruct['MMAng'] = _pack_result(MinMaxAng_c)
|
|
|
|
if 'left' in edges and 'right' in edges:
|
|
left_edges = edges['left']
|
|
right_edges = edges['right']
|
|
OutStruct['EdgesLeftX'] = left_edges.get('x', np.array([]))
|
|
OutStruct['EdgesLeftY'] = left_edges.get('y', np.array([]))
|
|
OutStruct['EdgesRightX'] = right_edges.get('x', np.array([]))
|
|
OutStruct['EdgesRightY'] = right_edges.get('y', np.array([]))
|
|
|
|
elif IntensType in (7, 8):
|
|
axis = 0 if IntensType == 7 else 1
|
|
settings = mem['MatlabGateway']['settings']
|
|
err_meas_head = mem['MatlabGateway']['err_meas_head']
|
|
sensorStatus = mem['MatlabGateway'].get('sensorStatus', np.zeros((20, 16)))
|
|
rawInt = mem['MatlabGateway'].get('rawIntensity', [])
|
|
if isinstance(rawInt, dict) and 'x' in rawInt:
|
|
rawInt_list = [rawInt]
|
|
elif isinstance(rawInt, list) and len(rawInt) > 0:
|
|
rawInt_list = rawInt
|
|
else:
|
|
rawInt_list = []
|
|
cableTypeOrg_val = settings.get('cableTypeOrg', 0)
|
|
|
|
if cableTypeOrg_val in (111, 2, 22, 116) and len(rawInt_list) > 0:
|
|
settings, err_meas_head = ovrview(rawInt_list, settings, err_meas_head, sensorStatus, axis)
|
|
|
|
num_sensors = len(rawInt_list)
|
|
NormVideoX_arr = []
|
|
NormVideoY_arr = []
|
|
|
|
for senPair in range(num_sensors):
|
|
settings_loc = copy.deepcopy(settings)
|
|
settings_loc['avgData'] = settings_loc.get('avgData', {})
|
|
if senPair > 0:
|
|
settings_loc['avgData']['init'] = 0
|
|
|
|
raw_sen = rawInt[senPair] if isinstance(rawInt, list) and senPair < len(rawInt) else rawInt
|
|
sen_pair_arr = [senPair + 1, num_sensors]
|
|
|
|
(avgresults_s, results_s, edges_s, status_s, att_s, err_s, layeruse_s,
|
|
AttCoeff_s, AttCoeffSt_s, Void_s, AutoDet_s, ScanWay_s,
|
|
NVx, NVy, da, db) = startx8ana(
|
|
raw_sen, settings_loc, err_meas_head, sensorStatus, sen_pair_arr, axis
|
|
)
|
|
|
|
if hasattr(NVx, '__len__'):
|
|
NormVideoX_arr.append(np.asarray(NVx))
|
|
if hasattr(NVy, '__len__'):
|
|
NormVideoY_arr.append(np.asarray(NVy))
|
|
|
|
prefix = '1' if axis == 0 else '2'
|
|
for i in range(min(4, len(NormVideoY_arr))):
|
|
OutStruct[f'NormVideo{prefix}{2*i+1}'] = NormVideoY_arr[i] if i < len(NormVideoY_arr) else np.array([])
|
|
OutStruct[f'NormVideo{prefix}{2*i+2}'] = NormVideoX_arr[i] if i < len(NormVideoX_arr) else np.array([])
|
|
|
|
OutStruct['GatewayStatus'] = np.array([np.uint16(gatewayStatus), np.uint16(0)])
|
|
memStruct = mem
|
|
|
|
except Exception as e:
|
|
import traceback
|
|
OutStruct['Warning'] = str(e) + '\n' + traceback.format_exc()
|
|
OutStruct['GatewayStatus'] = np.array([np.uint16(15), np.uint16(0)])
|
|
memStruct = mem if mem is not None else {}
|
|
|
|
finally:
|
|
if mem is not None:
|
|
set_user_data(mem)
|
|
|
|
return OutStruct, memStruct
|
|
|
|
|
|
def _fill_outstruct_2k(OutStruct, avgresults, results, edges, status_x, status_y):
|
|
if isinstance(avgresults, dict):
|
|
dmOut = avgresults.get('dmOut', np.zeros((3, 2)))
|
|
if isinstance(dmOut, np.ndarray):
|
|
OutStruct['DmALL'] = dmOut
|
|
|
|
coreDm = avgresults.get('coreDm', np.zeros((3, 2)))
|
|
if isinstance(coreDm, np.ndarray):
|
|
OutStruct['DmCORE'] = coreDm
|
|
|
|
left = avgresults.get('left', {})
|
|
right = avgresults.get('right', {})
|
|
if isinstance(left, dict):
|
|
osc = left.get('osc', np.zeros((3, 2)))
|
|
iso = left.get('iso', np.zeros((3, 2)))
|
|
isc = left.get('isc', np.zeros((3, 2)))
|
|
if isinstance(osc, np.ndarray):
|
|
OutStruct['WtOSC'] = osc
|
|
if isinstance(iso, np.ndarray):
|
|
OutStruct['WtINS'] = iso
|
|
if isinstance(isc, np.ndarray):
|
|
OutStruct['WtISC'] = isc
|
|
|
|
if isinstance(edges, dict):
|
|
left_edges = edges.get('left', {})
|
|
right_edges = edges.get('right', {})
|
|
if isinstance(left_edges, dict):
|
|
OutStruct['EdgesLeftX'] = left_edges.get('x', np.array([]))
|
|
OutStruct['EdgesLeftY'] = left_edges.get('y', np.array([]))
|
|
if isinstance(right_edges, dict):
|
|
OutStruct['EdgesRightX'] = right_edges.get('x', np.array([]))
|
|
OutStruct['EdgesRightY'] = right_edges.get('y', np.array([]))
|
|
|
|
|
|
def _mat_value_convert(val):
|
|
"""将MATLAB加载的值转换为Python原生类型"""
|
|
if isinstance(val, np.ndarray):
|
|
if val.size == 0:
|
|
return np.array([])
|
|
val_sq = np.squeeze(val)
|
|
if val_sq.ndim == 0:
|
|
if val_sq.dtype.kind in ('U', 'S'):
|
|
return str(val_sq.item())
|
|
return val_sq.item()
|
|
return val_sq
|
|
return val
|
|
|
|
|
|
def _mat_struct_to_dict(elem):
|
|
"""将 MATLAB struct 元素递归转换为 Python dict"""
|
|
if isinstance(elem, np.ndarray):
|
|
if elem.size == 0:
|
|
return {}
|
|
elem = elem.flat[0] if elem.size > 0 else elem
|
|
result = {}
|
|
fieldnames = []
|
|
if hasattr(elem, '_fieldnames'):
|
|
fieldnames = elem._fieldnames
|
|
elif isinstance(elem, np.void) and elem.dtype.names:
|
|
fieldnames = elem.dtype.names
|
|
|
|
for fn in fieldnames:
|
|
if hasattr(elem, fn):
|
|
raw_val = getattr(elem, fn)
|
|
else:
|
|
raw_val = elem[fn]
|
|
is_sub = False
|
|
if isinstance(raw_val, np.ndarray):
|
|
test = raw_val.flat[0] if raw_val.size > 0 else raw_val
|
|
if hasattr(test, '_fieldnames') or (isinstance(test, np.void) and test.dtype.names):
|
|
is_sub = True
|
|
if is_sub and isinstance(raw_val, np.ndarray):
|
|
items = []
|
|
for i in range(raw_val.size):
|
|
items.append(_mat_struct_to_dict(raw_val.flat[i]))
|
|
result[fn] = items if len(items) > 1 else items[0]
|
|
else:
|
|
result[fn] = _mat_value_convert(raw_val)
|
|
return result
|
|
|
|
def cpyAlgorithm(in_struct_path):
|
|
try:
|
|
if in_struct_path.endswith('.mat'):
|
|
in_struct = scipy.io.loadmat(in_struct_path)
|
|
if 'InStruct' in in_struct:
|
|
in_struct = _mat_struct_to_dict(in_struct['InStruct'])
|
|
in_struct['ConfigFile'] = r'D:\Qt\CpyAlgorithmServerQt\cpyAlgorithmMatlab2Python\ConfigFiles\confx2.prn'
|
|
else:
|
|
in_struct = np.load(in_struct_path)
|
|
except FileNotFoundError:
|
|
print(f"File not found: {in_struct_path}")
|
|
return None
|
|
except Exception as e:
|
|
print(f"Error loading file: {in_struct_path}")
|
|
print(e)
|
|
return None
|
|
|
|
time_start = time.time()
|
|
outStruct, mem = matlabgateway(in_struct)
|
|
if outStruct is None:
|
|
return None
|
|
time_end = time.time()
|
|
print(f"Gateway time: {time_end - time_start:.4f} seconds")
|
|
|
|
|
|
out_struct_path = in_struct_path.replace('_in', '_new_out')
|
|
if in_struct_path.endswith('.mat'):
|
|
scipy.io.savemat(out_struct_path, {'OutStruct': outStruct, 'mem': mem})
|
|
else:
|
|
np.savez(out_struct_path, OutStruct=outStruct, mem=mem)
|
|
|
|
return out_struct_path
|