repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/EXOPTA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class EXOPTAType(TREElement): def __init__(self, value): super(EXOPTAType, self).__init__() self.add_field('ANGLETONORTH', 's', 3, value) self.add_field('MEANGSD', 's', 5, value) self.add_field('RESERV01', 's', 1, value) self.add_field('DYNAMICRANGE', 's', 5, value) self.add_field('RESERV02', 's', 7, value) self.add_field('OBLANG', 's', 5, value) self.add_field('ROLLANG', 's', 6, value) self.add_field('PRIMEID', 's', 12, value) self.add_field('PRIMEBE', 's', 15, value) self.add_field('RESERV03', 's', 5, value) self.add_field('NSEC', 's', 3, value) self.add_field('RESERV04', 's', 2, value) self.add_field('RESERV05', 's', 7, value) self.add_field('NSEG', 's', 3, value) self.add_field('MAXLPSEG', 's', 6, value) self.add_field('RESERV06', 's', 12, value) self.add_field('SUNEL', 's', 5, value) self.add_field('SUNAZ', 's', 5, value) class EXOPTA(TREExtension): _tag_value = 'EXOPTA' _data_type = EXOPTAType
1,204
34.441176
53
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/CMETAA.py
import numpy from sarpy.geometry.geocoords import geodetic_to_ecf from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class CMETAAType(TREElement): def __init__(self, value): super(CMETAAType, self).__init__() self.add_field('RELATED_TRES', 's', 2, value) self.add_field('ADDITIONAL_TRES', 's', 120, value) self.add_field('RD_PRC_NO', 's', 12, value) self.add_field('IF_PROCESS', 's', 4, value) self.add_field('RD_CEN_FREQ', 's', 4, value) self.add_field('RD_MODE', 's', 5, value) self.add_field('RD_PATCH_NO', 's', 4, value) self.add_field('CMPLX_DOMAIN', 's', 5, value) self.add_field('CMPLX_MAG_REMAP_TYPE', 's', 4, value) self.add_field('CMPLX_LIN_SCALE', 's', 7, value) self.add_field('CMPLX_AVG_POWER', 's', 7, value) self.add_field('CMPLX_LINLOG_TP', 's', 5, value) self.add_field('CMPLX_PHASE_QUANT_FLAG', 's', 3, value) self.add_field('CMPLX_PHASE_QUANT_BIT_DEPTH', 's', 2, value) self.add_field('CMPLX_SIZE_1', 's', 2, value) self.add_field('CMPLX_IC_1', 's', 2, value) self.add_field('CMPLX_SIZE_2', 's', 2, value) self.add_field('CMPLX_IC_2', 's', 2, value) self.add_field('CMPLX_IC_BPP', 's', 5, value) self.add_field('CMPLX_WEIGHT', 's', 3, value) self.add_field('CMPLX_AZ_SLL', 's', 2, value) self.add_field('CMPLX_RNG_SLL', 's', 2, value) self.add_field('CMPLX_AZ_TAY_NBAR', 's', 2, value) self.add_field('CMPLX_RNG_TAY_NBAR', 's', 2, value) self.add_field('CMPLX_WEIGHT_NORM', 's', 3, value) self.add_field('CMPLX_SIGNAL_PLANE', 's', 1, value) self.add_field('IF_DC_SF_ROW', 's', 6, value) self.add_field('IF_DC_SF_COL', 's', 6, value) for part in range(1, 5): for comp in ['ROW', 'COL']: self.add_field('IF_PATCH_{}{}'.format(comp, part), 's', 6, value) self.add_field('IF_DC_IS_ROW', 's', 8, value) self.add_field('IF_DC_IS_COL', 's', 8, value) self.add_field('IF_IMG_ROW_DC', 's', 8, value) self.add_field('IF_IMG_COL_DC', 's', 8, value) for part in range(1, 5): for comp in ['ROW', 'COL']: self.add_field('IF_TILE_{}{}'.format(comp, part), 's', 6, value) self.add_field('IF_RD', 's', 1, value) self.add_field('IF_RGWLK', 's', 1, value) self.add_field('IF_KEYSTN', 's', 1, value) self.add_field('IF_LINSFT', 's', 1, value) self.add_field('IF_SUBPATCH', 's', 1, value) self.add_field('IF_GEODIST', 's', 1, value) self.add_field('IF_RGFO', 's', 1, value) self.add_field('IF_BEAM_COMP', 's', 1, value) self.add_field('IF_RGRES', 's', 8, value) self.add_field('IF_AZRES', 's', 8, value) self.add_field('IF_RSS', 's', 8, value) self.add_field('IF_AZSS', 's', 8, value) self.add_field('IF_RSR', 's', 8, value) self.add_field('IF_AZSR', 's', 8, value) self.add_field('IF_RFFT_SAMP', 's', 7, value) self.add_field('IF_AZFFT_SAMP', 's', 7, value) self.add_field('IF_RFFT_TOT', 's', 7, value) self.add_field('IF_AZFFT_TOT', 's', 7, value) self.add_field('IF_SUBP_ROW', 's', 6, value) self.add_field('IF_SUBP_COL', 's', 6, value) self.add_field('IF_SUB_RG', 's', 4, value) self.add_field('IF_SUB_AZ', 's', 4, value) self.add_field('IF_RFFTS', 's', 1, value) self.add_field('IF_AFFTS', 's', 1, value) self.add_field('IF_RANGE_DATA', 's', 7, value) self.add_field('IF_INCPH', 's', 1, value) for part in range(1, 4): for comp in ['NAME', 'AMOUNT']: self.add_field('IF_SR_{}{}'.format(comp, part), 's', 8, value) for part in range(1, 4): self.add_field('AF_TYPE{}'.format(part), 's', 5, value) self.add_field('POL_TR', 's', 1, value) self.add_field('POL_RE', 's', 1, value) self.add_field('POL_REFERENCE', 's', 40, value) self.add_field('POL', 's', 1, value) self.add_field('POL_REG', 's', 1, value) self.add_field('POL_ISO_1', 's', 5, value) self.add_field('POL_BAL', 's', 1, value) self.add_field('POL_BAL_MAG', 's', 8, value) self.add_field('POL_BAL_PHS', 's', 8, value) self.add_field('POL_HCOMP', 's', 1, value) self.add_field('POL_HCOMP_BASIS', 's', 10, value) for part in range(1, 4): self.add_field('POL_HCOMP_COEF{}'.format(part), 's', 9, value) self.add_field('POL_AFCOMP', 's', 1, value) self.add_field('POL_SPARE_A', 's', 15, value) self.add_field('POL_SPARE_N', 's', 9, value) self.add_field('T_UTC_YYYYMMMDD', 's', 9, value) self.add_field('T_HHMMSSUTC', 's', 6, value) self.add_field('T_HHMMSSLOCAL', 's', 6, value) self.add_field('CG_SRAC', 's', 11, value) self.add_field('CG_SLANT_CONFIDENCE', 's', 7, value) self.add_field('CG_CROSS', 's', 11, value) self.add_field('CG_CROSS_CONFIDENCE', 's', 7, value) self.add_field('CG_CAAC', 's', 9, value) self.add_field('CG_CONE_CONFIDENCE', 's', 6, value) self.add_field('CG_GPSAC', 's', 8, value) self.add_field('CG_GPSAC_CONFIDENCE', 's', 6, value) self.add_field('CG_SQUINT', 's', 8, value) self.add_field('CG_GAAC', 's', 7, value) self.add_field('CG_GAAC_CONFIDENCE', 's', 6, value) self.add_field('CG_INCIDENT', 's', 7, value) self.add_field('CG_SLOPE', 's', 7, value) self.add_field('CG_TILT', 's', 8, value) self.add_field('CG_LD', 's', 1, value) self.add_field('CG_NORTH', 's', 8, value) self.add_field('CG_NORTH_CONFIDENCE', 's', 6, value) self.add_field('CG_EAST', 's', 8, value) self.add_field('CG_RLOS', 's', 8, value) self.add_field('CG_LOS_CONFIDENCE', 's', 6, value) self.add_field('CG_LAYOVER', 's', 8, value) self.add_field('CG_SHADOW', 's', 8, value) self.add_field('CG_OPM', 's', 7, value) self.add_field('CG_MODEL', 's', 5, value) for comp in ['X', 'Y', 'Z']: self.add_field('CG_AMPT_{}'.format(comp), 's', 13, value) self.add_field('CG_AP_CONF_XY', 's', 6, value) self.add_field('CG_AP_CONF_Z', 's', 6, value) for comp in ['X', 'Y', 'Z']: self.add_field('CG_APCEN_{}'.format(comp), 's', 13, value) self.add_field('CG_APER_CONF_XY', 's', 6, value) self.add_field('CG_APER_CONF_Z', 's', 6, value) for comp in ['X', 'Y', 'Z']: self.add_field('CG_FPNUV_{}'.format(comp), 's', 9, value) for comp in ['X', 'Y', 'Z']: self.add_field('CG_IDPNUV{}'.format(comp), 's', 9, value) for comp in ['X', 'Y', 'Z']: self.add_field('CG_SCECN_{}'.format(comp), 's', 13, value) self.add_field('CG_SC_CONF_XY', 's', 6, value) self.add_field('CG_SC_CONF_Z', 's', 6, value) self.add_field('CG_SWWD', 's', 8, value) for comp in ['X', 'Y', 'Z']: self.add_field('CG_SNVEL_{}'.format(comp), 's', 10, value) for comp in ['X', 'Y', 'Z']: self.add_field('CG_SNACC_{}'.format(comp), 's', 10, value) for comp in ['ROLL', 'PITCH', 'YAW']: self.add_field('CG_SNATT_{}'.format(comp), 's', 8, value) for comp in ['X', 'Y', 'Z']: self.add_field('CG_GTP_{}'.format(comp), 's', 9, value) self.add_field('CG_MAP_TYPE', 's', 4, value) if self.CG_MAP_TYPE.strip() == 'GEOD': self.add_field('CG_PATCH_LATCEN', 's', 11, value) self.add_field('CG_PATCH_LNGCEN', 's', 12, value) self.add_field('CG_PATCH_LTCORUL', 's', 11, value) self.add_field('CG_PATCH_LGCORUL', 's', 12, value) self.add_field('CG_PATCH_LTCORUR', 's', 11, value) self.add_field('CG_PATCH_LGCORUR', 's', 12, value) self.add_field('CG_PATCH_LTCORLR', 's', 11, value) self.add_field('CG_PATCH_LGCORLR', 's', 12, value) self.add_field('CG_PATCH_LTCORLL', 's', 11, value) self.add_field('CG_PATH_LNGCOLL', 's', 12, value) self.add_field('CG_PATCH_LAT_CONFIDENCE', 's', 9, value) self.add_field('CG_PATCH_LONG_CONFIDENCE', 's', 9, value) elif self.CG_MAP_TYPE.strip() == 'MGRS': self.add_field('CG_MGRS_CENT', 's', 23, value) self.add_field('CG_MGRSCORUL', 's', 23, value) self.add_field('CG_MGRSCORUR', 's', 23, value) self.add_field('CG_MGRSCORLR', 's', 23, value) self.add_field('CG_MGRCORLL', 's', 23, value) self.add_field('CG_MGRS_CONFIDENCE', 's', 7, value) self.add_field('CG_MGRS_PAD', 's', 11, value) elif self.CG_MAP_TYPE.strip() == 'NA': self.add_field('CG_MAP_TYPE_BLANK', 's', 133, value) self.add_field('CG_SPARE_A', 's', 144, value) self.add_field('CA_CALPA', 's', 7, value) self.add_field('WF_SRTFR', 's', 14, value) self.add_field('WF_ENDFR', 's', 14, value) self.add_field('WF_CHRPRT', 's', 10, value) self.add_field('WF_WIDTH', 's', 9, value) self.add_field('WF_CENFRQ', 's', 13, value) self.add_field('WF_BW', 's', 13, value) self.add_field('WF_PRF', 's', 7, value) self.add_field('WF_PRI', 's', 9, value) self.add_field('WF_CDP', 's', 7, value) self.add_field('WF_NUMBER_OF_PULSES', 's', 9, value) self.add_field('VPH_COND', 's', 1, value) class CMETAA(TREExtension): _tag_value = 'CMETAA' _data_type = CMETAAType def get_scp(self): """ Gets the SCP location in ECF coordinates. Returns ------- numpy.ndarray """ cg_model = self.DATA.CG_MODEL.strip() scp_array = numpy.array( [float(self.DATA.CG_SCECN_X), float(self.DATA.CG_SCECN_Y), float(self.DATA.CG_SCECN_Z)], dtype='float64') if cg_model == 'ECEF': return scp_array elif cg_model == 'WGS84': return geodetic_to_ecf(scp_array) else: raise ValueError('Got unhandled CG_MODEL {}'.format(cg_model)) def get_arp(self): """ Gets the Aperture Position, at SCP Time, in ECF coordinates. Returns ------- numpy.ndarray """ cg_model = self.DATA.CG_MODEL.strip() arp_array = numpy.array( [float(self.DATA.CG_APCEN_X), float(self.DATA.CG_APCEN_Y), float(self.DATA.CG_APCEN_Z)], dtype='float64') if cg_model == 'ECEF': return arp_array elif cg_model == 'WGS84': return geodetic_to_ecf(arp_array) else: raise ValueError('Got unhandled CG_MODEL {}'.format(cg_model)) def get_image_corners(self): """ Gets the image corners in Lat/Lon, if feasible. Returns ------- None|numpy.ndarray """ if self.DATA.CG_MAP_TYPE.strip() != 'GEOD': return None return numpy.array([ [float(self.DATA.CG_PATCH_LTCORUL), float(self.DATA.CG_PATCH_LGCORUL)], [float(self.DATA.CG_PATCH_LTCORUR), float(self.DATA.CG_PATCH_LGCORUR)], [float(self.DATA.CG_PATCH_LTCORLR), float(self.DATA.CG_PATCH_LGCORLR)], [float(self.DATA.CG_PATCH_LTCORLL), float(self.DATA.CG_PATCH_LNGCOLL)]], dtype='float64')
11,683
42.434944
105
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/ACCHZB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PT(TREElement): def __init__(self, value): super(PT, self).__init__() self.add_field('LON', 's', 15, value) self.add_field('LAT', 's', 15, value) class ACHZ(TREElement): def __init__(self, value): super(ACHZ, self).__init__() self.add_field('UNIAAH', 's', 3, value) if self.UNIAAH != '': self.add_field('AAH', 's', 5, value) self.add_field('UNIAPH', 's', 3, value) if self.UNIAPH != '': self.add_field('APH', 's', 5, value) self.add_field('NUMPTS', 'd', 3, value) self.add_loop('PTs', self.NUMPTS, PT, value) class ACCHZBType(TREElement): def __init__(self, value): super(ACCHZBType, self).__init__() self.add_field('NUMACHZ', 'd', 2, value) self.add_loop('ACHZs', self.NUMACHZ, ACHZ, value) class ACCHZB(TREExtension): _tag_value = 'ACCHZB' _data_type = ACCHZBType
1,051
26.684211
57
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/MSTGTA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class MSTGTAType(TREElement): def __init__(self, value): super(MSTGTAType, self).__init__() self.add_field('TGTNUM', 's', 5, value) self.add_field('TGTID', 's', 12, value) self.add_field('TGTBE', 's', 15, value) self.add_field('TGTPRI', 's', 3, value) self.add_field('TGTREQ', 's', 12, value) self.add_field('TGTLTIOV', 's', 12, value) self.add_field('TGTTYPE', 's', 1, value) self.add_field('TGTCOLL', 's', 1, value) self.add_field('TGTCAT', 's', 5, value) self.add_field('TGTUTC', 's', 7, value) self.add_field('TGTELEV', 's', 6, value) self.add_field('TGTELEVUNIT', 's', 1, value) self.add_field('TGTLOC', 's', 21, value) class MSTGTA(TREExtension): _tag_value = 'MSTGTA' _data_type = MSTGTAType
950
31.793103
52
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/PATCHB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PATCHBType(TREElement): def __init__(self, value): super(PATCHBType, self).__init__() self.add_field('PAT_NO', 's', 4, value) self.add_field('LAST_PAT_FLAG', 's', 1, value) self.add_field('LNSTRT', 's', 7, value) self.add_field('LNSTOP', 's', 7, value) self.add_field('AZL', 's', 5, value) self.add_field('NVL', 's', 5, value) self.add_field('FVL', 's', 3, value) self.add_field('NPIXEL', 's', 5, value) self.add_field('FVPIX', 's', 5, value) self.add_field('FRAME', 's', 3, value) self.add_field('UTC', 's', 8, value) self.add_field('SHEAD', 's', 7, value) self.add_field('GRAVITY', 's', 7, value) self.add_field('INS_V_NC', 's', 5, value) self.add_field('INS_V_EC', 's', 5, value) self.add_field('INS_V_DC', 's', 5, value) self.add_field('OFFLAT', 's', 8, value) self.add_field('OFFLONG', 's', 8, value) self.add_field('TRACK', 's', 3, value) self.add_field('GSWEEP', 's', 6, value) self.add_field('SHEAR', 's', 8, value) self.add_field('BATCH_NO', 's', 6, value) class PATCHB(TREExtension): _tag_value = 'PATCHB' _data_type = PATCHBType
1,369
35.052632
54
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/CCINFA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class CODE(TREElement): def __init__(self, value): super(CODE, self).__init__() self.add_field('CODE_LEN', 'd', 1, value) self.add_field('CODE', 's', self.CODE_LEN, value) self.add_field('EQTYPE', 's', 1, value) self.add_field('ESURN_LEN', 'd', 2, value) self.add_field('ESURN', 's', self.ESURN_LEN, value) self.add_field('DETAIL_LEN', 'd', 5, value) if self.DETAIL_LEN > 0: self.add_field('DETAIL_CMPR', 's', 1, value) self.add_field('DETAIL', 's', self.DETAIL_LEN, value) class CCINFAType(TREElement): def __init__(self, value): super(CCINFAType, self).__init__() self.add_field('NUMCODE', 'd', 3, value) self.add_loop('CODEs', self.NUMCODE, CODE, value) class CCINFA(TREExtension): _tag_value = 'CCINFA' _data_type = CCINFAType
988
29.90625
65
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/ASTORA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class ASTORAType(TREElement): def __init__(self, value): super(ASTORAType, self).__init__() self.add_field('IMG_TOTAL_ROWS', 's', 6, value) self.add_field('IMG_TOTAL_COLS', 's', 6, value) self.add_field('IMG_INDEX_ROW', 's', 6, value) self.add_field('IMG_INDEX_COL', 's', 6, value) self.add_field('GEOID_OFFSET', 's', 7, value) self.add_field('ALPHA_0', 's', 16, value) self.add_field('K_L', 's', 2, value) self.add_field('C_M', 's', 15, value) self.add_field('AC_ROLL', 's', 16, value) self.add_field('AC_PITCH', 's', 16, value) self.add_field('AC_YAW', 's', 16, value) self.add_field('AC_TRACK_HEADING', 's', 16, value) self.add_field('AP_ORIGIN_X', 's', 13, value) self.add_field('AP_ORIGIN_Y', 's', 13, value) self.add_field('AP_ORIGIN_Z', 's', 13, value) self.add_field('AP_DIR_X', 's', 16, value) self.add_field('AP_DIR_Y', 's', 16, value) self.add_field('AP_DIR_Z', 's', 16, value) self.add_field('X_AP_START', 's', 12, value) self.add_field('X_AP_END', 's', 12, value) self.add_field('SS_ROW_SHIFT', 's', 4, value) self.add_field('SS_COL_SHIFT', 's', 4, value) self.add_field('U_HAT_X', 's', 16, value) self.add_field('U_HAT_Y', 's', 16, value) self.add_field('U_HAT_Z', 's', 16, value) self.add_field('V_HAT_X', 's', 16, value) self.add_field('V_HAT_Y', 's', 16, value) self.add_field('V_HAT_Z', 's', 16, value) self.add_field('N_HAT_X', 's', 16, value) self.add_field('N_HAT_Y', 's', 16, value) self.add_field('N_HAT_Z', 's', 16, value) self.add_field('ETA_0', 's', 16, value) self.add_field('SIGMA_SM', 's', 13, value) self.add_field('SIGMA_SN', 's', 13, value) self.add_field('S_OFF', 's', 10, value) self.add_field('RN_OFFSET', 's', 12, value) self.add_field('R_SCL', 's', 16, value) self.add_field('R_NAV', 's', 16, value) self.add_field('R_SC_EXACT', 's', 16, value) self.add_field('C_SC_X', 's', 16, value) self.add_field('C_SC_Y', 's', 16, value) self.add_field('C_SC_Z', 's', 16, value) self.add_field('K_HAT_X', 's', 16, value) self.add_field('K_HAT_Y', 's', 16, value) self.add_field('K_HAT_Z', 's', 16, value) self.add_field('L_HAT_X', 's', 16, value) self.add_field('L_HAT_Y', 's', 16, value) self.add_field('L_HAT_Z', 's', 16, value) self.add_field('P_Z', 's', 16, value) self.add_field('THETA_C', 's', 16, value) self.add_field('ALPHA_SL', 's', 16, value) self.add_field('SIGMA_TC', 's', 16, value) class ASTORA(TREExtension): _tag_value = 'ASTORA' _data_type = ASTORAType
2,960
42.544118
58
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/RSMPCA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class RNT(TREElement): def __init__(self, value): super(RNT, self).__init__() self.add_field('RNPCF', 's', 21, value) class RDT(TREElement): def __init__(self, value): super(RDT, self).__init__() self.add_field('RDPCF', 's', 21, value) class CNT(TREElement): def __init__(self, value): super(CNT, self).__init__() self.add_field('CNPCF', 's', 21, value) class CDT(TREElement): def __init__(self, value): super(CDT, self).__init__() self.add_field('CDPCF', 's', 21, value) class RSMPCAType(TREElement): def __init__(self, value): super(RSMPCAType, self).__init__() self.add_field('IID', 's', 80, value) self.add_field('EDITION', 's', 40, value) self.add_field('RSN', 's', 3, value) self.add_field('CSN', 's', 3, value) self.add_field('RFEP', 's', 21, value) self.add_field('CFEP', 's', 21, value) self.add_field('RNRMO', 's', 21, value) self.add_field('CNRMO', 's', 21, value) self.add_field('XNRMO', 's', 21, value) self.add_field('YNRMO', 's', 21, value) self.add_field('ZNRMO', 's', 21, value) self.add_field('RNRMSF', 's', 21, value) self.add_field('CNRMSF', 's', 21, value) self.add_field('XNRMSF', 's', 21, value) self.add_field('YNRMSF', 's', 21, value) self.add_field('ZNRMSF', 's', 21, value) self.add_field('RNPWRX', 's', 1, value) self.add_field('RNPWRY', 's', 1, value) self.add_field('RNPWRZ', 's', 1, value) self.add_field('RNTRMS', 'd', 3, value) self.add_loop('RNTs', self.RNTRMS, RNT, value) self.add_field('RDPWRX', 's', 1, value) self.add_field('RDPWRY', 's', 1, value) self.add_field('RDPWRZ', 's', 1, value) self.add_field('RDTRMS', 'd', 3, value) self.add_loop('RDTs', self.RDTRMS, RDT, value) self.add_field('CNPWRX', 's', 1, value) self.add_field('CNPWRY', 's', 1, value) self.add_field('CNPWRZ', 's', 1, value) self.add_field('CNTRMS', 'd', 3, value) self.add_loop('CNTs', self.CNTRMS, CNT, value) self.add_field('CDPWRX', 's', 1, value) self.add_field('CDPWRY', 's', 1, value) self.add_field('CDPWRZ', 's', 1, value) self.add_field('CDTRMS', 'd', 3, value) self.add_loop('CDTs', self.CDTRMS, CDT, value) class RSMPCA(TREExtension): _tag_value = 'RSMPCA' _data_type = RSMPCAType
2,626
33.565789
54
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/AIPBCA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class AIPBCAType(TREElement): def __init__(self, value): super(AIPBCAType, self).__init__() self.add_field('PATCH_WIDTH', 's', 5, value) self.add_field('U_HAT_X', 's', 16, value) self.add_field('U_HAT_Y', 's', 16, value) self.add_field('U_HAT_Z', 's', 16, value) self.add_field('V_HAT_X', 's', 16, value) self.add_field('V_HAT_Y', 's', 16, value) self.add_field('V_HAT_Z', 's', 16, value) self.add_field('N_HAT_X', 's', 16, value) self.add_field('N_HAT_Y', 's', 16, value) self.add_field('N_HAT_Z', 's', 16, value) self.add_field('DEP_ANGLE', 's', 7, value) self.add_field('CT_TRACK_RANGE', 's', 10, value) self.add_field('ETA_0', 's', 16, value) self.add_field('ETA_1', 's', 16, value) self.add_field('X_IMG_U', 's', 9, value) self.add_field('X_IMG_V', 's', 9, value) self.add_field('X_IMG_N', 's', 9, value) self.add_field('Y_IMG_U', 's', 9, value) self.add_field('Y_IMG_V', 's', 9, value) self.add_field('Y_IMG_N', 's', 9, value) self.add_field('Z_IMG_U', 's', 9, value) self.add_field('Z_IMG_V', 's', 9, value) self.add_field('Z_IMG_N', 's', 9, value) self.add_field('CT_HAT_X', 's', 9, value) self.add_field('CT_HAT_Y', 's', 9, value) self.add_field('CT_HAT_Z', 's', 9, value) self.add_field('SCL_PT_U', 's', 13, value) self.add_field('SCL_PT_V', 's', 13, value) self.add_field('SCL_PT_N', 's', 13, value) self.add_field('SIGMA_SM', 's', 13, value) self.add_field('SIGMA_SN', 's', 13, value) self.add_field('S_OFF', 's', 10, value) self.add_field('RN_OFFSET', 's', 12, value) self.add_field('CRP_RANGE', 's', 11, value) self.add_field('REF_DEP_ANG', 's', 7, value) self.add_field('REF_ASP_ANG', 's', 9, value) self.add_field('N_SKIP_AZ', 's', 1, value) self.add_field('N_SKIP_RANGE', 's', 1, value) class AIPBCA(TREExtension): _tag_value = 'AIPBCA' _data_type = AIPBCAType
2,229
40.296296
56
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/RPFDES.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class SECREC(TREElement): def __init__(self, value): super(SECREC, self).__init__() self.add_field('LOCID', 'b', 1, value) self.add_field('SECLEN', 'b', 1, value) self.add_field('PHYSIDX', 'b', 1, value) class RPFDESType(TREElement): def __init__(self, value): super(RPFDESType, self).__init__() self.add_field('LOCLEN', 'b', 1, value) # TODO: It's unclear whether this should be interpreted as an 8-bit int, or string? if int(self.LOCLEN) > 0: self.add_field('CLTOFF', 'b', 1, value) self.add_field('SECRECS', 'b', 1, value) self.add_field('RECLEN', 'b', 1, value) self.add_field('AGGLEN', 'b', 1, value) self.add_loop('SECRECList', int(self.SECRECS), SECREC, value) self.add_field('UNKNOWN', 'b', len(value) - self._bytes_length, value) class RPFDES(TREExtension): _tag_value = 'RPFDES' _data_type = RPFDESType
1,090
32.060606
91
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/CLCTNB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class SITE(TREElement): def __init__(self, value): super(SITE, self).__init__() self.add_field('SCLCTN_NAME', 's', 20, value) self.add_field('SDESCRIPTION', 's', 255, value) self.add_field('SITE_NUM', 's', 3, value) self.add_field('SCN_NUM', 's', 3, value) self.add_field('SCLCTN_STDATE', 's', 8, value) self.add_field('SCLCTN_SPDATE', 's', 8, value) self.add_field('SCN_CNTR', 's', 11, value) self.add_field('ALTITUDE', 's', 5, value) self.add_field('SCN_CONTENT', 's', 50, value) self.add_field('BGRND_TYPE', 's', 50, value) self.add_field('SITE_COV', 's', 1, value) class CLCTNBType(TREElement): def __init__(self, value): super(CLCTNBType, self).__init__() self.add_field('VERNUM', 's', 4, value) self.add_field('CLCTN_NAME', 's', 25, value) self.add_field('CLCTN_DESCRIPT', 's', 255, value) self.add_field('CLCTN_STDATE', 's', 8, value) self.add_field('CLCTN_SPDATE', 's', 8, value) self.add_field('CLCTN_LOC', 's', 11, value) self.add_field('SITE', 's', 15, value) self.add_field('COUNTRY', 's', 2, value) self.add_field('SPONSOR', 's', 20, value) self.add_field('PERSONNEL', 's', 100, value) self.add_field('NUM_SITES', 'd', 1, value) self.add_loop('SITEs', self.NUM_SITES, SITE, value) self.add_field('SCLCTN_Z_OFF', 's', 3, value) self.add_field('SECURITY', 's', 7, value) self.add_field('SCG', 's', 15, value) self.add_field('FLIGHT_NUM', 's', 2, value) self.add_field('PASS_NUM', 's', 2, value) self.add_field('WX_STATION', 's', 20, value) self.add_field('WX_OVERVIEW', 's', 15, value) self.add_field('WX_FILE', 's', 30, value) class CLCTNB(TREExtension): _tag_value = 'CLCTNB' _data_type = CLCTNBType
2,022
37.903846
59
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/PIAIMC.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PIAIMCType(TREElement): def __init__(self, value): super(PIAIMCType, self).__init__() self.add_field('CLOUDCVR', 's', 3, value) self.add_field('SRP', 's', 1, value) self.add_field('SENSMODE', 's', 12, value) self.add_field('SENSNAME', 's', 18, value) self.add_field('SOURCE', 's', 255, value) self.add_field('COMGEN', 's', 2, value) self.add_field('SUBQUAL', 's', 1, value) self.add_field('PIAMSNNUM', 's', 7, value) self.add_field('CAMSPECS', 's', 32, value) self.add_field('PROJID', 's', 2, value) self.add_field('GENERATION', 's', 1, value) self.add_field('ESD', 's', 1, value) self.add_field('OTHERCOND', 's', 2, value) self.add_field('MEANGSD', 's', 7, value) self.add_field('IDATUM', 's', 3, value) self.add_field('IELLIP', 's', 3, value) self.add_field('PREPROC', 's', 2, value) self.add_field('IPROJ', 's', 2, value) self.add_field('SATTRACK', 's', 8, value) class PIAIMC(TREExtension): _tag_value = 'PIAIMC' _data_type = PIAIMCType
1,246
34.628571
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/IOMAPA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class IOMAPA_6Type(TREElement): def __init__(self, value): super(IOMAPA_6Type, self).__init__() self.add_field('BAND_NUMBER', 's', 3, value) self.add_field('MAP_SELECT', 's', 1, value) self.add_field('S2', 's', 2, value) class IOMAPA_6(TREExtension): _tag_value = 'IOMAPA' _data_type = IOMAPA_6Type class IOMAPA_16Type(TREElement): def __init__(self, value): super(IOMAPA_16Type, self).__init__() self.add_field('BAND_NUMBER', 's', 3, value) self.add_field('MAP_SELECT', 's', 1, value) self.add_field('TABLE_ID', 's', 2, value) self.add_field('S1', 's', 2, value) self.add_field('S2', 's', 2, value) self.add_field('R_WHOLE', 's', 3, value) self.add_field('R_FRACTION', 's', 3, value) class IOMAPA_16(TREExtension): _tag_value = 'IOMAPA' _data_type = IOMAPA_16Type class SEGMENT(TREElement): def __init__(self, value): super(SEGMENT, self).__init__() self.add_field('OUT_B0', 'b', 4, value) self.add_field('OUT_B1', 'b', 4, value) self.add_field('OUT_B2', 'b', 4, value) self.add_field('OUT_B3', 'b', 4, value) self.add_field('OUT_B4', 'b', 4, value) self.add_field('OUT_B5', 'b', 4, value) class IOMAPA_91Type(TREElement): def __init__(self, value): super(IOMAPA_91Type, self).__init__() self.add_field('BAND_NUMBER', 's', 3, value) self.add_field('MAP_SELECT', 's', 1, value) self.add_field('TABLE_ID', 's', 1, value) self.add_field('S1', 's', 2, value) self.add_field('S2', 's', 2, value) self.add_field('NO_OF_SEGMENTS', 'd', 1, value) self.add_field('XOB_1', 's', 4, value) self.add_field('XOB_2', 's', 4, value) self.add_loop('SEGMENTs', self.NO_OF_SEGMENTS, SEGMENT, value) class IOMAPA_91(TREExtension): _tag_value = 'IOMAPA' _data_type = IOMAPA_91Type class MAP(TREElement): def __init__(self, value): super(MAP, self).__init__() self.add_field('OUTPUT_MAP_VALUE', 's', 2, value) class IOMAPA_8202Type(TREElement): def __init__(self, value): super(IOMAPA_8202Type, self).__init__() self.add_field('BAND_NUMBER', 's', 3, value) self.add_field('MAP_SELECT', 's', 1, value) self.add_field('TABLE_ID', 's', 2, value) self.add_field('S1', 's', 2, value) self.add_field('S2', 's', 2, value) self.add_loop('MAPs', 4096, MAP, value) class IOMAPA_8202(TREExtension): _tag_value = 'IOMAPA' _data_type = IOMAPA_8202Type class IOMAPA(TREExtension): _tag_value = 'IOMAPA' def __init__(self): raise ValueError( 'Not to be implemented directly. ' 'Use of one IOMAPA_6, IOMAPA_16, IOMAPA_91, or IOMAPA_8202') @classmethod def from_bytes(cls, value, start): """ Parameters ---------- value : bytes start : int Returns ------- IOMAPA_6|IOMAPA_16|IOMAPA_91|IOMAPA_8202 """ tag_value = value[start:start+6].decode('utf-8').strip() if tag_value != cls._tag_value: raise ValueError('tag value must be {}. Got {}'.format(cls._tag_value, tag_value)) lng = int(value[start+6:start+11]) if lng == 6: return IOMAPA_6.from_bytes(value, start) elif lng == 16: return IOMAPA_16.from_bytes(value, start) elif lng == 91: return IOMAPA_91.from_bytes(value, start) elif lng == 8202: return IOMAPA_8202.from_bytes(value, start) else: raise ValueError('the data must be length 6, 16, 91, or 8202. Got {}'.format(lng))
3,858
29.385827
94
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/CSDIDA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class CSDIDAType(TREElement): def __init__(self, value): super(CSDIDAType, self).__init__() self.add_field('DAY', 's', 2, value) self.add_field('MONTH', 's', 3, value) self.add_field('YEAR', 's', 4, value) self.add_field('PLATFORM_CODE', 's', 2, value) self.add_field('VEHICLE_ID', 's', 2, value) self.add_field('PASS', 's', 2, value) self.add_field('OPERATION', 's', 3, value) self.add_field('SENSOR_ID', 's', 2, value) self.add_field('PRODUCT_ID', 's', 2, value) self.add_field('RESERVED_1', 's', 4, value) self.add_field('TIME', 's', 14, value) self.add_field('PROCESS_TIME', 's', 14, value) self.add_field('RESERVED_2', 's', 2, value) self.add_field('RESERVED_3', 's', 2, value) self.add_field('RESERVED_4', 's', 1, value) self.add_field('RESERVED_5', 's', 1, value) self.add_field('SOFTWARE_VERSION_NUMBER', 's', 10, value) class CSDIDA(TREExtension): _tag_value = 'CSDIDA' _data_type = CSDIDAType
1,186
34.969697
65
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/CLCTNA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class CLCTNAType(TREElement): def __init__(self, value): super(CLCTNAType, self).__init__() self.add_field('VERNUM', 's', 4, value) self.add_field('CLCTN_NAME', 's', 25, value) self.add_field('CLCTN_DESCRIPT', 's', 255, value) self.add_field('CLCTN_STDATE', 's', 8, value) self.add_field('CLCTN_SPDATE', 's', 8, value) self.add_field('CLCTN_LOC', 's', 11, value) self.add_field('COUNTRY', 's', 2, value) self.add_field('SPONSOR', 's', 20, value) self.add_field('PERSONNEL', 's', 100, value) self.add_field('SCLCTN_NAME', 's', 20, value) self.add_field('SDESCRIPTION', 's', 255, value) self.add_field('SCLCTN_Z_OFF', 's', 3, value) self.add_field('SCLCTN_STDATE', 's', 8, value) self.add_field('SCLCTN_SPDATE', 's', 8, value) self.add_field('SECURITY', 's', 7, value) self.add_field('SCG', 's', 15, value) self.add_field('SITE', 's', 15, value) self.add_field('SITE_NUM', 's', 3, value) self.add_field('SCN_NUM', 's', 3, value) self.add_field('FLIGHT_NUM', 's', 2, value) self.add_field('PASS_NUM', 's', 2, value) self.add_field('SCN_CNTR', 's', 11, value) self.add_field('ALTITUDE', 's', 5, value) self.add_field('SCN_CONTENT', 's', 50, value) self.add_field('BGRND_TYPE', 's', 50, value) self.add_field('WX_STATION', 's', 20, value) self.add_field('WX_OVERVIEW', 's', 15, value) self.add_field('WX_FILE', 's', 30, value) class CLCTNA(TREExtension): _tag_value = 'CLCTNA' _data_type = CLCTNAType
1,767
39.181818
57
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/USE00A.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class USE00AType(TREElement): def __init__(self, value): super(USE00AType, self).__init__() self.add_field('ANGLE_TO_NORTH', 's', 3, value) self.add_field('MEAN_GSD', 's', 5, value) self.add_field('RSRVD01', 's', 1, value) self.add_field('DYNAMIC_RANGE', 's', 5, value) self.add_field('RSRVD02', 's', 3, value) self.add_field('RSRVD03', 's', 1, value) self.add_field('RSRVD04', 's', 3, value) self.add_field('OBL_ANG', 's', 5, value) self.add_field('ROLL_ANG', 's', 6, value) self.add_field('RSRVD05', 's', 12, value) self.add_field('RSRVD06', 's', 15, value) self.add_field('RSRVD07', 's', 4, value) self.add_field('RSRVD08', 's', 1, value) self.add_field('RSRVD09', 's', 3, value) self.add_field('RSRVD10', 's', 1, value) self.add_field('RSRVD11', 's', 1, value) self.add_field('N_REF', 's', 2, value) self.add_field('REV_NUM', 's', 5, value) self.add_field('N_SEG', 's', 3, value) self.add_field('MAX_LP_SEG', 's', 6, value) self.add_field('RSRVD12', 's', 6, value) self.add_field('RSRVD13', 's', 6, value) self.add_field('SUN_EL', 's', 5, value) self.add_field('SUN_AZ', 's', 5, value) class USE00A(TREExtension): _tag_value = 'USE00A' _data_type = USE00AType
1,503
36.6
55
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/RSMIDA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class RSMIDAType(TREElement): def __init__(self, value): super(RSMIDAType, self).__init__() self.add_field('IID', 's', 80, value) self.add_field('EDITION', 's', 40, value) self.add_field('ISID', 's', 40, value) self.add_field('SID', 's', 40, value) self.add_field('STID', 's', 40, value) self.add_field('YEAR', 's', 4, value) self.add_field('MONTH', 's', 2, value) self.add_field('DAY', 's', 2, value) self.add_field('HOUR', 's', 2, value) self.add_field('MINUTE', 's', 2, value) self.add_field('SECOND', 's', 9, value) self.add_field('NRG', 's', 8, value) self.add_field('NCG', 's', 8, value) self.add_field('TRG', 's', 21, value) self.add_field('TCG', 's', 21, value) self.add_field('GRNDD', 's', 1, value) self.add_field('XUOR', 's', 21, value) self.add_field('YUOR', 's', 21, value) self.add_field('ZUOR', 's', 21, value) self.add_field('XUXR', 's', 21, value) self.add_field('XUYR', 's', 21, value) self.add_field('XUZR', 's', 21, value) self.add_field('YUXR', 's', 21, value) self.add_field('YUYR', 's', 21, value) self.add_field('YUZR', 's', 21, value) self.add_field('ZUXR', 's', 21, value) self.add_field('ZUYR', 's', 21, value) self.add_field('ZUZR', 's', 21, value) self.add_field('V1X', 's', 21, value) self.add_field('V1Y', 's', 21, value) self.add_field('V1Z', 's', 21, value) self.add_field('V2X', 's', 21, value) self.add_field('V2Y', 's', 21, value) self.add_field('V2Z', 's', 21, value) self.add_field('V3X', 's', 21, value) self.add_field('V3Y', 's', 21, value) self.add_field('V3Z', 's', 21, value) self.add_field('V4X', 's', 21, value) self.add_field('V4Y', 's', 21, value) self.add_field('V4Z', 's', 21, value) self.add_field('V5X', 's', 21, value) self.add_field('V5Y', 's', 21, value) self.add_field('V5Z', 's', 21, value) self.add_field('V6X', 's', 21, value) self.add_field('V6Y', 's', 21, value) self.add_field('V6Z', 's', 21, value) self.add_field('V7X', 's', 21, value) self.add_field('V7Y', 's', 21, value) self.add_field('V7Z', 's', 21, value) self.add_field('V8X', 's', 21, value) self.add_field('V8Y', 's', 21, value) self.add_field('V8Z', 's', 21, value) self.add_field('GRPX', 's', 21, value) self.add_field('GRPY', 's', 21, value) self.add_field('GRPZ', 's', 21, value) self.add_field('FULLR', 's', 8, value) self.add_field('FULLC', 's', 8, value) self.add_field('MINR', 's', 8, value) self.add_field('MAXR', 's', 8, value) self.add_field('MINC', 's', 8, value) self.add_field('MAXC', 's', 8, value) self.add_field('IE0', 's', 21, value) self.add_field('IER', 's', 21, value) self.add_field('IEC', 's', 21, value) self.add_field('IERR', 's', 21, value) self.add_field('IERC', 's', 21, value) self.add_field('IECC', 's', 21, value) self.add_field('IA0', 's', 21, value) self.add_field('IAR', 's', 21, value) self.add_field('IAC', 's', 21, value) self.add_field('IARR', 's', 21, value) self.add_field('IARC', 's', 21, value) self.add_field('IACC', 's', 21, value) self.add_field('SPX', 's', 21, value) self.add_field('SVX', 's', 21, value) self.add_field('SAX', 's', 21, value) self.add_field('SPY', 's', 21, value) self.add_field('SVY', 's', 21, value) self.add_field('SAY', 's', 21, value) self.add_field('SPZ', 's', 21, value) self.add_field('SVZ', 's', 21, value) self.add_field('SAZ', 's', 21, value) class RSMIDA(TREExtension): _tag_value = 'RSMIDA' _data_type = RSMIDAType
4,117
41.020408
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/ACCVTB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PT(TREElement): def __init__(self, value): super(PT, self).__init__() self.add_field('LON', 's', 15, value) self.add_field('LAT', 's', 15, value) class ACVT(TREElement): def __init__(self, value): super(ACVT, self).__init__() self.add_field('UNIAAV', 's', 3, value) if self.UNIAAV != '': self.add_field('AAV', 's', 5, value) self.add_field('UNIAPV', 's', 3, value) if self.UNIAPV != '': self.add_field('APV', 's', 5, value) self.add_field('NUMPTS', 'd', 3, value) self.add_loop('PTs', self.NUMPTS, PT, value) class ACCVTBType(TREElement): def __init__(self, value): super(ACCVTBType, self).__init__() self.add_field('NUMACVT', 'd', 2, value) self.add_loop('ACVTs', self.NUMACVT, ACVT, value) class ACCVTB(TREExtension): _tag_value = 'ACCVTB' _data_type = ACCVTBType
1,051
26.684211
57
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/J2KLRA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class LAYER(TREElement): def __init__(self, value): super(LAYER, self).__init__() self.add_field('LAYER_ID', 's', 3, value) self.add_field('BITRATE', 's', 9, value) class J2KLRAType(TREElement): def __init__(self, value): super(J2KLRAType, self).__init__() self.add_field('ORIG', 's', 1, value) self.add_field('NLEVELS_O', 's', 2, value) self.add_field('NBANDS_O', 's', 5, value) self.add_field('NLAYERS_O', 'd', 3, value) self.add_loop('LAYERs', self.NLAYERS_O, LAYER, value) if self.ORIG in ['1', '3', '9']: self.add_field('NLEVELS_I', 's', 2, value) self.add_field('NBANDS_I', 's', 5, value) self.add_field('NLAYERS_I', 's', 3, value) class J2KLRA(TREExtension): _tag_value = 'J2KLRA' _data_type = J2KLRAType
973
29.4375
61
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/MENSRB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class MENSRBType(TREElement): def __init__(self, value): super(MENSRBType, self).__init__() self.add_field('ACFT_LOC', 's', 25, value) self.add_field('ACFT_LOC_ACCY', 's', 6, value) self.add_field('ACFT_ALT', 's', 6, value) self.add_field('RP_LOC', 's', 25, value) self.add_field('RP_LOC_ACCY', 's', 6, value) self.add_field('RP_ELV', 's', 6, value) self.add_field('OF_PC_R', 's', 7, value) self.add_field('OF_PC_A', 's', 7, value) self.add_field('COSGRZ', 's', 7, value) self.add_field('RGCRP', 's', 7, value) self.add_field('RLMAP', 's', 1, value) self.add_field('RP_ROW', 's', 5, value) self.add_field('RP_COL', 's', 5, value) self.add_field('C_R_NC', 's', 10, value) self.add_field('C_R_EC', 's', 10, value) self.add_field('C_R_DC', 's', 10, value) self.add_field('C_AZ_NC', 's', 9, value) self.add_field('C_AZ_EC', 's', 9, value) self.add_field('C_AZ_DC', 's', 9, value) self.add_field('C_AL_NC', 's', 9, value) self.add_field('C_AL_EC', 's', 9, value) self.add_field('C_AL_DC', 's', 9, value) self.add_field('TOTAL_TILES_COLS', 's', 3, value) self.add_field('TOTAL_TILES_ROWS', 's', 5, value) class MENSRB(TREExtension): _tag_value = 'MENSRB' _data_type = MENSRBType
1,512
36.825
57
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/IMRFCA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class XINC(TREElement): def __init__(self, value): super(XINC, self).__init__() self.add_field('XINC', 's', 22, value) class XIDC(TREElement): def __init__(self, value): super(XIDC, self).__init__() self.add_field('XIDC', 's', 22, value) class YINC(TREElement): def __init__(self, value): super(YINC, self).__init__() self.add_field('YINC', 's', 22, value) class YIDC(TREElement): def __init__(self, value): super(YIDC, self).__init__() self.add_field('YIDC', 's', 22, value) class IMRFCAType(TREElement): def __init__(self, value): super(IMRFCAType, self).__init__() self.add_loop('XINCs', 20, XINC, value) self.add_loop('XIDCs', 20, XIDC, value) self.add_loop('YINCs', 20, YINC, value) self.add_loop('YIDCs', 20, YIDC, value) class IMRFCA(TREExtension): _tag_value = 'IMRFCA' _data_type = IMRFCAType
1,069
23.318182
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/REGPTB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PT(TREElement): def __init__(self, value): super(PT, self).__init__() self.add_field('PID', 's', 10, value) self.add_field('LON', 's', 15, value) self.add_field('LAT', 's', 15, value) self.add_field('ZVL', 's', 15, value) self.add_field('DIX', 's', 11, value) self.add_field('DIY', 's', 11, value) class REGPTBType(TREElement): def __init__(self, value): super(REGPTBType, self).__init__() self.add_field('NUMPTS', 'd', 4, value) self.add_loop('PTs', self.NUMPTS, PT, value) class REGPTB(TREExtension): _tag_value = 'REGPTB' _data_type = REGPTBType
780
25.931034
52
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/OFFSET.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class OFFSETType(TREElement): def __init__(self, value): super(OFFSETType, self).__init__() self.add_field('LINE', 's', 8, value) self.add_field('SAMPLE', 's', 8, value) class OFFSET(TREExtension): _tag_value = 'OFFSET' _data_type = OFFSETType
407
21.666667
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/PIXQLA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class AIS(TREElement): def __init__(self, value): super(AIS, self).__init__() self.add_field('AISDLVL', 's', 3, value) class PIXQUAL(TREElement): def __init__(self, value): super(PIXQUAL, self).__init__() self.add_field('PQ_CONDITION', 's', 40, value) class PIXQLAType(TREElement): def __init__(self, value): super(PIXQLAType, self).__init__() self.add_field('NUMAIS', 's', 3, value) if self.NUMAIS != 'ALL': self.add_loop('AISs', int(self.NUMAIS), AIS, value) self.add_field('NPIXQUAL', 'd', 4, value) self.add_field('PQ_BIT_VALUE', 's', 1, value) self.add_loop('PIXQUALs', self.NPIXQUAL, PIXQUAL, value) class PIXQLA(TREExtension): _tag_value = 'PIXQLA' _data_type = PIXQLAType
923
26.176471
64
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/ACCPOB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PT(TREElement): def __init__(self, value): super(PT, self).__init__() self.add_field('LON', 's', 15, value) self.add_field('LAT', 's', 15, value) class ACPO(TREElement): def __init__(self, value): super(ACPO, self).__init__() self.add_field('UNIAAH', 's', 3, value) self.add_field('AAH', 's', 5, value) self.add_field('UNIAAV', 's', 3, value) self.add_field('AAV', 's', 5, value) self.add_field('UNIAPH', 's', 3, value) self.add_field('APH', 's', 5, value) self.add_field('UNIAPV', 's', 3, value) self.add_field('APV', 's', 5, value) self.add_field('NUMPTS', 'd', 3, value) self.add_loop('PTs', self.NUMPTS, PT, value) class ACCPOBType(TREElement): def __init__(self, value): super(ACCPOBType, self).__init__() self.add_field('NUMACPO', 'd', 2, value) self.add_loop('ACPOs', self.NUMACPO, ACPO, value) class ACCPOB(TREExtension): _tag_value = 'ACCPOB' _data_type = ACCPOBType
1,169
28.25
57
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/PLTFMA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PLTFMAType(TREElement): def __init__(self, value): super(PLTFMAType, self).__init__() self.add_field('VERNUM', 's', 4, value) self.add_field('P_NAME', 's', 12, value) self.add_field('P_DESCR', 's', 40, value) self.add_field('P_DATE', 's', 8, value) self.add_field('P_TIME', 's', 9, value) self.add_field('P_TYPE', 's', 1, value) if self.P_TYPE in ['G', 'T', 'M']: self.add_field('SNSR_HT', 's', 3, value) self.add_field('SNSRLOC', 's', 21, value) self.add_field('SNSRHDNG', 's', 3, value) elif self.P_TYPE == 'A': self.add_field('AC_TYPE', 's', 15, value) self.add_field('AC_SERIAL', 's', 12, value) self.add_field('AC_T_NUM', 's', 10, value) self.add_field('AC_PITCH', 's', 5, value) self.add_field('AC_ROLL', 's', 5, value) self.add_field('AC_HDNG', 's', 3, value) self.add_field('AC_REF_PT', 's', 1, value) self.add_field('AC_POS_X', 's', 9, value) self.add_field('AC_POS_Y', 's', 9, value) self.add_field('AC_POS_Z', 's', 9, value) self.add_field('AC_VEL_X', 's', 9, value) self.add_field('AC_VEL_Y', 's', 9, value) self.add_field('AC_POS_Z', 's', 9, value) self.add_field('AC_ACC_X', 's', 8, value) self.add_field('AC_ACC_Y', 's', 8, value) self.add_field('AC_POS_Z', 's', 8, value) self.add_field('AC_SPEED', 's', 5, value) self.add_field('ENTLOC', 's', 21, value) self.add_field('ENTALT', 's', 6, value) self.add_field('EXITLOC', 's', 21, value) self.add_field('EXITALTH', 's', 6, value) self.add_field('INS_V_NC', 's', 5, value) self.add_field('INS_V_EC', 's', 5, value) self.add_field('INS_V_DC', 's', 5, value) class PLTFMA(TREExtension): _tag_value = 'PLTFMA' _data_type = PLTFMAType
2,136
40.901961
55
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/AIMIDB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class AIMIDBType(TREElement): def __init__(self, value): super(AIMIDBType, self).__init__() self.add_field('ACQUISITION_DATE', 's', 14, value) self.add_field('MISSION_NO', 's', 4, value) self.add_field('MISSION_IDENTIFICATION', 's', 10, value) self.add_field('FLIGHT_NO', 's', 2, value) self.add_field('OP_NUM', 's', 3, value) self.add_field('CURRENT_SEGMENT', 's', 2, value) self.add_field('REPRO_NUM', 's', 2, value) self.add_field('REPLAY', 's', 3, value) self.add_field('RESERVED_001', 's', 1, value) self.add_field('START_TILE_COLUMN', 's', 3, value) self.add_field('START_TILE_ROW', 's', 5, value) self.add_field('END_SEGMENT', 's', 2, value) self.add_field('END_TILE_COLUMN', 's', 3, value) self.add_field('END_TILE_ROW', 's', 5, value) self.add_field('COUNTRY', 's', 2, value) self.add_field('RESERVED002', 's', 4, value) self.add_field('LOCATION', 's', 11, value) self.add_field('RESERVED003', 's', 13, value) class AIMIDB(TREExtension): _tag_value = 'AIMIDB' _data_type = AIMIDBType
1,284
36.794118
64
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/RSMDCA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class IMGE(TREElement): def __init__(self, value): super(IMGE, self).__init__() self.add_field('IIDI', 's', 80, value) self.add_field('NPARI', 'd', 2, value) class DERCOV(TREElement): def __init__(self, value): super(DERCOV, self).__init__() self.add_field('DERCOV', 's', 21, value) class RSMDCAType(TREElement): def __init__(self, value): super(RSMDCAType, self).__init__() self.add_field('IID', 's', 80, value) self.add_field('EDITION', 's', 40, value) self.add_field('TID', 's', 40, value) self.add_field('NPAR', 'd', 2, value) self.add_field('NIMGE', 'd', 3, value) self.add_field('NPART', 'd', 5, value) self.add_loop('IMGEs', self.NIMGE, IMGE, value) self.add_field('XUOL', 's', 21, value) self.add_field('YUOL', 's', 21, value) self.add_field('ZUOL', 's', 21, value) self.add_field('XUXL', 's', 21, value) self.add_field('XUYL', 's', 21, value) self.add_field('XUZL', 's', 21, value) self.add_field('YUXL', 's', 21, value) self.add_field('YUYL', 's', 21, value) self.add_field('YUZL', 's', 21, value) self.add_field('ZUXL', 's', 21, value) self.add_field('ZUYL', 's', 21, value) self.add_field('ZUZL', 's', 21, value) self.add_field('IR0', 's', 2, value) self.add_field('IRX', 's', 2, value) self.add_field('IRY', 's', 2, value) self.add_field('IRZ', 's', 2, value) self.add_field('IRXX', 's', 2, value) self.add_field('IRXY', 's', 2, value) self.add_field('IRXZ', 's', 2, value) self.add_field('IRYY', 's', 2, value) self.add_field('IRYZ', 's', 2, value) self.add_field('IRZZ', 's', 2, value) self.add_field('IC0', 's', 2, value) self.add_field('ICX', 's', 2, value) self.add_field('ICY', 's', 2, value) self.add_field('ICZ', 's', 2, value) self.add_field('ICXX', 's', 2, value) self.add_field('ICXY', 's', 2, value) self.add_field('ICXZ', 's', 2, value) self.add_field('ICYY', 's', 2, value) self.add_field('ICYZ', 's', 2, value) self.add_field('ICZZ', 's', 2, value) self.add_field('GX0', 's', 2, value) self.add_field('GY0', 's', 2, value) self.add_field('GZ0', 's', 2, value) self.add_field('GXR', 's', 2, value) self.add_field('GYR', 's', 2, value) self.add_field('GZR', 's', 2, value) self.add_field('GS', 's', 2, value) self.add_field('GXX', 's', 2, value) self.add_field('GXY', 's', 2, value) self.add_field('GXZ', 's', 2, value) self.add_field('GYX', 's', 2, value) self.add_field('GYY', 's', 2, value) self.add_field('GYZ', 's', 2, value) self.add_field('GZX', 's', 2, value) self.add_field('GZY', 's', 2, value) self.add_field('GZZ', 's', 2, value) self.add_loop('DERCOVs', self.dercov_count(), DERCOV, value) def dercov_count(self): # type: () -> int return int((self.NPART+1)*self.NPART/2) class RSMDCA(TREExtension): _tag_value = 'RSMDCA' _data_type = RSMDCAType
3,346
37.034091
68
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/GEOPSB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class GEOPSBType(TREElement): def __init__(self, value): super(GEOPSBType, self).__init__() self.add_field('TYP', 's', 3, value) self.add_field('UNI', 's', 3, value) self.add_field('DAG', 's', 80, value) self.add_field('DCD', 's', 4, value) self.add_field('ELL', 's', 80, value) self.add_field('ELC', 's', 3, value) self.add_field('DVR', 's', 80, value) self.add_field('VDCDVR', 's', 4, value) self.add_field('SDA', 's', 80, value) self.add_field('VDCSDA', 's', 4, value) self.add_field('ZOR', 's', 15, value) self.add_field('GRD', 's', 3, value) self.add_field('GRN', 's', 80, value) self.add_field('ZNA', 's', 4, value) class GEOPSB(TREExtension): _tag_value = 'GEOPSB' _data_type = GEOPSBType
955
30.866667
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/PIAPRD.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class SECTT(TREElement): def __init__(self, value): super(SECTT, self).__init__() self.add_field('SECTITLE', 's', 40, value) self.add_field('PPNUM', 's', 5, value) self.add_field('TPP', 's', 3, value) class RQORG(TREElement): def __init__(self, value): super(RQORG, self).__init__() self.add_field('REQORG', 's', 64, value) class KEYWD(TREElement): def __init__(self, value): super(KEYWD, self).__init__() self.add_field('KEYWORD', 's', 255, value) class ASRPT(TREElement): def __init__(self, value): super(ASRPT, self).__init__() self.add_field('ASSRPT', 's', 20, value) class ATEXT(TREElement): def __init__(self, value): super(ATEXT, self).__init__() self.add_field('ATEXT', 's', 255, value) class PIAPRDType(TREElement): def __init__(self, value): super(PIAPRDType, self).__init__() self.add_field('ACCESSID', 's', 64, value) self.add_field('FMCNTROL', 's', 32, value) self.add_field('SUBDET', 's', 1, value) self.add_field('PRODCODE', 's', 2, value) self.add_field('PRODCRSE', 's', 6, value) self.add_field('PRODIDNO', 's', 20, value) self.add_field('PRODSNME', 's', 10, value) self.add_field('PRODCRCD', 's', 2, value) self.add_field('PRODCRTM', 's', 14, value) self.add_field('MAPID', 's', 40, value) self.add_field('SECTTREP', 'd', 2, value) self.add_loop('SECTTs', self.SECTTREP, SECTT, value) self.add_field('RQORGREP', 'd', 2, value) self.add_loop('RQORGs', self.RQORGREP, RQORG, value) self.add_field('KEYWDREP', 'd', 2, value) self.add_loop('KEYWDs', self.KEYWDREP, KEYWD, value) self.add_field('ASRPTREP', 'd', 2, value) self.add_loop('ASRPTs', self.ASRPTREP, ASRPT, value) self.add_field('ATEXTREP', 'd', 2, value) self.add_loop('ATEXTs', self.ATEXTREP, ATEXT, value) class PIAPRD(TREExtension): _tag_value = 'PIAPRD' _data_type = PIAPRDType
2,190
31.220588
60
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/BANDSB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" # TODO: I'm not entirely confident that these bit operation work as expected class PARAMETER(TREElement): def __init__(self, value, EXISTENCE_MASK): super(PARAMETER, self).__init__() if EXISTENCE_MASK & 0x10000000: self.add_field('BANDID', 's', 50, value) if EXISTENCE_MASK & 0x08000000: self.add_field('BAD_BAND', 'd', 1, value) if EXISTENCE_MASK & 0x04000000: self.add_field('NIIRS', 'd', 3, value) if EXISTENCE_MASK & 0x02000000: self.add_field('FOCAL_LEN', 'd', 5, value) if EXISTENCE_MASK & 0x01000000: self.add_field('CWAVE', 'd', 7, value) if EXISTENCE_MASK & 0x00800000: self.add_field('FWHM', 'd', 7, value) if EXISTENCE_MASK & 0x00400000: self.add_field('FWHM_UNC', 'd', 7, value) if EXISTENCE_MASK & 0x00200000: self.add_field('NOM_WAVE', 'd', 7, value) if EXISTENCE_MASK & 0x00100000: self.add_field('NOM_WAVE_UNC', 'd', 7, value) if EXISTENCE_MASK & 0x00080000: self.add_field('LBOUND', 'd', 7, value) self.add_field('UBOUND', 'd', 7, value) if EXISTENCE_MASK & 0x00040000: self.add_field('SCALE_FACTOR', 'b', 4, value) self.add_field('ADDITIVE_FACTOR', 'b', 4, value) if EXISTENCE_MASK & 0x00020000: self.add_field('START_TIME', 's', 16, value) if EXISTENCE_MASK & 0x00010000: self.add_field('INT_TIME', 'd', 6, value) if EXISTENCE_MASK & 0x00008000: self.add_field('CALDRK', 'd', 6, value) self.add_field('CALIBRATION_SENSITIVITY', 'd', 5, value) if EXISTENCE_MASK & 0x00004000: self.add_field('ROW_GSD', 'd', 7, value) if EXISTENCE_MASK & 0x00002000: self.add_field('ROW_GSD_UNC', 'd', 7, value) self.add_field('ROW_GSD_UNIT', 's', 1, value) self.add_field('COL_GSD', 'd', 7, value) if EXISTENCE_MASK & 0x00002000: self.add_field('COL_GSD_UNC', 'd', 7, value) self.add_field('COL_GSD_UNIT', 's', 1, value) if EXISTENCE_MASK & 0x00001000: self.add_field('BKNOISE', 'd', 5, value) self.add_field('SCNNOISE', 'd', 5, value) if EXISTENCE_MASK & 0x00000800: self.add_field('SPT_RESP_FUNCTION_ROW', 'd', 7, value) if EXISTENCE_MASK & 0x00000400: self.add_field('SPT_RESP_UNC_ROW', 'd', 7, value) self.add_field('SPT_RESP_UNIT_ROW', 's', 1, value) self.add_field('SPT_RESP_FUNCTION_COL', 'd', 7, value) if EXISTENCE_MASK & 0x00000400: self.add_field('SPT_RESP_UNC_COL', 'd', 7, value) self.add_field('SPT_RESP_UNIT_COL', 's', 1, value) if EXISTENCE_MASK & 0x00000200: self.add_field('DATA_FLD_3', 'b', 16, value) if EXISTENCE_MASK & 0x00000100: self.add_field('DATA_FLD_4', 'b', 24, value) if EXISTENCE_MASK & 0x00000080: self.add_field('DATA_FLD_5', 'b', 32, value) if EXISTENCE_MASK & 0x00000040: self.add_field('DATA_FLD_6', 'b', 48, value) class BAND(TREElement): def __init__(self, value): super(BAND, self).__init__() if self.BAPF == 'I': self.add_field('APN', 'd', 10, value) if self.BAPF == 'R': self.add_field('APR', 'b', 4, value) if self.BAPF == 'A': self.add_field('APA', 'd', 20, value) class AUX_B(TREElement): def __init__(self, value): super(AUX_B, self).__init__() self.add_field('BAPF', 's', 1, value) self.add_field('UBAP', 's', 7, value) self.add_loop('BANDs', self.COUNT, BAND, value) class AUX_C(TREElement): def __init__(self, value): super(AUX_C, self).__init__() self.add_field('CAPF', 's', 1, value) self.add_field('UCAP', 's', 7, value) if self.CAPF == 'I': self.add_field('APN', 'd', 10, value) if self.CAPF == 'R': self.add_field('APR', 'b', 4, value) if self.CAPF == 'A': self.add_field('APA', 'd', 20, value) class BANDSBType(TREElement): def __init__(self, value): super(BANDSBType, self).__init__() self.add_field('COUNT', 'd', 5, value) self.add_field('RADIOMETRIC_QUANTITY', 's', 24, value) self.add_field('RADIOMETRIC_QUANTITY_UNIT', 's', 1, value) self.add_field('SCALE_FACTOR', 'b', 4, value) self.add_field('ADDITIVE_FACTOR', 'b', 4, value) self.add_field('ROW_GSD', 'd', 7, value) self.add_field('ROW_GSD_UNIT', 's', 1, value) self.add_field('COL_GSD', 'd', 7, value) self.add_field('COL_GSD_UNIT', 's', 1, value) self.add_field('SPT_RESP_ROW', 'd', 7, value) self.add_field('SPT_RESP_UNIT_ROW', 's', 1, value) self.add_field('SPT_RESP_COL', 'd', 7, value) self.add_field('SPT_RESP_UNIT_COL', 's', 1, value) self.add_field('DATA_FLD_1', 'b', 48, value) self.add_field('EXISTENCE_MASK', 'b', 4, value) if self.EXISTENCE_MASK & 0x80000000: self.add_field('RADIOMETRIC_ADJUSTMENT_SURFACE', 's', 24, value) self.add_field('ATMOSPHERIC_ADJUSTMENT_ALTITUDE', 'b', 4, value) if self.EXISTENCE_MASK & 0x40000000: self.add_field('DIAMETER', 'd', 7, value) if self.EXISTENCE_MASK & 0x20000000: self.add_field('DATA_FLD_2', 'b', 32, value) if self.EXISTENCE_MASK & 0x01F80000: self.add_field('WAVE_LENGTH_UNIT', 's', 1, value) self.add_loop('PARAMETERs', self.COUNT, PARAMETER, value, self.EXISTENCE_MASK) if self.EXISTENCE_MASK & 0x00000001: self.add_field('NUM_AUX_B', 'd', 2, value) self.add_field('NUM_AUX_C', 'd', 2, value) self.add_loop('AUX_Bs', self.NUM_AUX_B, AUX_B, value) self.add_loop('AUX_Cs', self.NUM_AUX_C, AUX_C, value) self.add_field('NULL', 'U', 0, value) class BANDSB(TREExtension): _tag_value = 'BANDSB' _data_type = BANDSBType
6,291
42.09589
86
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/PIAPEA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PIAPEAType(TREElement): def __init__(self, value): super(PIAPEAType, self).__init__() self.add_field('LASTNME', 's', 28, value) self.add_field('FIRSTNME', 's', 28, value) self.add_field('MIDNME', 's', 28, value) self.add_field('DOB', 's', 6, value) self.add_field('ASSOCTRY', 's', 2, value) class PIAPEA(TREExtension): _tag_value = 'PIAPEA' _data_type = PIAPEAType
558
25.619048
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/GRDPSB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class GRD(TREElement): def __init__(self, value): super(GRD, self).__init__() self.add_field('ZVL', 's', 10, value) self.add_field('BAD', 's', 10, value) self.add_field('LOD', 's', 12, value) self.add_field('LAD', 's', 12, value) self.add_field('LSO', 's', 11, value) self.add_field('PSO', 's', 11, value) class GRDPSBType(TREElement): def __init__(self, value): super(GRDPSBType, self).__init__() self.add_field('NUM_GRDS', 'd', 2, value) self.add_loop('GRDs', self.NUM_GRDS, GRD, value) class GRDPSB(TREExtension): _tag_value = 'GRDPSB' _data_type = GRDPSBType
788
26.206897
56
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/PRJPSB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PRJ(TREElement): def __init__(self, value): super(PRJ, self).__init__() self.add_field('PRJ', 's', 15, value) class PRJPSBType(TREElement): def __init__(self, value): super(PRJPSBType, self).__init__() self.add_field('PRN', 's', 80, value) self.add_field('PCO', 's', 2, value) self.add_field('NUM_PRJ', 'd', 1, value) self.add_loop('PRJs', self.NUM_PRJ, PRJ, value) self.add_field('XOR', 's', 15, value) self.add_field('YOR', 's', 15, value) class PRJPSB(TREExtension): _tag_value = 'PRJPSB' _data_type = PRJPSBType
739
25.428571
55
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/IMASDA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class IMASDAType(TREElement): def __init__(self, value): super(IMASDAType, self).__init__() self.add_field('LONTR', 's', 22, value) self.add_field('LATTR', 's', 22, value) self.add_field('ELVTR', 's', 22, value) self.add_field('LONSC', 's', 22, value) self.add_field('LATSC', 's', 22, value) self.add_field('ELVSC', 's', 22, value) self.add_field('XITR', 's', 22, value) self.add_field('YITR', 's', 22, value) self.add_field('XISC', 's', 22, value) self.add_field('YISC', 's', 22, value) self.add_field('DELEV', 's', 22, value) class IMASDA(TREExtension): _tag_value = 'IMASDA' _data_type = IMASDAType
837
30.037037
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/PIAIMB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PIAIMBType(TREElement): def __init__(self, value): super(PIAIMBType, self).__init__() self.add_field('CLOUD', 's', 3, value) self.add_field('STDRD', 's', 1, value) self.add_field('SMODE', 's', 12, value) self.add_field('SNAME', 's', 18, value) self.add_field('SRCE', 's', 255, value) self.add_field('CMGEN', 's', 2, value) self.add_field('SQUAL', 's', 1, value) self.add_field('MISNM', 's', 7, value) self.add_field('CSPEC', 's', 32, value) self.add_field('PJTID', 's', 2, value) self.add_field('GENER', 's', 1, value) self.add_field('EXPLS', 's', 1, value) self.add_field('OTHRC', 's', 2, value) class PIAIMB(TREExtension): _tag_value = 'PIAIMB' _data_type = PIAIMBType
928
31.034483
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/SOURCB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PT(TREElement): def __init__(self, value): super(PT, self).__init__() self.add_field('LON', 's', 15, value) self.add_field('LAT', 's', 15, value) class BP(TREElement): def __init__(self, value): super(BP, self).__init__() self.add_field('NUM_PTS', 'd', 3, value) self.add_loop('PTs', self.NUM_PTS, PT, value) class MI(TREElement): def __init__(self, value): super(MI, self).__init__() self.add_field('CDV30', 's', 8, value) self.add_field('UNIRAT', 's', 3, value) self.add_field('RAT', 's', 8, value) self.add_field('UNIGMA', 's', 3, value) self.add_field('GMA', 's', 8, value) self.add_field('LONGMA', 's', 15, value) self.add_field('LATGMA', 's', 15, value) self.add_field('UNIGCA', 's', 3, value) self.add_field('GCA', 's', 8, value) class LI(TREElement): def __init__(self, value): super(LI, self).__init__() self.add_field('BAD', 's', 10, value) class PRJ(TREElement): def __init__(self, value): super(PRJ, self).__init__() self.add_field('PRJ', 's', 15, value) class IN(TREElement): def __init__(self, value): super(IN, self).__init__() self.add_field('INT', 's', 10, value) self.add_field('INS_SCA', 's', 9, value) self.add_field('NTL', 's', 15, value) self.add_field('TTL', 's', 15, value) self.add_field('NVL', 's', 15, value) self.add_field('TVL', 's', 15, value) self.add_field('NTR', 's', 15, value) self.add_field('TTR', 's', 15, value) self.add_field('NVR', 's', 15, value) self.add_field('TVR', 's', 15, value) self.add_field('NRL', 's', 15, value) self.add_field('TRL', 's', 15, value) self.add_field('NSL', 's', 15, value) self.add_field('TSL', 's', 15, value) self.add_field('NRR', 's', 15, value) self.add_field('TRR', 's', 15, value) self.add_field('NSR', 's', 15, value) self.add_field('TSR', 's', 15, value) class SOUR(TREElement): def __init__(self, value): super(SOUR, self).__init__() self.add_field('NUM_BP', 'd', 2, value) self.add_loop('BPs', self.NUM_BP, BP, value) self.add_field('PRT', 's', 10, value) self.add_field('URF', 's', 20, value) self.add_field('EDN', 's', 7, value) self.add_field('NAM', 's', 20, value) self.add_field('CDP', 's', 3, value) self.add_field('CDV', 's', 8, value) self.add_field('CDV27', 's', 8, value) self.add_field('SRN', 's', 80, value) self.add_field('SCA', 's', 9, value) self.add_field('UNISQU', 's', 3, value) self.add_field('SQU', 's', 10, value) self.add_field('UNIPCI', 's', 3, value) self.add_field('PCI', 's', 4, value) self.add_field('WPC', 's', 3, value) self.add_field('NST', 's', 3, value) self.add_field('UNIHKE', 's', 3, value) self.add_field('HKE', 's', 6, value) self.add_field('LONHKE', 's', 15, value) self.add_field('LATHKE', 's', 15, value) self.add_field('QSS', 's', 1, value) self.add_field('QOD', 's', 1, value) self.add_field('CDV10', 's', 8, value) self.add_field('QLE', 's', 80, value) self.add_field('CPY', 's', 80, value) self.add_field('NMI', 'd', 2, value) self.add_loop('MIs', self.NMI, MI, value) self.add_field('NLI', 'd', 2, value) self.add_loop('LIs', self.NLI, LI, value) self.add_field('DAG', 's', 80, value) self.add_field('DCD', 's', 4, value) self.add_field('ELL', 's', 80, value) self.add_field('ELC', 's', 3, value) self.add_field('DVR', 's', 80, value) self.add_field('VDCDVR', 's', 4, value) self.add_field('SDA', 's', 80, value) self.add_field('VDCSDA', 's', 4, value) self.add_field('PRN', 's', 80, value) self.add_field('PCO', 's', 2, value) self.add_field('NUM_PRJ', 'd', 1, value) self.add_loop('PRJs', self.NUM_PRJ, PRJ, value) self.add_field('XOR', 's', 15, value) self.add_field('YOR', 's', 15, value) self.add_field('GRD', 's', 3, value) self.add_field('GRN', 's', 80, value) self.add_field('ZNA', 's', 4, value) self.add_field('NIN', 'd', 2, value) self.add_loop('INs', self.NIN, IN, value) class SOURCBType(TREElement): def __init__(self, value): super(SOURCBType, self).__init__() self.add_field('IS_SCA', 's', 9, value) self.add_field('CPATCH', 's', 10, value) self.add_field('NUM_SOUR', 'd', 2, value) self.add_loop('SOURs', self.NUM_SOUR, SOUR, value) class SOURCB(TREExtension): _tag_value = 'SOURCB' _data_type = SOURCBType
4,985
35.394161
58
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/MTIRPA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class VTGT(TREElement): def __init__(self, value): super(VTGT, self).__init__() self.add_field('TGLOC', 's', 21, value) self.add_field('TGRDV', 's', 4, value) self.add_field('TGGSP', 's', 3, value) self.add_field('TGHEA', 's', 3, value) self.add_field('TGSIG', 's', 2, value) self.add_field('TGCAT', 's', 1, value) class MTIRPAType(TREElement): def __init__(self, value): super(MTIRPAType, self).__init__() self.add_field('DESTP', 's', 2, value) self.add_field('MTPID', 's', 3, value) self.add_field('PCHNO', 's', 4, value) self.add_field('WAMFN', 's', 5, value) self.add_field('WAMBN', 's', 1, value) self.add_field('UTC', 's', 8, value) self.add_field('SQNTA', 's', 5, value) self.add_field('COSGZ', 's', 7, value) self.add_field('NVTGT', 'd', 3, value) self.add_loop('VTGTs', self.NVTGT, VTGT, value) class MTIRPA(TREExtension): _tag_value = 'MTIRPA' _data_type = MTIRPAType
1,167
30.567568
55
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/TRGTA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class TGT_QC(TREElement): def __init__(self, value): super(TGT_QC, self).__init__() self.add_field('TGT_QCOMMENT', 's', 40, value) class TGT_CC(TREElement): def __init__(self, value): super(TGT_CC, self).__init__() self.add_field('TGT_CCOMMENT', 's', 40, value) class REF_PT(TREElement): def __init__(self, value): super(REF_PT, self).__init__() self.add_field('TGT_REF', 's', 10, value) self.add_field('TGT_LL', 's', 21, value) self.add_field('TGT_ELEV', 's', 8, value) self.add_field('TGT_BAND', 's', 3, value) self.add_field('TGT_ROW', 's', 8, value) self.add_field('TGT_COL', 's', 8, value) self.add_field('TGT_PROW', 's', 8, value) self.add_field('TGT_PCOL', 's', 8, value) class VALID_TGT(TREElement): def __init__(self, value): super(VALID_TGT, self).__init__() self.add_field('TGT_NAME', 's', 25, value) self.add_field('TGT_TYPE', 's', 15, value) self.add_field('TGT_VER', 's', 6, value) self.add_field('TGT_CAT', 's', 5, value) self.add_field('TGT_BE', 's', 17, value) self.add_field('TGT_SN', 's', 10, value) self.add_field('TGT_POSNUM', 's', 2, value) self.add_field('TGT_ATTITUDE_PITCH', 's', 6, value) self.add_field('TGT_ATTITUDE_ROLL', 's', 6, value) self.add_field('TGT_ATTITUDE_YAW', 's', 6, value) self.add_field('TGT_DIM_LENGTH', 's', 5, value) self.add_field('TGT_DIM_WIDTH', 's', 5, value) self.add_field('TGT_DIM_HEIGHT', 's', 5, value) self.add_field('TGT_AZIMUTH', 's', 6, value) self.add_field('TGT_CLTR_RATIO', 's', 8, value) self.add_field('TGT_STATE', 's', 10, value) self.add_field('TGT_COND', 's', 30, value) self.add_field('TGT_OBSCR', 's', 20, value) self.add_field('TGT_OBSCR%', 's', 3, value) self.add_field('TGT_CAMO', 's', 20, value) self.add_field('TGT_CAMO%', 's', 3, value) self.add_field('TGT_UNDER', 's', 12, value) self.add_field('TGT_OVER', 's', 30, value) self.add_field('TGT_TTEXTURE', 's', 45, value) self.add_field('TGT_PAINT', 's', 40, value) self.add_field('TGT_SPEED', 's', 3, value) self.add_field('TGT_HEADING', 's', 3, value) self.add_field('TGT_QC_NUM', 'd', 1, value) self.add_loop('TGT_QCs', self.TGT_QC_NUM, TGT_QC, value) self.add_field('TGT_CC_NUM', 'd', 1, value) self.add_loop('TGT_CCs', self.TGT_CC_NUM, TGT_CC, value) self.add_field('NO_REF_PT', 'd', 1, value) self.add_loop('REF_PTs', self.NO_REF_PT, REF_PT, value) class ATTRIBUTE(TREElement): def __init__(self, value): super(ATTRIBUTE, self).__init__() self.add_field('ATTR_TGT_NUM', 's', 3, value) self.add_field('ATTR_NAME', 's', 30, value) self.add_field('ATTR_CONDTN', 's', 35, value) self.add_field('ATTR_VALUE', 's', 10, value) class TRGTAType(TREElement): def __init__(self, value): super(TRGTAType, self).__init__() self.add_field('VERNUM', 's', 4, value) self.add_field('NO_VALID_TGTS', 'd', 3, value) self.add_field('NO_SCENE_TGTS', 'd', 3, value) self.add_loop('VALID_TGTs', self.NO_VALID_TGTS, VALID_TGT, value) self.add_field('NO_ATTRIBUTES', 'd', 3, value) self.add_loop('ATTRIBUTEs', self.NO_ATTRIBUTES, ATTRIBUTE, value) class TRGTA(TREExtension): _tag_value = 'TRGTA' _data_type = TRGTAType
3,666
38.010638
73
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/MPDSRA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class MPDSRAType(TREElement): def __init__(self, value): super(MPDSRAType, self).__init__() self.add_field('BLKNO', 's', 2, value) self.add_field('CDIPR', 's', 2, value) self.add_field('NBLKW', 's', 2, value) self.add_field('NRBLK', 's', 5, value) self.add_field('NCBLK', 's', 5, value) self.add_field('ORPX', 's', 9, value) self.add_field('ORPY', 's', 9, value) self.add_field('ORPZ', 's', 9, value) self.add_field('ORPRO', 's', 5, value) self.add_field('ORPCO', 's', 5, value) self.add_field('FPNVX', 's', 7, value) self.add_field('FPNVY', 's', 7, value) self.add_field('FPNVZ', 's', 7, value) self.add_field('ARPTM', 's', 9, value) self.add_field('RESV1', 's', 14, value) self.add_field('ARPPN', 's', 9, value) self.add_field('ARPPE', 's', 9, value) self.add_field('ARPPD', 's', 9, value) self.add_field('ARPVN', 's', 9, value) self.add_field('ARPVE', 's', 9, value) self.add_field('ARPVD', 's', 9, value) self.add_field('ARPAN', 's', 8, value) self.add_field('ARPAE', 's', 8, value) self.add_field('ARPAD', 's', 8, value) self.add_field('RESV2', 's', 13, value) class MPDSRA(TREExtension): _tag_value = 'MPDSRA' _data_type = MPDSRAType
1,487
35.292683
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/BCKGDA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class BCKGDAType(TREElement): def __init__(self, value): super(BCKGDAType, self).__init__() self.add_field('BGWIDTH', 's', 8, value) self.add_field('BGHEIGHT', 's', 8, value) self.add_field('BGRED', 's', 8, value) self.add_field('BGGREEN', 's', 8, value) self.add_field('BGBLUE', 's', 8, value) self.add_field('PIXSIZE', 's', 8, value) self.add_field('PIXUNITS', 's', 8, value) class BCKGDA(TREExtension): _tag_value = 'BCKGDA' _data_type = BCKGDAType
655
27.521739
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/PIAEQA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PIAEQAType(TREElement): def __init__(self, value): super(PIAEQAType, self).__init__() self.add_field('EQPCODE', 's', 7, value) self.add_field('EQPNOMEN', 's', 45, value) self.add_field('EQPMAN', 's', 64, value) self.add_field('OBTYPE', 's', 1, value) self.add_field('ORDBAT', 's', 3, value) self.add_field('CTRYPROD', 's', 2, value) self.add_field('CTRYDSN', 's', 2, value) self.add_field('OBJVIEW', 's', 6, value) class PIAEQA(TREExtension): _tag_value = 'PIAEQA' _data_type = PIAEQAType
706
28.458333
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/CSCRNA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class CSCRNAType(TREElement): def __init__(self, value): super(CSCRNAType, self).__init__() self.add_field('PREDICT_CORNERS', 's', 1, value) self.add_field('ULCNR_LAT', 's', 9, value) self.add_field('ULCNR_LONG', 's', 10, value) self.add_field('ULCNR_HT', 's', 8, value) self.add_field('URCNR_LAT', 's', 9, value) self.add_field('URCNR_LONG', 's', 10, value) self.add_field('URCNR_HT', 's', 8, value) self.add_field('LRCNR_LAT', 's', 9, value) self.add_field('LRCNR_LONG', 's', 10, value) self.add_field('LRCNR_HT', 's', 8, value) self.add_field('LLCNR_LAT', 's', 9, value) self.add_field('LLCNR_LONG', 's', 10, value) self.add_field('LLCNR_HT', 's', 8, value) class CSCRNA(TREExtension): _tag_value = 'CSCRNA' _data_type = CSCRNAType
986
33.034483
56
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/PATCHA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PATCHA_74Type(TREElement): def __init__(self, value): super(PATCHA_74Type, self).__init__() self.add_field('PAT_NO', 's', 4, value) self.add_field('LAST_PAT_FLAG', 's', 1, value) self.add_field('LNSTRT', 's', 7, value) self.add_field('LNSTOP', 's', 7, value) self.add_field('AZL', 's', 5, value) self.add_field('NVL', 's', 5, value) self.add_field('FVL', 's', 3, value) self.add_field('NPIXEL', 's', 5, value) self.add_field('FVPIX', 's', 5, value) self.add_field('FRAME', 's', 3, value) self.add_field('GMT', 's', 8, value) self.add_field('SHEAD', 's', 7, value) self.add_field('GSWEEP', 's', 6, value) self.add_field('SHEAR', 's', 8, value) class PATCHA_74(TREExtension): _tag_value = 'PATCHA' _data_type = PATCHA_74Type class PATCHA_115Type(TREElement): def __init__(self, value): super(PATCHA_115Type, self).__init__() self.add_field('PAT_NO', 's', 4, value) self.add_field('LAST_PAT_FLAG', 's', 1, value) self.add_field('LNSTRT', 's', 7, value) self.add_field('LNSTOP', 's', 7, value) self.add_field('AZL', 's', 5, value) self.add_field('NVL', 's', 5, value) self.add_field('FVL', 's', 3, value) self.add_field('NPIXEL', 's', 5, value) self.add_field('FVPIX', 's', 5, value) self.add_field('FRAME', 's', 3, value) self.add_field('UTC', 's', 8, value) self.add_field('SHEAD', 's', 7, value) self.add_field('GRAVITY', 's', 7, value) self.add_field('INS_V_NC', 's', 5, value) self.add_field('INS_V_EC', 's', 5, value) self.add_field('INS_V_DC', 's', 5, value) self.add_field('OFFLAT', 's', 8, value) self.add_field('OFFLONG', 's', 8, value) self.add_field('TRACK', 's', 3, value) self.add_field('GSWEEP', 's', 6, value) self.add_field('SHEAR', 's', 8, value) class PATCHA_115(TREExtension): _tag_value = 'PATCHA' _data_type = PATCHA_115Type class PATCHA(TREExtension): _tag_value = 'PATCHA' def __init__(self): raise ValueError( 'Not to be implemented directly. ' 'Use of one PATCHA_74 or PATCHA_115') @classmethod def from_bytes(cls, value, start): """ Parameters ---------- value : bytes start : int Returns ------- PATCHA_74|PATCHA_115 """ tag_value = value[start:start+6].decode('utf-8').strip() if tag_value != cls._tag_value: raise ValueError('tag value must be {}. Got {}'.format(cls._tag_value, tag_value)) lng = int(value[start+6:start+11]) if lng == 74: return PATCHA_74.from_bytes(value, start) elif lng == 115: return PATCHA_115.from_bytes(value, start) else: raise ValueError('the data must be length 74 or 115. Got {}'.format(lng))
3,129
31.604167
94
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/MTIRPB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class VTGT(TREElement): def __init__(self, value): super(VTGT, self).__init__() self.add_field('TGLOC', 's', 23, value) self.add_field('TGLCA', 's', 6, value) self.add_field('TGRDV', 's', 4, value) self.add_field('TGGSP', 's', 3, value) self.add_field('TGHEA', 's', 3, value) self.add_field('TGSIG', 's', 2, value) self.add_field('TGCAT', 's', 1, value) class MTIRPBType(TREElement): def __init__(self, value): super(MTIRPBType, self).__init__() self.add_field('DESTP', 's', 2, value) self.add_field('MTPID', 's', 3, value) self.add_field('PCHNO', 's', 4, value) self.add_field('WAMFN', 's', 5, value) self.add_field('WAMBN', 's', 1, value) self.add_field('UTC', 's', 14, value) self.add_field('ACLOC', 's', 21, value) self.add_field('ACALT', 's', 6, value) self.add_field('ACALU', 's', 1, value) self.add_field('ACHED', 's', 3, value) self.add_field('MTILR', 's', 1, value) self.add_field('SQNTA', 's', 5, value) self.add_field('COSGZ', 's', 7, value) self.add_field('NVTGT', 'd', 3, value) self.add_loop('VTGTs', self.NVTGT, VTGT, value) class MTIRPB(TREExtension): _tag_value = 'MTIRPB' _data_type = MTIRPBType
1,451
32.767442
55
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/MENSRA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class MENSRA_155Type(TREElement): def __init__(self, value): super(MENSRA_155Type, self).__init__() self.add_field('CCRP_LOC', 's', 21, value) self.add_field('CCRP_ALT', 's', 6, value) self.add_field('OF_PC_R', 's', 7, value) self.add_field('OF_PC_A', 's', 7, value) self.add_field('COSGRZ', 's', 7, value) self.add_field('RGCCRP', 's', 7, value) self.add_field('RLMAP', 's', 1, value) self.add_field('CCRP_ROW', 's', 5, value) self.add_field('CCRP_COL', 's', 5, value) self.add_field('ACFT_LOC', 's', 21, value) self.add_field('ACFT_ALT', 's', 5, value) self.add_field('C_R_NC', 's', 7, value) self.add_field('C_R_EC', 's', 7, value) self.add_field('C_R_DC', 's', 7, value) self.add_field('C_AZ_NC', 's', 7, value) self.add_field('C_AZ_EC', 's', 7, value) self.add_field('C_AZ_DC', 's', 7, value) self.add_field('C_AL_NC', 's', 7, value) self.add_field('C_AL_EC', 's', 7, value) self.add_field('C_AL_DC', 's', 7, value) class MENSRA_155(TREExtension): _tag_value = 'MENSRA' _data_type = MENSRA_155Type class MENSRA_174Type(TREElement): def __init__(self, value): super(MENSRA_174Type, self).__init__() self.add_field('ACFT_LOC', 's', 21, value) self.add_field('ACFT_ALT', 's', 6, value) self.add_field('CCRP_LOC', 's', 21, value) self.add_field('CCRP_ALT', 's', 6, value) self.add_field('OF_PC_R', 's', 7, value) self.add_field('OF_PC_A', 's', 7, value) self.add_field('COSGRZ', 's', 7, value) self.add_field('RGCCRP', 's', 7, value) self.add_field('RLMAP', 's', 1, value) self.add_field('CCRP_ROW', 's', 5, value) self.add_field('CCRP_COL', 's', 5, value) self.add_field('C_R_NC', 's', 9, value) self.add_field('C_R_EC', 's', 9, value) self.add_field('C_R_DC', 's', 9, value) self.add_field('C_AZ_NC', 's', 9, value) self.add_field('C_AZ_EC', 's', 9, value) self.add_field('C_AZ_DC', 's', 9, value) self.add_field('C_AL_NC', 's', 9, value) self.add_field('C_AL_EC', 's', 9, value) self.add_field('C_AL_DC', 's', 9, value) class MENSRA_174(TREExtension): _tag_value = 'MENSRA' _data_type = MENSRA_174Type class MENSRA_185Type(TREElement): def __init__(self, value): super(MENSRA_185Type, self).__init__() self.add_field('ACFT_LOC', 's', 25, value) self.add_field('ACFT_ALT', 's', 6, value) self.add_field('CCRP_LOC', 's', 25, value) self.add_field('CCRP_ALT', 's', 6, value) self.add_field('OF_PC_R', 's', 7, value) self.add_field('OF_PC_A', 's', 7, value) self.add_field('COSGZ', 's', 7, value) self.add_field('RGCCRP', 's', 7, value) self.add_field('RLMAP', 's', 1, value) self.add_field('CCRP_ROW', 's', 5, value) self.add_field('CCRP_COL', 's', 5, value) self.add_field('C_R_NC', 's', 10, value) self.add_field('C_R_EC', 's', 10, value) self.add_field('C_R_DC', 's', 10, value) self.add_field('C_AZ_NC', 's', 9, value) self.add_field('C_AZ_EC', 's', 9, value) self.add_field('C_AZ_DC', 's', 9, value) self.add_field('C_AL_NC', 's', 9, value) self.add_field('C_AL_EC', 's', 9, value) self.add_field('C_AL_DC', 's', 9, value) self.add_field('TOTAL_TILES_COLS', 's', 3, value) self.add_field('TOTAL_TILES_ROWS', 's', 5, value) class MENSRA_185(TREExtension): _tag_value = 'MENSRA' _data_type = MENSRA_185Type class MENSRA(TREExtension): _tag_value = 'MENSRA' def __init__(self): raise ValueError( 'Not to be implemented directly. ' 'Use of one MENSRA_155, MENSRA_174, or MENSRA_185') @classmethod def from_bytes(cls, value, start): """ Parameters ---------- value : bytes start : int Returns ------- MENSRA_155|MENSRA_174|MENSRA_185 """ tag_value = value[start:start+6].decode('utf-8').strip() if tag_value != cls._tag_value: raise ValueError('tag value must be {}. Got {}'.format(cls._tag_value, tag_value)) lng = int(value[start+6:start+11]) if lng == 155: return MENSRA_155.from_bytes(value, start) elif lng == 174: return MENSRA_174.from_bytes(value, start) elif lng == 185: return MENSRA_185.from_bytes(value, start) else: raise ValueError('the data must be length 155, 174, or 185. Got {}'.format(lng))
4,846
34.903704
94
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/RSMECA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class MAP(TREElement): def __init__(self, value): super(MAP, self).__init__() self.add_field('MAP', 's', 21, value) class CORSEG(TREElement): def __init__(self, value): super(CORSEG, self).__init__() self.add_field('CORSEG', 's', 21, value) self.add_field('TAUSEG', 's', 21, value) class ERRCVG(TREElement): def __init__(self, value): super(ERRCVG, self).__init__() self.add_field('ERRCVG', 's', 21, value) class ERRCOVDATA(TREElement): def __init__(self, value): super(ERRCOVDATA, self).__init__() self.add_field('NUMOPG', 'd', 2, value) self.add_loop( 'ERRCVGs', int((self.NUMOPG+1)*self.NUMOPG/2), ERRCVG, value) self.add_field('TCDF', 'd', 1, value) self.add_field('NCSEG', 'd', 1, value) self.add_loop('CORSEGs', self.NCSEG, CORSEG, value) class UCORSEGR(TREElement): def __init__(self, value): super(UCORSEGR, self).__init__() self.add_field('UCORSR', 's', 21, value) self.add_field('UTAUSR', 's', 21, value) class UCORSEGC(TREElement): def __init__(self, value): super(UCORSEGC, self).__init__() self.add_field('UCORSC', 's', 21, value) self.add_field('UTAUSC', 's', 21, value) class RSMECAType(TREElement): def __init__(self, value): super(RSMECAType, self).__init__() self.add_field('IID', 's', 80, value) self.add_field('EDITION', 's', 40, value) self.add_field('TID', 's', 40, value) self.add_field('INCLIC', 's', 1, value) self.add_field('INCLUC', 's', 1, value) if self.INCLIC == 'Y': self.add_field('NPAR', 'd', 2, value) self.add_field('NPARO', 'd', 2, value) self.add_field('IGN', 'd', 2, value) self.add_field('CVDATE', 's', 8, value) self.add_field('XUOL', 's', 21, value) self.add_field('YUOL', 's', 21, value) self.add_field('ZUOL', 's', 21, value) self.add_field('XUXL', 's', 21, value) self.add_field('XUYL', 's', 21, value) self.add_field('XUZL', 's', 21, value) self.add_field('YUXL', 's', 21, value) self.add_field('YUYL', 's', 21, value) self.add_field('YUZL', 's', 21, value) self.add_field('ZUXL', 's', 21, value) self.add_field('ZUYL', 's', 21, value) self.add_field('ZUZL', 's', 21, value) self.add_field('IR0', 's', 2, value) self.add_field('IRX', 's', 2, value) self.add_field('IRY', 's', 2, value) self.add_field('IRZ', 's', 2, value) self.add_field('IRXX', 's', 2, value) self.add_field('IRXY', 's', 2, value) self.add_field('IRXZ', 's', 2, value) self.add_field('IRYY', 's', 2, value) self.add_field('IRYZ', 's', 2, value) self.add_field('IRZZ', 's', 2, value) self.add_field('IC0', 's', 2, value) self.add_field('ICX', 's', 2, value) self.add_field('ICY', 's', 2, value) self.add_field('ICZ', 's', 2, value) self.add_field('ICXX', 's', 2, value) self.add_field('ICXY', 's', 2, value) self.add_field('ICXZ', 's', 2, value) self.add_field('ICYY', 's', 2, value) self.add_field('ICYZ', 's', 2, value) self.add_field('ICZZ', 's', 2, value) self.add_field('GX0', 's', 2, value) self.add_field('GY0', 's', 2, value) self.add_field('GZ0', 's', 2, value) self.add_field('GXR', 's', 2, value) self.add_field('GYR', 's', 2, value) self.add_field('GZR', 's', 2, value) self.add_field('GS', 's', 2, value) self.add_field('GXX', 's', 2, value) self.add_field('GXY', 's', 2, value) self.add_field('GXZ', 's', 2, value) self.add_field('GYX', 's', 2, value) self.add_field('GYY', 's', 2, value) self.add_field('GYZ', 's', 2, value) self.add_field('GZX', 's', 2, value) self.add_field('GZY', 's', 2, value) self.add_field('GZZ', 's', 2, value) self.add_loop('ERRCOVDATAs', self.IGN, ERRCOVDATA, value) self.add_loop('MAPMAT', int(self.NPAR * self.NPARO), MAP, value) if self.INCLUC == 'Y': self.add_field('URR', 's', 21, value) self.add_field('URC', 's', 21, value) self.add_field('UCC', 's', 21, value) self.add_field('UNCSR', 'd', 1, value) self.add_loop('UCORSEGRs', self.UNCSR, UCORSEGR, value) self.add_field('UNCSC', 'd', 1, value) self.add_loop('UCORSEGCs', self.UNCSC, UCORSEGC, value) class RSMECA(TREExtension): _tag_value = 'RSMECA' _data_type = RSMECAType
5,024
37.653846
76
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/STDIDC.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class STDIDCType(TREElement): def __init__(self, value): super(STDIDCType, self).__init__() self.add_field('ACQUISITION_DATE', 's', 14, value) self.add_field('MISSION', 's', 14, value) self.add_field('PASS', 's', 2, value) self.add_field('OP_NUM', 's', 3, value) self.add_field('START_SEGMENT', 's', 2, value) self.add_field('REPRO_NUM', 's', 2, value) self.add_field('REPLAY_REGEN', 's', 3, value) self.add_field('BLANK_FILL', 's', 1, value) self.add_field('START_COLUMN', 's', 3, value) self.add_field('START_ROW', 's', 5, value) self.add_field('END_SEGMENT', 's', 2, value) self.add_field('END_COLUMN', 's', 3, value) self.add_field('END_ROW', 's', 5, value) self.add_field('COUNTRY', 's', 2, value) self.add_field('WAC', 's', 4, value) self.add_field('LOCATION', 's', 11, value) self.add_field('RESERV01', 's', 5, value) self.add_field('RESERV02', 's', 8, value) class STDIDC(TREExtension): _tag_value = 'STDIDC' _data_type = STDIDCType
1,232
35.264706
58
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/PIAPEB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PIAPEBType(TREElement): def __init__(self, value): super(PIAPEBType, self).__init__() self.add_field('LASTNME', 's', 28, value) self.add_field('FIRSTNME', 's', 28, value) self.add_field('MIDNME', 's', 28, value) self.add_field('DOB', 's', 8, value) self.add_field('ASSOCTRY', 's', 2, value) class PIAPEB(TREExtension): _tag_value = 'PIAPEB' _data_type = PIAPEBType
558
25.619048
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/PIATGB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PIATGBType(TREElement): def __init__(self, value): super(PIATGBType, self).__init__() self.add_field('TGTUTM', 's', 15, value) self.add_field('PIATGAID', 's', 15, value) self.add_field('PIACTRY', 's', 2, value) self.add_field('PIACAT', 's', 5, value) self.add_field('TGTGEO', 's', 15, value) self.add_field('DATUM', 's', 3, value) self.add_field('TGTNAME', 's', 38, value) self.add_field('PERCOVER', 's', 3, value) self.add_field('TGTLAT', 's', 10, value) self.add_field('TGTLON', 's', 11, value) class PIATGB(TREExtension): _tag_value = 'PIATGB' _data_type = PIATGBType
804
29.961538
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/__init__.py
__classification__ = "UNCLASSIFIED"
37
11.666667
35
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/RPC00B.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class LINE_NUM_COEFF(TREElement): def __init__(self, value): super(LINE_NUM_COEFF, self).__init__() self.add_field('LINE_NUM_COEFF', 's', 12, value) class LINE_DEN_COEFF(TREElement): def __init__(self, value): super(LINE_DEN_COEFF, self).__init__() self.add_field('LINE_DEN_COEFF', 's', 12, value) class SAMP_NUM_COEFF(TREElement): def __init__(self, value): super(SAMP_NUM_COEFF, self).__init__() self.add_field('SAMP_NUM_COEFF', 's', 12, value) class SAMP_DEN_COEFF(TREElement): def __init__(self, value): super(SAMP_DEN_COEFF, self).__init__() self.add_field('SAMP_DEN_COEFF', 's', 12, value) class RPC00BType(TREElement): def __init__(self, value): super(RPC00BType, self).__init__() self.add_field('SUCCESS', 's', 1, value) self.add_field('ERR_BIAS', 's', 7, value) self.add_field('ERR_RAND', 's', 7, value) self.add_field('LINE_OFF', 's', 6, value) self.add_field('SAMP_OFF', 's', 5, value) self.add_field('LAT_OFF', 's', 8, value) self.add_field('LONG_OFF', 's', 9, value) self.add_field('HEIGHT_OFF', 's', 5, value) self.add_field('LINE_SCALE', 's', 6, value) self.add_field('SAMP_SCALE', 's', 5, value) self.add_field('LAT_SCALE', 's', 8, value) self.add_field('LONG_SCALE', 's', 9, value) self.add_field('HEIGHT_SCALE', 's', 5, value) self.add_loop('LINE_NUM_COEFFs', 20, LINE_NUM_COEFF, value) self.add_loop('LINE_DEN_COEFFs', 20, LINE_DEN_COEFF, value) self.add_loop('SAMP_NUM_COEFFs', 20, SAMP_NUM_COEFF, value) self.add_loop('SAMP_DEN_COEFFs', 20, SAMP_DEN_COEFF, value) class RPC00B(TREExtension): _tag_value = 'RPC00B' _data_type = RPC00BType
1,930
32.877193
67
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/RPFHDR.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class RPFHDRType(TREElement): def __init__(self, value): super(RPFHDRType, self).__init__() self.add_field('ENDIAN', 'b', 1, value) self.add_field('HDSECL', 'b', 2, value) self.add_field('FILENM', 's', 12, value) self.add_field('NEWFLG', 'b', 1, value) self.add_field('STDNUM', 's', 15, value) self.add_field('STDDAT', 's', 8, value) self.add_field('CLASS', 's', 1, value) self.add_field('COUNTR', 's', 2, value) self.add_field('RELEAS', 's', 2, value) self.add_field('LOCSEC', 'b', 4, value) class RPFHDR(TREExtension): _tag_value = 'RPFHDR' _data_type = RPFHDRType
794
29.576923
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/SENSRB.py
__classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" import logging from ..tre_elements import TREExtension, TREElement logger = logging.getLogger(__name__) def get_ref_type_length(typ_val): typ_val = typ_val.lower() if typ_val in ['06a', '06c']: return 11 elif typ_val == '06b': return 12 elif typ_val in ['06d', '06e', '06f']: return 8 elif typ_val in [ '07b', '07d', '07h', '08a', '08b', '08c', '08d', '08e', '08f', '08g', '08h', '08i', '09a', '09b', '09c', '09d']: return 10 elif typ_val in ['07c', '07f', '07g', '10a', '10b', '10c']: return 9 else: logger.error( 'An unknown type value {} was found when deserializing a SENSRB TRE object.\n\t' 'Something may fail in this deserialization.') return None class POINT(TREElement): def __init__(self, value): super(POINT, self).__init__() self.add_field('P_ROW', 's', 8, value) self.add_field('P_COLUMN', 's', 8, value) self.add_field('P_LATITUDE', 's', 10, value) self.add_field('P_LONGITUDE', 's', 11, value) self.add_field('P_ELEVATION', 's', 6, value) self.add_field('P_RANGE', 's', 8, value) class POINT_SET(TREElement): def __init__(self, value): super(POINT_SET, self).__init__() self.add_field('POINT_SET_TYPE', 's', 25, value) self.add_field('POINT_COUNT', 'd', 3, value) self.add_loop('POINTs', self.POINT_COUNT, POINT, value) class TIME_STAMP(TREElement): def __init__(self, value, time_len): super(TIME_STAMP, self).__init__() self.add_field('TIME_STAMP_TIME', 's', 12, value) if time_len is not None: self.add_field('TIME_STAMP_VALUE', 's', time_len, value) class TIME_STAMPED_DATA(TREElement): def __init__(self, value): super(TIME_STAMPED_DATA, self).__init__() self.add_field('TIME_STAMP_TYPE', 's', 3, value) self.add_field('TIME_STAMP_COUNT', 'd', 4, value) self.add_loop( 'TIME_STAMPs', self.TIME_STAMP_COUNT, TIME_STAMP, value, get_ref_type_length(self.TIME_STAMP_TYPE)) class PIXEL_REFERENCE(TREElement): def __init__(self, value, pixel_ref_len): super(PIXEL_REFERENCE, self).__init__() self.add_field('PIXEL_REFERENCE_ROW', 's', 8, value) self.add_field('PIXEL_REFERENCE_COLUMN', 's', 8, value) if pixel_ref_len is not None: self.add_field('PIXEL_REFERENCE_VALUE', 's', pixel_ref_len, value) class PIXEL_REFERENCED_DATA(TREElement): def __init__(self, value): super(PIXEL_REFERENCED_DATA, self).__init__() self.add_field('PIXEL_REFERENCE_TYPE', 's', 3, value) self.add_field('PIXEL_REFERENCE_COUNT', 'd', 4, value) self.add_loop( 'PIXEL_REFERENCEs', self.PIXEL_REFERENCE_COUNT, PIXEL_REFERENCE, value, get_ref_type_length(self.PIXEL_REFERENCE_TYPE)) class UNCERTAINTY(TREElement): def __init__(self, value): super(UNCERTAINTY, self).__init__() self.add_field('UNCERTAINTY_FIRST_TYPE', 's', 11, value) self.add_field('UNCERTAINTY_SECOND_TYPE', 's', 11, value) self.add_field('UNCERTAINTY_VALUE', 's', 10, value) class PARAMETER(TREElement): def __init__(self, value): super(PARAMETER, self).__init__() self.add_field('PARAMETER_VALUE', 'b', self.PARAMETER_SIZE, value) class ADDITIONAL_PARAMETER(TREElement): def __init__(self, value): super(ADDITIONAL_PARAMETER, self).__init__() self.add_field('PARAMETER_NAME', 's', 25, value) self.add_field('PARAMETER_SIZE', 's', 3, value) self.add_field('PARAMETER_COUNT', 'd', 4, value) self.add_loop('PARAMETERs', self.PARAMETER_COUNT, PARAMETER, value) class SENSRBType(TREElement): def __init__(self, value): super(SENSRBType, self).__init__() self.add_field('GENERAL_DATA', 's', 1, value) if self.GENERAL_DATA == 'Y': self.add_field('SENSOR', 's', 25, value) self.add_field('SENSOR_URI', 's', 32, value) self.add_field('PLATFORM', 's', 25, value) self.add_field('PLATFORM_URI', 's', 32, value) self.add_field('OPERATION_DOMAIN', 's', 10, value) self.add_field('CONTENT_LEVEL', 's', 1, value) self.add_field('GEODETIC_SYSTEM', 's', 5, value) self.add_field('GEODETIC_TYPE', 's', 1, value) self.add_field('ELEVATION_DATUM', 's', 3, value) self.add_field('LENGTH_UNIT', 's', 2, value) self.add_field('ANGULAR_UNIT', 's', 3, value) self.add_field('START_DATE', 's', 8, value) self.add_field('START_TIME', 's', 14, value) self.add_field('END_DATE', 's', 8, value) self.add_field('END_TIME', 's', 14, value) self.add_field('GENERATION_COUNT', 's', 2, value) self.add_field('GENERATION_DATE', 's', 8, value) self.add_field('GENERATION_TIME', 's', 10, value) self.add_field('SENSOR_ARRAY_DATA', 's', 1, value) if self.SENSOR_ARRAY_DATA == 'Y': self.add_field('DETECTION', 's', 20, value) self.add_field('ROW_DETECTORS', 's', 8, value) self.add_field('COLUMN_DETECTORS', 's', 8, value) self.add_field('ROW_METRIC', 's', 8, value) self.add_field('COLUMN_METRIC', 's', 8, value) self.add_field('FOCAL_LENGTH', 's', 8, value) self.add_field('ROW_FOV', 's', 8, value) self.add_field('COLUMN_FOV', 's', 8, value) self.add_field('CALIBRATED', 's', 1, value) self.add_field('SENSOR_CALIBRATION_DATA', 's', 1, value) if self.SENSOR_CALIBRATION_DATA == 'Y': self.add_field('CALIBRATION_UNIT', 's', 2, value) self.add_field('PRINCIPAL_POINT_OFFSET_X', 's', 9, value) self.add_field('PRINCIPAL_POINT_OFFSET_Y', 's', 9, value) self.add_field('RADIAL_DISTORT_1', 's', 12, value) self.add_field('RADIAL_DISTORT_2', 's', 12, value) self.add_field('RADIAL_DISTORT_3', 's', 12, value) self.add_field('RADIAL_DISTORT_LIMIT', 's', 9, value) self.add_field('DECENT_DISTORT_1', 's', 12, value) self.add_field('DECENT_DISTORT_2', 's', 12, value) self.add_field('AFFINITY_DISTORT_1', 's', 12, value) self.add_field('AFFINITY_DISTORT_2', 's', 12, value) self.add_field('CALIBRATION_DATE', 's', 8, value) self.add_field('IMAGE_FORMATION_DATA', 's', 1, value) if self.IMAGE_FORMATION_DATA == 'Y': self.add_field('METHOD', 's', 15, value) self.add_field('MODE', 's', 3, value) self.add_field('ROW_COUNT', 's', 8, value) self.add_field('COLUMN_COUNT', 's', 8, value) self.add_field('ROW_SET', 's', 8, value) self.add_field('COLUMN_SET', 's', 8, value) self.add_field('ROW_RATE', 's', 10, value) self.add_field('COLUMN_RATE', 's', 10, value) self.add_field('FIRST_PIXEL_ROW', 's', 8, value) self.add_field('FIRST_PIXEL_COLUMN', 's', 8, value) self.add_field('TRANSFORM_PARAMS', 'd', 1, value) for i in range(self.TRANSFORM_PARAMS): self.add_field('TRANSFORM_PARAM_{}'.format(i+1), 's', 12, value) self.add_field('REFERENCE_TIME', 's', 12, value) self.add_field('REFERENCE_ROW', 's', 8, value) self.add_field('REFERENCE_COLUMN', 's', 8, value) self.add_field('LATITUDE_OR_X', 's', 11, value) self.add_field('LONGITUDE_OR_Y', 's', 12, value) self.add_field('ALTITUDE_OR_Z', 's', 11, value) self.add_field('SENSOR_X_OFFSET', 's', 8, value) self.add_field('SENSOR_Y_OFFSET', 's', 8, value) self.add_field('SENSOR_Z_OFFSET', 's', 8, value) self.add_field('ATTITUDE_EULER_ANGLES', 's', 1, value) if self.ATTITUDE_EULER_ANGLES == 'Y': self.add_field('SENSOR_ANGLE_MODEL', 's', 1, value) self.add_field('SENSOR_ANGLE_1', 's', 10, value) self.add_field('SENSOR_ANGLE_2', 's', 9, value) self.add_field('SENSOR_ANGLE_3', 's', 10, value) self.add_field('PLATFORM_RELATIVE', 's', 1, value) self.add_field('PLATFORM_HEADING', 's', 9, value) self.add_field('PLATFORM_PITCH', 's', 9, value) self.add_field('PLATFORM_ROLL', 's', 10, value) self.add_field('ATTITUDE_UNIT_VECTORS', 's', 1, value) if self.ATTITUDE_UNIT_VECTORS == 'Y': self.add_field('ICX_NORTH_OR_X', 's', 10, value) self.add_field('ICX_EAST_OR_Y', 's', 10, value) self.add_field('ICX_DOWN_OR_Z', 's', 10, value) self.add_field('ICY_NORTH_OR_X', 's', 10, value) self.add_field('ICY_EAST_OR_Y', 's', 10, value) self.add_field('ICY_DOWN_OR_Z', 's', 10, value) self.add_field('ICZ_NORTH_OR_X', 's', 10, value) self.add_field('ICZ_EAST_OR_Y', 's', 10, value) self.add_field('ICZ_DOWN_OR_Z', 's', 10, value) self.add_field('ATTITUDE_QUATERNION', 's', 1, value) if self.ATTITUDE_QUATERNION == 'Y': self.add_field('ATTITUDE_Q1', 's', 10, value) self.add_field('ATTITUDE_Q2', 's', 10, value) self.add_field('ATTITUDE_Q3', 's', 10, value) self.add_field('ATTITUDE_Q4', 's', 10, value) self.add_field('SENSOR_VELOCITY_DATA', 's', 1, value) if self.SENSOR_VELOCITY_DATA == 'Y': self.add_field('VELOCITY_NORTH_OR_X', 's', 9, value) self.add_field('VELOCITY_EAST_OR_Y', 's', 9, value) self.add_field('VELOCITY_DOWN_OR_Z', 's', 9, value) self.add_field('POINT_SET_DATA', 'd', 2, value) self.add_loop('POINT_SETs', self.POINT_SET_DATA, POINT_SET, value) self.add_field('TIME_STAMPED_DATA_SETS', 'd', 2, value) self.add_loop('TIME_STAMPED_DATAs', self.TIME_STAMPED_DATA_SETS, TIME_STAMPED_DATA, value) self.add_field('PIXEL_REFERENCED_DATA_SETS', 'd', 2, value) self.add_loop('PIXEL_REFERENCED_DATAs', self.PIXEL_REFERENCED_DATA_SETS, PIXEL_REFERENCED_DATA, value) self.add_field('UNCERTAINTY_DATA', 'd', 3, value) self.add_loop('UNCERTAINTYs', self.UNCERTAINTY_DATA, UNCERTAINTY, value) self.add_field('ADDITIONAL_PARAMETER_DATA', 'd', 3, value) self.add_loop('ADDITIONAL_PARAMETERs', self.ADDITIONAL_PARAMETER_DATA, ADDITIONAL_PARAMETER, value) class SENSRB(TREExtension): _tag_value = 'SENSRB' _data_type = SENSRBType
10,741
42.844898
110
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/CSEPHA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class EPHEM(TREElement): def __init__(self, value): super(EPHEM, self).__init__() self.add_field('EPHEM_X', 's', 12, value) self.add_field('EPHEM_Y', 's', 12, value) self.add_field('EPHEM_Z', 's', 12, value) class CSEPHAType(TREElement): def __init__(self, value): super(CSEPHAType, self).__init__() self.add_field('EPHEM_FLAG', 's', 12, value) self.add_field('DT_EPHEM', 's', 5, value) self.add_field('DATE_EPHEM', 's', 8, value) self.add_field('T0_EPHEM', 's', 13, value) self.add_field('NUM_EPHEM', 'd', 3, value) self.add_loop('EPHEMs', self.NUM_EPHEM, EPHEM, value) class CSEPHA(TREExtension): _tag_value = 'CSEPHA' _data_type = CSEPHAType
878
28.3
61
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/IMGDTA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class VER(TREElement): def __init__(self, value): super(VER, self).__init__() self.add_field('VER_NAME', 's', 15, value) self.add_field('VERNUM', 's', 10, value) class IMGDTAType(TREElement): def __init__(self, value): super(IMGDTAType, self).__init__() self.add_field('VERNUM', 's', 4, value) self.add_field('FILENAME', 's', 32, value) self.add_field('PARENT_FNAME', 's', 32, value) self.add_field('CHECKSUM', 's', 32, value) self.add_field('ISIZE', 's', 10, value) self.add_field('STATUS', 's', 1, value) self.add_field('CDATE', 's', 8, value) self.add_field('CTIME', 's', 10, value) self.add_field('PDATE', 's', 8, value) self.add_field('SENTYPE', 's', 1, value) self.add_field('DATA_PLANE', 's', 1, value) self.add_field('DATA_TYPE', 's', 4, value) self.add_field('NUM_ROWS', 's', 6, value) self.add_field('NUM_COLS', 's', 6, value) self.add_field('SEN_POS', 's', 1, value) self.add_field('SEN_CAL_FAC', 's', 15, value) self.add_field('IMGQUAL', 's', 50, value) self.add_field('NUM_VER', 'd', 2, value) self.add_loop('VERs', self.NUM_VER, VER, value) if self.SENTYPE == 'R': self.add_field('SEN_LOOK', 's', 1, value) self.add_field('CR_RES', 's', 7, value) self.add_field('RANGE_RES', 's', 7, value) self.add_field('CR_PIXELSP', 's', 7, value) self.add_field('RANGE_PIXELSP', 's', 7, value) self.add_field('CR_WEIGHT', 's', 40, value) self.add_field('RANGE_WEIGHT', 's', 40, value) self.add_field('R_OVR_SAMP', 's', 6, value) self.add_field('CR_OVR_SAMP', 's', 6, value) self.add_field('D_DEPRES', 's', 6, value) self.add_field('D_GP_SQ', 's', 7, value) self.add_field('D_SP_SQ', 's', 7, value) self.add_field('D_RANGE', 's', 7, value) self.add_field('D_AP_LL', 's', 21, value) self.add_field('D_AP_ELV', 's', 7, value) self.add_field('M_DEPRES', 's', 6, value) self.add_field('M_GP_SQ', 's', 7, value) self.add_field('M_SP_SQ', 's', 7, value) self.add_field('M_RANGE', 's', 7, value) self.add_field('M_AP_LL', 's', 21, value) self.add_field('M_AP_ELV', 's', 7, value) elif self.SENTYPE in ['E', 'I']: self.add_field('GRNDSAMPDIS', 's', 6, value) self.add_field('SWATHSIZE', 's', 6, value) self.add_field('D_RANGE', 's', 7, value) self.add_field('D_AZ_LOOK', 's', 6, value) self.add_field('D_EL_LOOK', 's', 5, value) self.add_field('M_RANGE', 's', 7, value) self.add_field('M_AZ_LOOK', 's', 6, value) self.add_field('M_EL_LOOK', 's', 5, value) class IMGDTA(TREExtension): _tag_value = 'IMGDTA' _data_type = IMGDTAType
3,115
41.684932
58
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/STREOB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class STREOBType(TREElement): def __init__(self, value): super(STREOBType, self).__init__() self.add_field('ST_ID', 's', 60, value) self.add_field('N_MATES', 's', 1, value) self.add_field('MATE_INSTANCE', 's', 1, value) self.add_field('B_CONV', 's', 5, value) self.add_field('E_CONV', 's', 5, value) self.add_field('B_ASYM', 's', 5, value) self.add_field('E_ASYM', 's', 5, value) self.add_field('B_BIE', 's', 6, value) self.add_field('E_BIE', 's', 6, value) class STREOB(TREExtension): _tag_value = 'STREOB' _data_type = STREOBType
751
29.08
54
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/PIATGA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PIATGAType(TREElement): def __init__(self, value): super(PIATGAType, self).__init__() self.add_field('TGTUTM', 's', 15, value) self.add_field('PIATGAID', 's', 15, value) self.add_field('PIACTRY', 's', 2, value) self.add_field('PIACAT', 's', 5, value) self.add_field('TGTGEO', 's', 15, value) self.add_field('DATUM', 's', 3, value) self.add_field('TGTNAME', 's', 38, value) self.add_field('PERCOVER', 's', 3, value) class PIATGA(TREExtension): _tag_value = 'PIATGA' _data_type = PIATGAType
706
28.458333
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/AIMIDA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class AIMIDA_69Type(TREElement): def __init__(self, value): super(AIMIDA_69Type, self).__init__() self.add_field('MISSION_DATE', 's', 7, value) self.add_field('MISSION_NO', 's', 4, value) self.add_field('FLIGHT_NO', 's', 2, value) self.add_field('OP_NUM', 's', 3, value) self.add_field('START_SEGMENT', 's', 2, value) self.add_field('REPRO_NUM', 's', 2, value) self.add_field('REPLAY', 's', 3, value) self.add_field('RESVD001', 's', 1, value) self.add_field('START_COLUMN', 's', 2, value) self.add_field('START_ROW', 's', 5, value) self.add_field('END_SEGMENT', 's', 2, value) self.add_field('END_COLUMN', 's', 2, value) self.add_field('END_ROW', 's', 5, value) self.add_field('COUNTRY', 's', 2, value) self.add_field('RESVD002', 's', 4, value) self.add_field('LOCATION', 's', 11, value) self.add_field('TIME', 's', 5, value) self.add_field('CREATION_DATE', 's', 7, value) class AIMIDA_69(TREExtension): _tag_value = 'AIMIDA' _data_type = AIMIDA_69Type class AIMIDA_73Type(TREElement): def __init__(self, value): super(AIMIDA_73Type, self).__init__() self.add_field('MISSION_DATE', 's', 8, value) self.add_field('MISSION_NO', 's', 4, value) self.add_field('FLIGHT_NO', 's', 2, value) self.add_field('OP_NUM', 's', 3, value) self.add_field('RESVD001', 's', 2, value) self.add_field('REPRO_NUM', 's', 2, value) self.add_field('REPLAY', 's', 3, value) self.add_field('RESVD002', 's', 1, value) self.add_field('START_COLUMN', 's', 3, value) self.add_field('START_ROW', 's', 5, value) self.add_field('RESVD003', 's', 2, value) self.add_field('END_COLUMN', 's', 3, value) self.add_field('END_ROW', 's', 5, value) self.add_field('COUNTRY', 's', 2, value) self.add_field('RESVD004', 's', 4, value) self.add_field('LOCATION', 's', 11, value) self.add_field('TIME', 's', 5, value) self.add_field('CREATION_DATE', 's', 8, value) class AIMIDA_73(TREExtension): _tag_value = 'AIMIDA' _data_type = AIMIDA_73Type class AIMIDA_89Type(TREElement): def __init__(self, value): super(AIMIDA_89Type, self).__init__() self.add_field('MISSION_DATE_TIME', 's', 14, value) self.add_field('MISSION_NO', 's', 4, value) self.add_field('MISSION_ID', 's', 10, value) self.add_field('FLIGHT_NO', 's', 2, value) self.add_field('OP_NUM', 's', 3, value) self.add_field('CURRENT_SEGMENT', 's', 2, value) self.add_field('REPRO_NUM', 's', 2, value) self.add_field('REPLAY', 's', 3, value) self.add_field('RESVD001', 's', 1, value) self.add_field('START_COLUMN', 's', 3, value) self.add_field('START_ROW', 's', 5, value) self.add_field('END_SEGMENT', 's', 2, value) self.add_field('END_COLUMN', 's', 3, value) self.add_field('END_ROW', 's', 5, value) self.add_field('COUNTRY', 's', 2, value) self.add_field('RESVD002', 's', 4, value) self.add_field('LOCATION', 's', 11, value) self.add_field('RESVD003', 's', 13, value) class AIMIDA_89(TREExtension): _tag_value = 'AIMIDA' _data_type = AIMIDA_89Type class AIMIDA(TREExtension): _tag_value = 'AIMIDA' def __init__(self): raise ValueError( 'Not to be implemented directly. ' 'Use of one AIMIDA_69, AIMIDA_73, or AIMIDA_89') @classmethod def from_bytes(cls, value, start): """ Parameters ---------- value : bytes start : int Returns ------- AIMIDA_69|AIMIDA_73|AIMIDA_89 """ tag_value = value[start:start+6].decode('utf-8').strip() if tag_value != cls._tag_value: raise ValueError('tag value must be {}. Got {}'.format(cls._tag_value, tag_value)) lng = int(value[start+6:start+11]) if lng == 69: return AIMIDA_69.from_bytes(value, start) elif lng == 73: return AIMIDA_73.from_bytes(value, start) elif lng == 89: return AIMIDA_89.from_bytes(value, start) else: raise ValueError('the data must be length 69, 73, or 89. Got {}'.format(lng))
4,518
34.582677
94
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/RPC00A.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class LINE_NUM_COEFF(TREElement): def __init__(self, value): super(LINE_NUM_COEFF, self).__init__() self.add_field('LINE_NUM_COEFF', 's', 12, value) class LINE_DEN_COEFF(TREElement): def __init__(self, value): super(LINE_DEN_COEFF, self).__init__() self.add_field('LINE_DEN_COEFF', 's', 12, value) class SAMP_NUM_COEFF(TREElement): def __init__(self, value): super(SAMP_NUM_COEFF, self).__init__() self.add_field('SAMP_NUM_COEFF', 's', 12, value) class SAMP_DEN_COEFF(TREElement): def __init__(self, value): super(SAMP_DEN_COEFF, self).__init__() self.add_field('SAMP_DEN_COEFF', 's', 12, value) class RPC00AType(TREElement): def __init__(self, value): super(RPC00AType, self).__init__() self.add_field('SUCCESS', 's', 1, value) self.add_field('ERR_BIAS', 's', 7, value) self.add_field('ERR_RAND', 's', 7, value) self.add_field('LINE_OFF', 's', 6, value) self.add_field('SAMP_OFF', 's', 5, value) self.add_field('LAT_OFF', 's', 8, value) self.add_field('LONG_OFF', 's', 9, value) self.add_field('HEIGHT_OFF', 's', 5, value) self.add_field('LINE_SCALE', 's', 6, value) self.add_field('SAMP_SCALE', 's', 5, value) self.add_field('LAT_SCALE', 's', 8, value) self.add_field('LONG_SCALE', 's', 9, value) self.add_field('HEIGHT_SCALE', 's', 5, value) self.add_loop('LINE_NUM_COEFFs', 20, LINE_NUM_COEFF, value) self.add_loop('LINE_DEN_COEFFs', 20, LINE_DEN_COEFF, value) self.add_loop('SAMP_NUM_COEFFs', 20, SAMP_NUM_COEFF, value) self.add_loop('SAMP_DEN_COEFFs', 20, SAMP_DEN_COEFF, value) class RPC00A(TREExtension): _tag_value = 'RPC00A' _data_type = RPC00AType
1,930
32.877193
67
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/EXPLTA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class EXPLTA_87Type(TREElement): def __init__(self, value): super(EXPLTA_87Type, self).__init__() self.add_field('ANGLE_TO_NORTH', 's', 3, value) self.add_field('SQUINT_ANGLE', 's', 3, value) self.add_field('MODE', 's', 3, value) self.add_field('RESVD001', 's', 16, value) self.add_field('GRAZE_ANG', 's', 2, value) self.add_field('SLOPE_ANG', 's', 2, value) self.add_field('POLAR', 's', 2, value) self.add_field('NSAMP', 's', 5, value) self.add_field('RESVD002', 's', 1, value) self.add_field('SEQ_NUM', 's', 1, value) self.add_field('PRIME_ID', 's', 12, value) self.add_field('PRIME_BE', 's', 15, value) self.add_field('RESVD003', 's', 1, value) self.add_field('N_SEC', 's', 2, value) self.add_field('IPR', 's', 2, value) self.add_field('RESVD004', 's', 2, value) self.add_field('RESVD005', 's', 2, value) self.add_field('RESVD006', 's', 5, value) self.add_field('RESVD007', 's', 8, value) class EXPLTA_87(TREExtension): _tag_value = 'EXPLTA' _data_type = EXPLTA_87Type class EXPLTA_101Type(TREElement): def __init__(self, value): super(EXPLTA_101Type, self).__init__() self.add_field('ANGLE_TO_NORTH', 's', 7, value) self.add_field('SQUINT_ANGLE', 's', 7, value) self.add_field('MODE', 's', 3, value) self.add_field('RESVD001', 's', 16, value) self.add_field('GRAZE_ANG', 's', 5, value) self.add_field('SLOPE_ANG', 's', 5, value) self.add_field('POLAR', 's', 2, value) self.add_field('NSAMP', 's', 5, value) self.add_field('RESVD002', 's', 1, value) self.add_field('SEQ_NUM', 's', 1, value) self.add_field('PRIME_ID', 's', 12, value) self.add_field('PRIME_BE', 's', 15, value) self.add_field('RESVD003', 's', 1, value) self.add_field('N_SEC', 's', 2, value) self.add_field('IPR', 's', 2, value) class EXPLTA_101(TREExtension): _tag_value = 'EXPLTA' _data_type = EXPLTA_101Type class EXPLTA(TREExtension): _tag_value = 'EXPLTA' def __init__(self): raise ValueError( 'Not to be implemented directly. ' 'Use of one EXPLTA_87 or EXPLTA_101') @classmethod def from_bytes(cls, value, start): """ Parameters ---------- value : bytes start : int Returns ------- EXPLTA_87|EXPLTA_101 """ tag_value = value[start:start+6].decode('utf-8').strip() if tag_value != cls._tag_value: raise ValueError('tag value must be {}. Got {}'.format(cls._tag_value, tag_value)) lng = int(value[start+6:start+11]) if lng == 87: return EXPLTA_87.from_bytes(value, start) elif lng == 101: return EXPLTA_101.from_bytes(value, start) else: raise ValueError('the data must be length 87 or 101. Got {}'.format(lng))
3,153
32.2
94
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/RPFIMG.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class SECREC(TREElement): def __init__(self, value): super(SECREC, self).__init__() self.add_field('LOCID', 'b', 1, value) self.add_field('SECLEN', 'b', 1, value) self.add_field('PHYSIDX', 'b', 1, value) class RPFIMGType(TREElement): def __init__(self, value): super(RPFIMGType, self).__init__() self.add_field('LOCLEN', 'b', 1, value) self.add_field('CLTOFF', 'b', 1, value) self.add_field('SECRECS', 'b', 1, value) self.add_field('RECLEN', 'b', 1, value) self.add_field('AGGLEN', 'b', 1, value) self.add_loop('SECRECList', int(self.SECRECS), SECREC, value) self.add_field('UNKNOWN', 'b', len(value) - self._bytes_length, value) class RPFIMG(TREExtension): _tag_value = 'RPFIMG' _data_type = RPFIMGType
945
29.516129
78
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/EXPLTB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class EXPLTBType(TREElement): def __init__(self, value): super(EXPLTBType, self).__init__() self.add_field('ANGLE_TO_NORTH', 's', 7, value) self.add_field('ANGLE_TO_NORTH_ACCY', 's', 6, value) self.add_field('SQUINT_ANGLE', 's', 7, value) self.add_field('SQUINT_ANGLE_ACCY', 's', 6, value) self.add_field('MODE', 's', 3, value) self.add_field('RESVD001', 's', 16, value) self.add_field('GRAZE_ANG', 's', 5, value) self.add_field('GRAZE_ANG_ACCY', 's', 5, value) self.add_field('SLOPE_ANG', 's', 5, value) self.add_field('POLAR', 's', 2, value) self.add_field('NSAMP', 's', 5, value) self.add_field('RESVD002', 's', 1, value) self.add_field('SEQ_NUM', 's', 1, value) self.add_field('PRIME_ID', 's', 12, value) self.add_field('PRIME_BE', 's', 15, value) self.add_field('RESVD003', 's', 1, value) self.add_field('N_SEC', 's', 2, value) self.add_field('IPR', 's', 2, value) class EXPLTB(TREExtension): _tag_value = 'EXPLTB' _data_type = EXPLTBType
1,235
35.352941
60
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/CSSFAA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class BAND(TREElement): def __init__(self, value): super(BAND, self).__init__() self.add_field('BAND_TYPE', 's', 1, value) self.add_field('BAND_ID', 's', 6, value) self.add_field('FOC_LENGTH', 's', 11, value) self.add_field('NUM_DAP', 's', 8, value) self.add_field('NUM_FIR', 's', 8, value) self.add_field('DELTA', 's', 7, value) self.add_field('OPPOFF_X', 's', 7, value) self.add_field('OPPOFF_Y', 's', 7, value) self.add_field('OPPOFF_Z', 's', 7, value) self.add_field('START_X', 's', 11, value) self.add_field('START_Y', 's', 11, value) self.add_field('FINISH_X', 's', 11, value) self.add_field('FINISH_Y', 's', 11, value) class CSSFAAType(TREElement): def __init__(self, value): super(CSSFAAType, self).__init__() self.add_field('NUM_BANDS', 'd', 1, value) self.add_loop('BANDs', self.NUM_BANDS, BAND, value) class CSSFAA(TREExtension): _tag_value = 'CSSFAA' _data_type = CSSFAAType
1,168
31.472222
59
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/CSSHPA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class CSSHPAType(TREElement): def __init__(self, value): super(CSSHPAType, self).__init__() self.add_field('SHAPE_USE', 's', 25, value) self.add_field('SHAPE_CLASS', 's', 10, value) if self.SHAPE_USE.strip() == 'CLOUD_SHAPES': self.add_field('CC_SOURCE', 's', 18, value) self.add_field('SHAPE1_NAME', 's', 3, value) self.add_field('SHAPE1_START', 's', 6, value) self.add_field('SHAPE2_NAME', 's', 3, value) self.add_field('SHAPE2_START', 's', 6, value) self.add_field('SHAPE3_NAME', 's', 3, value) self.add_field('SHAPE3_START', 's', 6, value) class CSSHPA(TREExtension): _tag_value = 'CSSHPA' _data_type = CSSHPAType
849
31.692308
55
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/OBJCTA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class OBJ(TREElement): def __init__(self, value): super(OBJ, self).__init__() self.add_field('OBJ_TY', 's', 20, value) self.add_field('OBJ_NM', 's', 15, value) self.add_field('OBJ_POS', 's', 2, value) self.add_field('OBJ_SN', 's', 10, value) self.add_field('OBJ_LL', 's', 21, value) self.add_field('OBJ_ELEV', 's', 8, value) self.add_field('OBJ_ROW', 's', 8, value) self.add_field('OBJ_COL', 's', 8, value) self.add_field('OBJ_PROW', 's', 8, value) self.add_field('OBJ_PCOL', 's', 8, value) self.add_field('OBJ_ATTR', 's', 20, value) self.add_field('OBJ_SEN', 's', 2, value) if self.OBJ_SEN == 'R': self.add_field('OBJ_AZ_3DB_WIDTH', 's', 7, value) self.add_field('OBJ_RNG_3DB_WIDTH', 's', 7, value) self.add_field('OBJ_AZ_18DB_WIDTH', 's', 7, value) self.add_field('OBJ_RNG_18DB_WIDTH', 's', 7, value) self.add_field('OBJ_AZ_3_18DB_RATIO', 's', 8, value) self.add_field('OBJ_RNG_3_18DB_RATIO', 's', 8, value) self.add_field('OBJ_AZ_PK_SL_RATIO', 's', 8, value) self.add_field('OBJ_RNG_PK_SL_RATIO', 's', 8, value) self.add_field('OBJ_AZ_INT_SL_RATIO', 's', 8, value) self.add_field('OBJ_RNGINT_SL_RATIO', 's', 8, value) elif self.OBJ_SEN in ['EO', 'IR']: self.add_field('OBJ_CAL_TEMP', 's', 6, value) class OBJCTAType(TREElement): def __init__(self, value): super(OBJCTAType, self).__init__() self.add_field('VERNUM', 's', 4, value) self.add_field('NUM_OBJ', 'd', 3, value) self.add_field('OBJ_REF', 's', 10, value) self.add_field('NUM_SCENE_OBJ', 'd', 3, value) self.add_loop('OBJs', self.NUM_OBJ, OBJ, value) class OBJCTA(TREExtension): _tag_value = 'OBJCTA' _data_type = OBJCTAType
2,031
38.843137
65
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/MAPLOB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class MAPLOBType(TREElement): def __init__(self, value): super(MAPLOBType, self).__init__() self.add_field('UNILOA', 's', 3, value) self.add_field('LOD', 's', 5, value) self.add_field('LAD', 's', 5, value) self.add_field('LSO', 's', 15, value) self.add_field('PSO', 's', 15, value) class MAPLOB(TREExtension): _tag_value = 'MAPLOB' _data_type = MAPLOBType
543
24.904762
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/RSMGIA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class RSMGIAType(TREElement): def __init__(self, value): super(RSMGIAType, self).__init__() self.add_field('IID', 's', 80, value) self.add_field('EDITION', 's', 40, value) self.add_field('GR0', 's', 21, value) self.add_field('GRX', 's', 21, value) self.add_field('GRY', 's', 21, value) self.add_field('GRZ', 's', 21, value) self.add_field('GRXX', 's', 21, value) self.add_field('GRXY', 's', 21, value) self.add_field('GRXZ', 's', 21, value) self.add_field('GRYY', 's', 21, value) self.add_field('GRYZ', 's', 21, value) self.add_field('GRZZ', 's', 21, value) self.add_field('GC0', 's', 21, value) self.add_field('GCX', 's', 21, value) self.add_field('GCY', 's', 21, value) self.add_field('GCZ', 's', 21, value) self.add_field('GCXX', 's', 21, value) self.add_field('GCXY', 's', 21, value) self.add_field('GCXZ', 's', 21, value) self.add_field('GCYY', 's', 21, value) self.add_field('GCYZ', 's', 21, value) self.add_field('GCZZ', 's', 21, value) self.add_field('GRNIS', 's', 3, value) self.add_field('GCNIS', 's', 3, value) self.add_field('GTNIS', 's', 3, value) self.add_field('GRSSIZ', 's', 21, value) self.add_field('GCSSIZ', 's', 21, value) class RSMGIA(TREExtension): _tag_value = 'RSMGIA' _data_type = RSMGIAType
1,580
35.767442
51
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/RSMAPA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PAR(TREElement): def __init__(self, value): super(PAR, self).__init__() self.add_field('PARVAL', 's', 21, value) class RSMAPAType(TREElement): def __init__(self, value): super(RSMAPAType, self).__init__() self.add_field('IID', 's', 80, value) self.add_field('EDITION', 's', 40, value) self.add_field('TID', 's', 40, value) self.add_field('NPAR', 'd', 2, value) self.add_field('XUOL', 's', 21, value) self.add_field('YUOL', 's', 21, value) self.add_field('ZUOL', 's', 21, value) self.add_field('XUXL', 's', 21, value) self.add_field('XUYL', 's', 21, value) self.add_field('XUZL', 's', 21, value) self.add_field('YUXL', 's', 21, value) self.add_field('YUYL', 's', 21, value) self.add_field('YUZL', 's', 21, value) self.add_field('ZUXL', 's', 21, value) self.add_field('ZUYL', 's', 21, value) self.add_field('ZUZL', 's', 21, value) self.add_field('IR0', 's', 2, value) self.add_field('IRX', 's', 2, value) self.add_field('IRY', 's', 2, value) self.add_field('IRZ', 's', 2, value) self.add_field('IRXX', 's', 2, value) self.add_field('IRXY', 's', 2, value) self.add_field('IRXZ', 's', 2, value) self.add_field('IRYY', 's', 2, value) self.add_field('IRYZ', 's', 2, value) self.add_field('IRZZ', 's', 2, value) self.add_field('IC0', 's', 2, value) self.add_field('ICX', 's', 2, value) self.add_field('ICY', 's', 2, value) self.add_field('ICZ', 's', 2, value) self.add_field('ICXX', 's', 2, value) self.add_field('ICXY', 's', 2, value) self.add_field('ICXZ', 's', 2, value) self.add_field('ICYY', 's', 2, value) self.add_field('ICYZ', 's', 2, value) self.add_field('ICZZ', 's', 2, value) self.add_field('GX0', 's', 2, value) self.add_field('GY0', 's', 2, value) self.add_field('GZ0', 's', 2, value) self.add_field('GXR', 's', 2, value) self.add_field('GYR', 's', 2, value) self.add_field('GZR', 's', 2, value) self.add_field('GS', 's', 2, value) self.add_field('GXX', 's', 2, value) self.add_field('GXY', 's', 2, value) self.add_field('GXZ', 's', 2, value) self.add_field('GYX', 's', 2, value) self.add_field('GYY', 's', 2, value) self.add_field('GYZ', 's', 2, value) self.add_field('GZX', 's', 2, value) self.add_field('GZY', 's', 2, value) self.add_field('GZZ', 's', 2, value) self.add_loop('PARs', self.NPAR, PAR, value) class RSMAPA(TREExtension): _tag_value = 'RSMAPA' _data_type = RSMAPAType
2,890
37.546667
52
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/BLOCKA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class BLOCKAType(TREElement): def __init__(self, value): super(BLOCKAType, self).__init__() self.add_field('BLOCK_INSTANCE', 's', 2, value) self.add_field('N_GRAY', 's', 5, value) self.add_field('L_LINES', 's', 5, value) self.add_field('LAYOVER_ANGLE', 's', 3, value) self.add_field('SHADOW_ANGLE', 's', 3, value) self.add_field('RESERVED_001', 's', 16, value) self.add_field('FRLC_LOC', 's', 21, value) self.add_field('LRLC_LOC', 's', 21, value) self.add_field('LRFC_LOC', 's', 21, value) self.add_field('FRFC_LOC', 's', 21, value) self.add_field('RESERVED_002', 's', 5, value) class BLOCKA(TREExtension): _tag_value = 'BLOCKA' _data_type = BLOCKAType
888
31.925926
55
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/ENGRDA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class RECORD(TREElement): def __init__(self, value): super(RECORD, self).__init__() self.add_field('ENGLN', 'd', 2, value) self.add_field('ENGLBL', 's', self.ENGLN, value) self.add_field('ENGMTXC', 's', 4, value) self.add_field('ENGMTXR', 's', 4, value) self.add_field('ENGTYP', 's', 1, value) self.add_field('ENGDTS', 'd', 1, value) self.add_field('ENGDTU', 's', 2, value) self.add_field('ENGDATC', 'd', 8, value) self.add_field('ENGDATA', 'b', self.ENGDATC*self.ENGDTS, value) class ENGRDAType(TREElement): def __init__(self, value): super(ENGRDAType, self).__init__() self.add_field('RESRC', 's', 20, value) self.add_field('RECNT', 'd', 3, value) self.add_loop('RECORDSs', self.RECNT, RECORD, value) class ENGRDA(TREExtension): _tag_value = 'ENGRDA' _data_type = ENGRDAType
1,034
30.363636
71
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/NBLOCA.py
from ..tre_elements import TREExtension, TREElement import struct __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class FRAME(TREElement): def __init__(self, value): super(FRAME, self).__init__() self.add_field('FRAME_OFFSET', 'b', 4, value) class NBLOCAType(TREElement): def __init__(self, value): super(NBLOCAType, self).__init__() self.add_field('FRAME_1_OFFSET', 'b', 4, value) self.add_field('NUMBER_OF_FRAMES', 'b', 4, value) self.add_loop('FRAMEs', struct.unpack('>I', self.NUMBER_OF_FRAMES)[0]-1, FRAME, value) class NBLOCA(TREExtension): _tag_value = 'NBLOCA' _data_type = NBLOCAType
686
25.423077
94
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/ICHIPB.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class ICHIPBType(TREElement): def __init__(self, value): super(ICHIPBType, self).__init__() self.add_field('XFRM_FLAG', 's', 2, value) self.add_field('SCALE_FACTOR', 's', 10, value) self.add_field('ANAMRPH_CORR', 's', 2, value) self.add_field('SCANBLK_NUM', 's', 2, value) self.add_field('OP_ROW_11', 's', 12, value) self.add_field('OP_COL_11', 's', 12, value) self.add_field('OP_ROW_12', 's', 12, value) self.add_field('OP_COL_12', 's', 12, value) self.add_field('OP_ROW_21', 's', 12, value) self.add_field('OP_COL_21', 's', 12, value) self.add_field('OP_ROW_22', 's', 12, value) self.add_field('OP_COL_22', 's', 12, value) self.add_field('FI_ROW_11', 's', 12, value) self.add_field('FI_COL_11', 's', 12, value) self.add_field('FI_ROW_12', 's', 12, value) self.add_field('FI_COL_12', 's', 12, value) self.add_field('FI_ROW_21', 's', 12, value) self.add_field('FI_COL_21', 's', 12, value) self.add_field('FI_ROW_22', 's', 12, value) self.add_field('FI_COL_22', 's', 12, value) self.add_field('FI_ROW', 's', 8, value) self.add_field('FI_COL', 's', 8, value) class ICHIPB(TREExtension): _tag_value = 'ICHIPB' _data_type = ICHIPBType
1,454
37.289474
54
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/CSEXRA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class CSEXRAType(TREElement): def __init__(self, value): super(CSEXRAType, self).__init__() self.add_field('SENSOR', 's', 6, value) self.add_field('TIME_FIRST_LINE_IMAGE', 's', 12, value) self.add_field('TIME_IMAGE_DURATION', 's', 12, value) self.add_field('MAX_GSD', 's', 5, value) self.add_field('ALONG_SCAN_GSD', 's', 5, value) self.add_field('CROSS_SCAN_GSD', 's', 5, value) self.add_field('GEO_MEAN_GSD', 's', 5, value) self.add_field('A_S_VERT_GSD', 's', 5, value) self.add_field('C_S_VERT_GSD', 's', 5, value) self.add_field('GEO_MEAN_VERT_GSD', 's', 5, value) self.add_field('GSD_BETA_ANGLE', 's', 5, value) self.add_field('DYNAMIC_RANGE', 's', 5, value) self.add_field('NUM_LINES', 's', 7, value) self.add_field('NUM_SAMPLES', 's', 5, value) self.add_field('ANGLE_TO_NORTH', 's', 7, value) self.add_field('OBLIQUITY_ANGLE', 's', 6, value) self.add_field('AZ_OF_OBLIQUITY', 's', 7, value) self.add_field('GRD_COVER', 's', 1, value) self.add_field('SNOW_DEPTH_CAT', 's', 1, value) self.add_field('SUN_AZIMUTH', 's', 7, value) self.add_field('SUN_ELEVATION', 's', 7, value) self.add_field('PREDICTED_NIIRS', 's', 3, value) self.add_field('CIRCL_ERR', 's', 3, value) self.add_field('LINEAR_ERR', 's', 3, value) class CSEXRA(TREExtension): _tag_value = 'CSEXRA' _data_type = CSEXRAType
1,629
39.75
63
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/CSPROA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class CSPROAType(TREElement): def __init__(self, value): super(CSPROAType, self).__init__() self.add_field('RESERVED_0', 's', 12, value) self.add_field('RESERVED_1', 's', 12, value) self.add_field('RESERVED_2', 's', 12, value) self.add_field('RESERVED_3', 's', 12, value) self.add_field('RESERVED_4', 's', 12, value) self.add_field('RESERVED_5', 's', 12, value) self.add_field('RESERVED_6', 's', 12, value) self.add_field('RESERVED_7', 's', 12, value) self.add_field('RESERVED_8', 's', 12, value) self.add_field('BWC', 's', 12, value) class CSPROA(TREExtension): _tag_value = 'CSPROA' _data_type = CSPROAType
836
31.192308
52
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/RSMGGA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class PTOFF(TREElement): def __init__(self, value): super(PTOFF, self).__init__() self.add_field('IXO', 's', 4, value) self.add_field('IYO', 's', 4, value) class GDPT(TREElement): def __init__(self, value, TNUMRD, TNUMCD): super(GDPT, self).__init__() self.add_field('RCOORD', 's', TNUMRD, value) self.add_field('CCOORD', 's', TNUMCD, value) class GRID(TREElement): def __init__(self, value, TNUMRD, TNUMCD): super(GRID, self).__init__() self.add_field('NXPTS', 'd', 3, value) self.add_field('NYPTS', 'd', 3, value) if len(value) < self.NXPTS*self.NYPTS*(TNUMRD+TNUMCD): raise ValueError( 'The input string is length {}, but there are supposed ' 'to be {}={}x{} elements each of length {}'.format( len(value), self.NXPTS*self.NYPTS, self.NXPTS, self.NYPTS, TNUMRD+TNUMCD)) self.add_loop('GDPTs', self.NXPTS*self.NYPTS, GDPT, value, TNUMRD, TNUMCD) class RSMGGAType(TREElement): def __init__(self, value): super(RSMGGAType, self).__init__() self.add_field('IID', 's', 80, value) self.add_field('EDITION', 's', 40, value) self.add_field('GGRSN', 'd', 3, value) self.add_field('GGCSN', 'd', 3, value) self.add_field('GGRFEP', 's', 21, value) self.add_field('GGCFEP', 's', 21, value) self.add_field('INTORD', 's', 1, value) self.add_field('NPLN', 'd', 3, value) self.add_field('DELTAZ', 's', 21, value) self.add_field('DELTAX', 's', 21, value) self.add_field('DELTAY', 's', 21, value) self.add_field('ZPLN1', 's', 21, value) self.add_field('XIPLN1', 's', 21, value) self.add_field('YIPLN1', 's', 21, value) self.add_field('REFROW', 's', 9, value) self.add_field('REFCOL', 's', 9, value) self.add_field('TNUMRD', 'd', 2, value) self.add_field('TNUMCD', 'd', 2, value) self.add_field('FNUMRD', 'd', 1, value) self.add_field('FNUMCD', 'd', 1, value) self.add_loop('PTOFFs', self.NPLN-1, PTOFF, value) self.add_loop('GRIDs', self.NPLN, GRID, value, self.TNUMRD, self.TNUMCD) class RSMGGA(TREExtension): _tag_value = 'RSMGGA' _data_type = RSMGGAType
2,434
36.461538
94
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/BANDSA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class BAND(TREElement): def __init__(self, value): super(BAND, self).__init__() self.add_field('BANDPEAK', 's', 5, value) self.add_field('BANDLBOUND', 's', 5, value) self.add_field('BANDUBOUND', 's', 5, value) self.add_field('BANDWIDTH', 's', 5, value) self.add_field('BANDCALDRK', 's', 6, value) self.add_field('BANDCALINC', 's', 5, value) self.add_field('BANDRESP', 's', 5, value) self.add_field('BANDASD', 's', 5, value) self.add_field('BANDGSD', 's', 5, value) class BANDSAType(TREElement): def __init__(self, value): super(BANDSAType, self).__init__() self.add_field('ROW_SPACING', 's', 7, value) self.add_field('ROW_SPACING_UNITS', 's', 1, value) self.add_field('COL_SPACING', 's', 7, value) self.add_field('COL_SPACING_UNITS', 's', 1, value) self.add_field('FOCAL_LENGTH', 's', 6, value) self.add_field('BANDCOUNT', 'd', 4, value) self.add_loop('BANDs', self.BANDCOUNT, BAND, value) class BANDSA(TREExtension): _tag_value = 'BANDSA' _data_type = BANDSAType
1,253
32.891892
59
py
sarpy
sarpy-master/sarpy/io/general/nitf_elements/tres/unclass/CSCCGA.py
from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class CSCCGAType(TREElement): def __init__(self, value): super(CSCCGAType, self).__init__() self.add_field('CCG_SOURCE', 's', 18, value) self.add_field('REG_SENSOR', 's', 6, value) self.add_field('ORIGIN_LINE', 's', 7, value) self.add_field('ORIGIN_SAMPLE', 's', 5, value) self.add_field('AS_CELL_SIZE', 's', 7, value) self.add_field('CS_CELL_SIZE', 's', 5, value) self.add_field('CCG_MAX_LINE', 's', 7, value) self.add_field('CCG_MAX_SAMPLE', 's', 5, value) class CSCCGA(TREExtension): _tag_value = 'CSCCGA' _data_type = CSCCGAType
744
30.041667
55
py
sarpy
sarpy-master/sarpy/io/product/base.py
""" Base common features for product readers """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" from typing import Sequence, List, Tuple, Union, Optional from sarpy.io.general.base import BaseReader from sarpy.io.general.data_segment import DataSegment from sarpy.io.product.sidd1_elements.SIDD import SIDDType as SIDDType1 from sarpy.io.product.sidd2_elements.SIDD import SIDDType as SIDDType2 from sarpy.io.product.sidd3_elements.SIDD import SIDDType as SIDDType3 from sarpy.io.complex.sicd_elements.SICD import SICDType class SIDDTypeReader(BaseReader): def __init__(self, data_segment: Union[None, DataSegment, Sequence[DataSegment]], sidd_meta: Union[None, SIDDType3, SIDDType2, SIDDType1, Sequence[SIDDType1], Sequence[SIDDType2], Sequence[SIDDType3]], sicd_meta: Union[None, SICDType, Sequence[SICDType]], close_segments: bool = True, delete_files: Union[None, str, Sequence[str]] = None): """ Parameters ---------- data_segment : None|DataSegment|Sequence[DataSegment] sidd_meta : None|SIDDType3|SIDDType1|SIDDType2|Sequence[SIDDType3]|Sequence[SIDDType1]|Sequence[SIDDType2] The SIDD metadata object(s). sicd_meta : None|SICDType|Sequence[SICDType] The SICD metadata object(s). close_segments : bool Call segment.close() for each data segment on reader.close()? delete_files : None|Sequence[str] Any temp files which should be cleaned up on reader.close()? This will occur after closing segments. """ if sidd_meta is None: self._sidd_meta = None elif isinstance(sidd_meta, (SIDDType1, SIDDType2, SIDDType3)): self._sidd_meta = sidd_meta else: temp_list = [] # type: List[Union[SIDDType1]] for el in sidd_meta: if not isinstance(el, (SIDDType1, SIDDType2, SIDDType3)): raise TypeError( 'Got a collection for sidd_meta, and all elements are required ' 'to be instances of SIDDType.') temp_list.append(el) self._sidd_meta = tuple(temp_list) if sicd_meta is None: self._sicd_meta = None elif isinstance(sicd_meta, SICDType): self._sicd_meta = (sicd_meta, ) else: temp_list = [] # type: List[SICDType] for el in sicd_meta: if not isinstance(el, SICDType): raise TypeError( 'Got a collection for sicd_meta, and all elements are required ' 'to be instances of SICDType.') temp_list.append(el) self._sicd_meta = tuple(temp_list) BaseReader.__init__( self, data_segment, reader_type='SIDD', close_segments=close_segments, delete_files=delete_files) def _check_sizes(self) -> None: data_sizes = self.get_data_size_as_tuple() sidds = self.get_sidds_as_tuple() if len(data_sizes) != len(sidds): raise ValueError( 'Got mismatched number of data segments ({}) and sidds ({})'.format( len(data_sizes), len(sidds))) agree = True msg = '' for i, (data_size, sidd) in enumerate(zip(data_sizes, sidds)): expected_size = (sidd.Measurement.PixelFootprint.Row, sidd.Measurement.PixelFootprint.Col) if data_size[:2] != expected_size: agree = False msg += 'data segment at index {} has data size {}\n\t' \ 'and expected size (from the sidd) {}\n'.format(i, data_size, expected_size) if not agree: raise ValueError(msg) @property def sidd_meta(self) -> Union[None, SIDDType1, SIDDType2, SIDDType3, Tuple[SIDDType1, ...], Tuple[SIDDType2, ...], Tuple[SIDDType3, ...]]: """ None|SIDDType1|SIDDType2|SIDDType3|Tuple[SIDDType1, ...]|Tuple[SIDDType2, ...]|Tuple[SIDDType3, ...]: the sidd meta_data collection. """ return self._sidd_meta @property def sicd_meta(self) -> Optional[Tuple[SICDType, ...]]: """ None|Tuple[SICDType, ...]: the sicd meta_data collection. """ return self._sicd_meta def get_sidds_as_tuple(self) -> Union[None, Tuple[SIDDType1, ...], Tuple[SIDDType2, ...], Tuple[SIDDType3, ...]]: """ Get the sidd collection as a tuple - for simplicity and consistency of use. Returns ------- None|Tuple[SIDDType1, ...]|Tuple[SIDDType2, ...]|Tuple[SIDDType3, ...] """ if self.sidd_meta is None: return None elif isinstance(self._sidd_meta, tuple): return self.sidd_meta else: # noinspection PyRedundantParentheses return (self.sidd_meta, )
4,983
38.872
141
py
sarpy
sarpy-master/sarpy/io/product/sidd.py
""" Module for reading and writing SIDD files """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" import logging from functools import reduce import re from typing import List, Tuple, Sequence, Union, BinaryIO, Optional import numpy from sarpy.io.xml.base import parse_xml_from_string from sarpy.io.general.utils import is_file_like from sarpy.io.general.base import SarpyIOError from sarpy.io.general.nitf import NITFDetails, NITFReader, NITFWriter, \ interpolate_corner_points_string, ImageSubheaderManager, \ GraphicsSubheaderManager, TextSubheaderManager, DESSubheaderManager, \ RESSubheaderManager, NITFWritingDetails, default_image_segmentation from sarpy.io.general.nitf_elements.nitf_head import NITFHeader from sarpy.io.general.nitf_elements.des import DataExtensionHeader, XMLDESSubheader from sarpy.io.general.nitf_elements.security import NITFSecurityTags from sarpy.io.general.nitf_elements.image import ImageSegmentHeader, \ ImageSegmentHeader0, ImageBands, ImageBand from sarpy.io.product.base import SIDDTypeReader from sarpy.io.product.sidd3_elements.SIDD import SIDDType as SIDDType3 from sarpy.io.product.sidd2_elements.SIDD import SIDDType as SIDDType2 from sarpy.io.product.sidd1_elements.SIDD import SIDDType as SIDDType1 from sarpy.io.complex.sicd_elements.SICD import SICDType from sarpy.io.complex.sicd import extract_clas as extract_clas_sicd, \ create_security_tags_from_sicd logger = logging.getLogger(__name__) ######## # module variables _class_priority = {'U': 0, 'R': 1, 'C': 2, 'S': 3, 'T': 4} ######### # Helper object for initially parses NITF header - specifically looking for SICD elements class SIDDDetails(NITFDetails): """ SIDD are stored in NITF 2.1 files. """ __slots__ = ( '_is_sidd', '_sidd_meta', '_sicd_meta') def __init__(self, file_object: Union[str, BinaryIO]): """ Parameters ---------- file_object : str|BinaryIO file name or file like object for a NITF 2.1 or 2.0 containing a SIDD """ self._img_headers = None self._is_sidd = False self._sidd_meta = None self._sicd_meta = None NITFDetails.__init__(self, file_object) if self._nitf_header.ImageSegments.subhead_sizes.size == 0: raise SarpyIOError('There are no image segments defined.') if self._nitf_header.GraphicsSegments.item_sizes.size > 0: raise SarpyIOError('A SIDD file does not allow for graphics segments.') if self._nitf_header.DataExtensions.subhead_sizes.size == 0: raise SarpyIOError( 'A SIDD file requires at least one data extension, containing the ' 'SIDD xml structure.') # define the sidd and sicd metadata self._find_sidd() if not self.is_sidd: raise SarpyIOError('Could not find SIDD xml data extensions.') @property def is_sidd(self) -> bool: """ bool: whether file name corresponds to a SIDD file, or not. """ return self._is_sidd @property def sidd_meta(self) -> Union[SIDDType3, SIDDType2, SIDDType1, List[SIDDType3], List[SIDDType2], List[SIDDType1]]: """ None|SIDDType3|SIDDType2|SIDDType1|List[SIDDType3]|List[SIDDType2]|List[SIDDType1]: the sidd meta-data structure(s). """ return self._sidd_meta @property def sicd_meta(self) -> Optional[List[SICDType]]: """ None|List[SICDType]: the sicd meta-data structure(s). """ return self._sicd_meta def _find_sidd(self) -> None: self._is_sidd = False if self.des_subheader_offsets is None: return self._sidd_meta = [] self._sicd_meta = [] for i in range(self.des_subheader_offsets.size): subhead_bytes = self.get_des_subheader_bytes(i) if subhead_bytes.startswith(b'DEXML_DATA_CONTENT'): des_bytes = self.get_des_bytes(i) try: root_node, xml_ns = parse_xml_from_string(des_bytes) if 'SIDD' in root_node.tag: self._is_sidd = True self._sidd_meta.append(SIDDType3.from_node(root_node, xml_ns, ns_key='default')) elif 'SICD' in root_node.tag: self._sicd_meta.append(SICDType.from_node(root_node, xml_ns, ns_key='default')) except Exception as e: logger.error('Failed checking des xml header at index {} with error {}'.format(i, e)) continue elif subhead_bytes.startswith(b'DESIDD_XML'): # This is an old format SIDD header des_bytes = self.get_des_bytes(i) try: root_node, xml_ns = parse_xml_from_string(des_bytes) if 'SIDD' in root_node.tag: self._is_sidd = True self._sidd_meta.append(SIDDType3.from_node(root_node, xml_ns, ns_key='default')) except Exception as e: logger.error( 'We found an apparent old-style SIDD DES header at index {},\n\t' 'but failed parsing with error {}'.format(i, e)) continue elif subhead_bytes.startswith(b'DESICD_XML'): # This is an old format SICD header des_bytes = self.get_des_bytes(i) try: root_node, xml_ns = parse_xml_from_string(des_bytes) if 'SICD' in root_node.tag: self._sicd_meta.append(SICDType.from_node(root_node, xml_ns, ns_key='default')) except Exception as e: logger.error( 'We found an apparent old-style SICD DES header at index {},\n\t' 'but failed parsing with error {}'.format(i, e)) continue if not self._is_sidd: return for sicd in self._sicd_meta: sicd.derive() ####### # The actual reading implementation def _check_iid_format(iid1: str) -> bool: if not (iid1[:4] == 'SIDD' and iid1[4:].isnumeric()): return False return True class SIDDReader(NITFReader, SIDDTypeReader): """ A reader object for a SIDD file (NITF container with SIDD contents) """ def __init__(self, nitf_details): """ Parameters ---------- nitf_details : str|BinaryIO|SIDDDetails filename, file-like object, or SIDDDetails object """ if isinstance(nitf_details, str) or is_file_like(nitf_details): nitf_details = SIDDDetails(nitf_details) if not isinstance(nitf_details, SIDDDetails): raise TypeError('The input argument for SIDDReader must be a filename or ' 'SIDDDetails object.') if not nitf_details.is_sidd: raise ValueError( 'The input file passed in appears to be a NITF 2.1 file that does not contain ' 'valid sidd metadata.') self._nitf_details = nitf_details SIDDTypeReader.__init__(self, None, self.nitf_details.sidd_meta, self.nitf_details.sicd_meta) NITFReader.__init__(self, nitf_details, reader_type="SIDD") self._check_sizes() @property def nitf_details(self) -> SIDDDetails: """ SIDDDetails: The SIDD NITF details object. """ return self._nitf_details def _check_image_segment_for_compliance( self, index: int, img_header: Union[ImageSegmentHeader, ImageSegmentHeader0]) -> bool: out = NITFReader._check_image_segment_for_compliance(self, index, img_header) if not out: return out out = True # skip anything but SAR for now (i.e. legend) if img_header.ICAT != 'SAR': logger.info('Image segment at index {} has ICAT != SAR'.format(index)) out = False if not _check_iid_format(img_header.IID1): logger.info('Image segment at index {} has IID1 {}'.format(index, img_header.IID1)) out = False return out def find_image_segment_collections(self) -> Tuple[Tuple[int, ...]]: segments = [[] for _ in self._sidd_meta] # the number of segments that we should have for i, img_header in enumerate(self.nitf_details.img_headers): if i in self.unsupported_segments: continue # skip these... iid1 = img_header.IID1 # required to be of the form SIDD###### if not _check_iid_format(iid1): raise ValueError('Got unhandled image segment at index {}'.format(i)) element = int(iid1[4:7]) if element > len(self._sidd_meta): raise ValueError( 'Got image segment iid1 {}, but there are only {} sidd elements'.format( iid1, len(self._sidd_meta))) segments[element - 1].append(i) # Ensure that all segments are populated with something... for i, entry in enumerate(segments): if len(entry) < 1: raise ValueError('Did not find any image segments for SIDD {}'.format(i)) # noinspection PyTypeChecker return tuple(tuple(entry) for entry in segments) ######## # base expected functionality for a module with an implemented Reader def is_a(file_name: Union[str, BinaryIO]) -> Optional[SIDDReader]: """ Tests whether a given file_name corresponds to a SIDD file. Returns a reader instance, if so. Parameters ---------- file_name : str the file_name to check Returns ------- SIDDReader|None `SIDDReader` instance if SIDD file, `None` otherwise """ try: nitf_details = SIDDDetails(file_name) if nitf_details.is_sidd: logger.info('File {} is determined to be a SIDD (NITF format) file.'.format(file_name)) return SIDDReader(nitf_details) else: return None except SarpyIOError: # we don't want to catch parsing errors, for now return None ######### # The writer implementation def validate_sidd_for_writing( sidd_meta: Union[SIDDType3, SIDDType2, SIDDType1, List[SIDDType3], List[SIDDType2], List[SIDDType1]]) -> Union[Tuple[SIDDType3, ...], Tuple[SIDDType2, ...], Tuple[SIDDType1, ...]]: """ Helper method which ensures the provided SIDD structure is appropriate. Parameters ---------- sidd_meta : SIDDType3|List[SIDDType3]|SIDDType2|List[SIDDType2]|SIDDType1|List[SIDDType1] Returns ------- Tuple[SIDDType3, ...]|Tuple[SIDDType2, ...]|Tuple[SIDDType1, ...] """ def inspect_sidd(the_sidd: Union[SIDDType3, SIDDType2, SIDDType1]) -> None: # we must have the image size if the_sidd.Measurement is None: raise ValueError('The sidd_meta has un-populated Measurement, ' 'and nothing useful can be inferred.') if the_sidd.Measurement.PixelFootprint is None: raise ValueError('The sidd_meta has un-populated Measurement.PixelFootprint, ' 'and this is not valid for writing.') # we must have the pixel type if the_sidd.Display is None: raise ValueError('The sidd_meta has un-populated Display, ' 'and nothing useful can be inferred.') if the_sidd.Display.PixelType is None: raise ValueError('The sidd_meta has un-populated Display.PixelType, ' 'and nothing useful can be inferred.') # No support for LUT until necessary if the_sidd.Display.PixelType in ('MONO8LU', 'RGB8LU'): raise ValueError('PixelType requiring lookup table currently unsupported.') # we must have collection time if the_sidd.ExploitationFeatures is None: raise ValueError('The sidd_meta has un-populated ExploitationFeatures.') if the_sidd.ExploitationFeatures.Collections is None or len(the_sidd.ExploitationFeatures.Collections) == 0: raise ValueError('The sidd_meta has un-populated ExploitationFeatures.Collections.') if the_sidd.ExploitationFeatures.Collections[0].Information is None: raise ValueError('The sidd_meta has un-populated ExploitationFeatures.Collections.Information.') if the_sidd.ExploitationFeatures.Collections[0].Information.CollectionDateTime is None: raise ValueError('The sidd_meta has un-populated ExploitationFeatures.Collections.' 'Information.CollectionDateTime') # try validating versus the appropriate schema xml_str = the_sidd.to_xml_string(tag='SIDD') from sarpy.consistency.sidd_consistency import evaluate_xml_versus_schema if isinstance(the_sidd, SIDDType1): urn = 'urn:SIDD:1.0.0' elif isinstance(the_sidd, SIDDType2): urn = 'urn:SIDD:2.0.0' elif isinstance(the_sidd, SIDDType3): urn = 'urn:SIDD:3.0.0' else: raise ValueError('Unhandled type {}'.format(type(the_sidd))) result = evaluate_xml_versus_schema(xml_str, urn) if result is False: logger.warning( 'The provided SIDD does not properly validate\n\t' 'against the schema for {}'.format(urn)) if isinstance(sidd_meta, (SIDDType3, SIDDType2, SIDDType1)): inspect_sidd(sidd_meta) # noinspection PyRedundantParentheses return (sidd_meta, ) elif isinstance(sidd_meta, (tuple, list)): out = [] for entry in sidd_meta: if not isinstance(entry, (SIDDType3, SIDDType2, SIDDType1)): raise TypeError('All entries are required to be an instance of SIDDType, ' 'got type {}'.format(type(entry))) inspect_sidd(entry) out.append(entry) return tuple(out) else: raise TypeError('sidd_meta is required to be an instance of SIDDType or a list/tuple ' 'of such instances, got {}'.format(type(sidd_meta))) def validate_sicd_for_writing(sicd_meta: Union[SICDType, Sequence[SICDType]]) -> Optional[Tuple[SICDType, ...]]: """ Helper method which ensures the provided SICD structure is appropriate. Parameters ---------- sicd_meta : SICDType|List[SICDType] Returns ------- None|Tuple[SICDType] """ if sicd_meta is None: return None if isinstance(sicd_meta, SICDType): # noinspection PyRedundantParentheses return (sicd_meta, ) elif isinstance(sicd_meta, (tuple, list)): out = [] for entry in sicd_meta: if not isinstance(entry, SICDType): raise TypeError('All entries are required to be an instance of SICDType, ' 'got type {}'.format(type(entry))) out.append(entry) return tuple(out) else: raise TypeError('sicd_meta is required to be an instance of SICDType or a list/tuple ' 'of such instances, got {}'.format(type(sicd_meta))) def extract_clas(the_sidd: Union[SIDDType3, SIDDType2, SIDDType1]) -> str: """ Extract the classification string from a SIDD as appropriate for NITF Security tags CLAS attribute. Parameters ---------- the_sidd : SIDDType3|SIDDType2|SIDDType1 Returns ------- str """ class_str = the_sidd.ProductCreation.Classification.classification if class_str is None or class_str == '': return 'U' else: return class_str[:1] def extract_clsy(the_sidd: Union[SIDDType3, SIDDType2, SIDDType1]) -> str: """ Extract the ownerProducer string from a SIDD as appropriate for NITF Security tags CLSY attribute. Parameters ---------- the_sidd : SIDDType3|SIDDType2|SIDDType1 Returns ------- str """ owner = the_sidd.ProductCreation.Classification.ownerProducer.upper() if owner is None: return '' elif owner in ('USA', 'CAN', 'AUS', 'NZL'): return owner[:2] elif owner == 'GBR': return 'UK' elif owner == 'NATO': return 'XN' else: logger.warning( 'Got owner {}, and the CLSY will be truncated\n\t' 'to two characters.'.format(owner)) return owner[:2] def create_security_tags_from_sidd(sidd_meta: Union[SIDDType3, SIDDType2, SIDDType1]) -> NITFSecurityTags: def get_basic_args(): out = {} sec_tags = sidd_meta.NITF.get('Security', {}) # noinspection PyProtectedMember for fld in NITFSecurityTags._ordering: if fld in sec_tags: out[fld] = sec_tags[fld] return out def get_clas(): if 'CLAS' in args: return args['CLAS'] = extract_clas(sidd_meta) def get_code(): # TODO: what to do here? if 'CODE' in args: return def get_clsy(): if 'CLSY' in args: return args['CLSY'] = extract_clsy(sidd_meta) args = get_basic_args() if sidd_meta.ProductCreation is not None and \ sidd_meta.ProductCreation.Classification is not None: get_clas() get_code() get_clsy() return NITFSecurityTags(**args) class SIDDWritingDetails(NITFWritingDetails): __slots__ = ( '_sidd_meta', '_sicd_meta', '_security_tags', '_sidd_security_tags', '_sicd_security_tags', '_row_limit') def __init__( self, sidd_meta: Union[SIDDType3, SIDDType2, SIDDType1, Sequence[SIDDType3], Sequence[SIDDType2], Sequence[SIDDType1]], sicd_meta: Optional[Union[SICDType, Sequence[SICDType]]], row_limit: Optional[int] = None, additional_des: Optional[Sequence[DESSubheaderManager]] = None, graphics_managers: Optional[Tuple[GraphicsSubheaderManager, ...]] = None, text_managers: Optional[Tuple[TextSubheaderManager, ...]] = None, res_managers: Optional[Tuple[RESSubheaderManager, ...]] = None): """ Parameters ---------- sidd_meta : SIDDType3|List[SIDDType3]|SIDDType2|List[SIDDType2]|SIDDType1|List[SIDDType1] sicd_meta : SICDType row_limit : None|int Desired row limit for the sicd image segments. Non-positive values or values > 99999 will be ignored. additional_des : None|Sequence[DESSubheaderManager] graphics_managers: Optional[Tuple[GraphicsSubheaderManager, ...]] text_managers: Optional[Tuple[TextSubheaderManager, ...]] res_managers: Optional[Tuple[RESSubheaderManager, ...]] """ self._sidd_meta = None self._sidd_security_tags = None self._set_sidd_meta(sidd_meta) self._sicd_meta = None self._sicd_security_tags = None self._set_sicd_meta(sicd_meta) self._security_tags = None self._create_security_tags() self._row_limit = None self._set_row_limit(row_limit) header = self._create_header() image_managers, image_segment_collection, image_segment_coordinates = self._create_image_segments() des_managers = self._create_des_segments(additional_des) NITFWritingDetails.__init__( self, header, image_managers=image_managers, image_segment_collections=image_segment_collection, image_segment_coordinates=image_segment_coordinates, graphics_managers=graphics_managers, text_managers=text_managers, des_managers=des_managers, res_managers=res_managers) @property def sidd_meta(self) -> Union[Tuple[SIDDType3, ...], Tuple[SIDDType2, ...], Tuple[SIDDType1, ...]]: """ Tuple[SIDDType3, ...]: The sidd metadata. """ return self._sidd_meta def _set_sidd_meta(self, value) -> None: if self._sidd_meta is not None: raise ValueError('sidd_meta is read only') if value is None: raise ValueError('sidd_meta is required.') self._sidd_meta = validate_sidd_for_writing(value) # noinspection PyTypeChecker self._sidd_security_tags = tuple(create_security_tags_from_sidd(entry) for entry in self._sidd_meta) @property def sicd_meta(self) -> Tuple[SICDType, ...]: """ Tuple[SICDType, ...]: The sicd metadata """ return self._sicd_meta def _set_sicd_meta(self, value) -> None: if self._sicd_meta is not None: raise ValueError('sicd_meta is read only') if value is None: self._sicd_meta = None self._sicd_security_tags = None return self._sicd_meta = validate_sicd_for_writing(value) # noinspection PyTypeChecker self._sicd_security_tags = tuple(create_security_tags_from_sicd(entry) for entry in self._sicd_meta) @property def row_limit(self) -> Tuple[int, ...]: return self._row_limit def _set_row_limit(self, value) -> None: if value is not None: if not isinstance(value, int): raise TypeError('row_bounds must be an integer') if value < 1: value = None if value is None or value > 99999: value = 99999 im_seg_limit = 10**10 - 2 # allowable image segment size row_limit = [] for sidd in self.sidd_meta: row_memory_size = sidd.Measurement.PixelFootprint.Col*sidd.Display.get_pixel_size() memory_limit = int(numpy.floor(im_seg_limit/row_memory_size)) row_limit.append(min(value, memory_limit)) self._row_limit = tuple(row_limit) def _create_security_tags(self): def class_priority(cls1, cls2): p1 = _class_priority[cls1] p2 = _class_priority[cls2] if p1 >= p2: return cls1 return cls2 # determine the highest priority clas string from all the sidds & sicds clas_collection = [extract_clas(sidd) for sidd in self.sidd_meta] if self.sicd_meta is not None: clas_collection.extend([extract_clas_sicd(sicd) for sicd in self.sicd_meta]) clas = reduce(class_priority, clas_collection) # try to determine clsy from all sidds clsy_collection = list(set(extract_clsy(sidd) for sidd in self.sidd_meta)) clsy = clsy_collection[0] if len(clsy_collection) else None # populate the attribute self._security_tags = NITFSecurityTags(CLAS=clas, CLSY=clsy) def _get_iid2(self, index: int) -> str: """ Get the IID2 for the sidd at `index`. Parameters ---------- index : int Returns ------- str """ sidd = self.sidd_meta[index] iid2 = sidd.NITF.get('IID2', None) if iid2 is None: iid2 = sidd.NITF.get('FTITLE', None) if iid2 is None: iid2 = sidd.NITF.get('SUGGESTED_NAME', None) if iid2 is None: iid2 = 'SIDD: Unknown' return iid2 def _get_ftitle(self, index: int = 0) -> str: sidd = self.sidd_meta[index] ftitle = sidd.NITF.get('FTITLE', None) if ftitle is None: ftitle = sidd.NITF.get('SUGGESTED_NAME', None) if ftitle is None: ftitle = 'SIDD: Unknown' return ftitle def _get_fdt(self, index: int) -> Optional[str]: sidd = self.sidd_meta[index] if sidd.ExploitationFeatures.Collections[0].Information.CollectionDateTime is not None: the_time = sidd.ExploitationFeatures.Collections[0].Information.CollectionDateTime.astype('datetime64[s]') return re.sub(r'[^0-9]', '', str(the_time)) else: return None def _get_ostaid(self, index: int = 0) -> str: sidd = self.sidd_meta[index] ostaid = sidd.NITF.get('OSTAID', 'Unknown') return ostaid def _get_isorce(self, index: int = 0) -> str: sidd = self.sidd_meta[index] isorce = sidd.NITF.get('ISORCE', sidd.ExploitationFeatures.Collections[0].Information.SensorName) if isorce is None: isorce = 'Unknown' return isorce def _get_icp(self, sidd_index: int) -> Optional[numpy.ndarray]: """ Get the Image corner point array, if possible. Parameters ---------- sidd_index : int Returns ------- None|numpy.ndarray """ sidd = self.sidd_meta[sidd_index] # type: Union[SIDDType3, SIDDType2, SIDDType1] if isinstance(sidd, SIDDType3) and sidd.GeoData is not None and sidd.GeoData.ImageCorners is not None: return sidd.GeoData.ImageCorners.get_array(dtype=numpy.dtype('float64')) elif isinstance(sidd, SIDDType2) and sidd.GeoData is not None and sidd.GeoData.ImageCorners is not None: return sidd.GeoData.ImageCorners.get_array(dtype=numpy.dtype('float64')) elif isinstance(sidd, SIDDType1) and sidd.GeographicAndTarget is not None and \ sidd.GeographicAndTarget.GeographicCoverage is not None and \ sidd.GeographicAndTarget.GeographicCoverage.Footprint is not None: return sidd.GeographicAndTarget.GeographicCoverage.Footprint.get_array(dtype=numpy.dtype('float64')) return None def _create_header(self) -> NITFHeader: """ Create the main NITF header. Returns ------- NITFHeader """ # NB: CLEVEL and FL will be corrected... return NITFHeader( Security=self._security_tags, CLEVEL=3, OSTAID=self._get_ostaid(), FDT=self._get_fdt(0), FTITLE=self._get_ftitle(), FL=0) def _create_image_segment_for_sidd( self, sidd_index: int, starting_index: int) -> Tuple[List[ImageSubheaderManager], Tuple[int, ...], Tuple[Tuple[int, ...], ...]]: image_managers = [] sidd = self.sidd_meta[sidd_index] if isinstance(sidd, (SIDDType2, SIDDType3)) and sidd.Compression is not None: raise ValueError('Compression not currently supported.') basic_args = { 'ICAT': 'SAR', 'IC': 'NC', 'IID2': self._get_iid2(sidd_index), 'ISORCE': self._get_isorce(sidd_index), 'IDATIM': self._get_fdt(sidd_index) } if sidd.Display.PixelType == 'MONO8I': basic_args['PVTYPE'] = 'INT' basic_args['NBPP'] = 8 basic_args['ABPP'] = 8 basic_args['IREP'] = 'MONO' basic_args['IMODE'] = 'B' irepband = ('M', ) elif sidd.Display.PixelType == 'MONO16I': basic_args['PVTYPE'] = 'INT' basic_args['NBPP'] = 16 basic_args['ABPP'] = 16 basic_args['IREP'] = 'MONO' basic_args['IMODE'] = 'B' irepband = ('M', ) elif sidd.Display.PixelType == 'RGB24I': basic_args['PVTYPE'] = 'INT' basic_args['NBPP'] = 8 basic_args['ABPP'] = 8 basic_args['IREP'] = 'RGB' basic_args['IMODE'] = 'P' irepband = ('R', 'G', 'B') else: raise ValueError('Unsupported PixelType {}'.format(sidd.Display.PixelType)) rows = sidd.Measurement.PixelFootprint.Row cols = sidd.Measurement.PixelFootprint.Col icp = self._get_icp(sidd_index) image_segment_limits = default_image_segmentation(rows, cols, self._row_limit[sidd_index]) image_segment_indices = [] total_image_count = starting_index for i, entry in enumerate(image_segment_limits): if i == 0: iloc = '0000000000' else: prev_lims = image_segment_limits[i-1] prev_rows = prev_lims[1] - prev_lims[0] iloc = '{0:05d}00000'.format(prev_rows) this_rows = entry[1]-entry[0] this_cols = entry[3]-entry[2] subhead = ImageSegmentHeader( IID1='SIDD{0:03d}{1:03d}'.format(sidd_index+1, i+1), NROWS=this_rows, NCOLS=this_cols, IGEOLO=interpolate_corner_points_string(numpy.array(entry, dtype=numpy.int64), rows, cols, icp), NPPBH=0 if this_cols > 8192 else this_cols, NPPBV=0 if this_rows > 8192 else this_rows, IDLVL=sidd_index + i + 2, IALVL=sidd_index + i + 1, ILOC=iloc, Bands=ImageBands(values=[ImageBand(ISUBCAT='', IREPBAND=entry) for entry in irepband]), Security=self._sidd_security_tags[sidd_index], **basic_args) image_managers.append(ImageSubheaderManager(subhead)) image_segment_indices.append(total_image_count) total_image_count += 1 return image_managers, tuple(image_segment_indices), image_segment_limits def _create_image_segments(self) -> Tuple[Tuple[ImageSubheaderManager, ...], Tuple[Tuple[int, ...], ...], Tuple[Tuple[Tuple[int, ...], ...]]]: image_managers = [] image_segment_collection = [] image_segment_coordinates = [] starting_index = 0 for i in range(len(self.sidd_meta)): t_managers, t_indices, t_limit = self._create_image_segment_for_sidd(i, starting_index) image_managers.extend(t_managers) image_segment_collection.append(t_indices) image_segment_coordinates.append(t_limit) starting_index = t_indices[-1] + 1 return tuple(image_managers), tuple(image_segment_collection), tuple(image_segment_coordinates) def _create_des_segment_for_sidd(self, sidd_index: int) -> DESSubheaderManager: sidd = self.sidd_meta[sidd_index] uh_args = sidd.get_des_details() try: desshdt = str(sidd.ProductCreation.ProcessorInformation.ProcessingDateTime.astype('datetime64[s]')) except AttributeError: desshdt = str(numpy.datetime64('now')) if desshdt[-1] != 'Z': desshdt += 'Z' uh_args['DESSHDT'] = desshdt desshlpg = '' icp = self._get_icp(sidd_index) if icp is not None: temp = [] for entry in icp: temp.append('{0:0=+12.8f}{1:0=+13.8f}'.format(entry[0], entry[1])) temp.append(temp[0]) desshlpg = ''.join(temp) uh_args['DESSHLPG'] = desshlpg subhead = DataExtensionHeader( Security=self._sidd_security_tags[sidd_index], UserHeader=XMLDESSubheader(**uh_args)) return DESSubheaderManager( subhead, sidd.to_xml_bytes(tag='SIDD')) def _create_sidd_des_segments(self) -> List[DESSubheaderManager]: return [self._create_des_segment_for_sidd(index) for index in range(len(self.sidd_meta))] def _create_des_segment_for_sicd(self, sicd_index: int) -> DESSubheaderManager: sicd = self.sicd_meta[sicd_index] uh_args = sicd.get_des_details() desshdt = str(sicd.ImageCreation.DateTime.astype('datetime64[s]')) if desshdt[-1] != 'Z': desshdt += 'Z' uh_args['DESSHDT'] = desshdt desshlpg = '' if sicd.GeoData is not None and sicd.GeoData.ImageCorners is not None: # noinspection PyTypeChecker icp = sicd.GeoData.ImageCorners.get_array(dtype=numpy.float64) temp = [] for entry in icp: temp.append('{0:0=+12.8f}{1:0=+13.8f}'.format(entry[0], entry[1])) temp.append(temp[0]) desshlpg = ''.join(temp) uh_args['DESSHLPG'] = desshlpg subhead = DataExtensionHeader( Security=self._sicd_security_tags[sicd_index], UserHeader=XMLDESSubheader(**uh_args)) return DESSubheaderManager( subhead, sicd.to_xml_bytes(tag='SICD', urn=uh_args['DESSHTN'])) def _create_sicd_des_segments(self) -> List[DESSubheaderManager]: if self.sicd_meta is None: return [] return [self._create_des_segment_for_sicd(index) for index in range(len(self.sicd_meta))] def _create_des_segments( self, additional_des: Optional[Sequence[DESSubheaderManager]]) -> Tuple[DESSubheaderManager, ...]: if additional_des is not None: des_managers = list(additional_des) else: des_managers = [] des_managers.extend(self._create_sidd_des_segments()) des_managers.extend(self._create_sicd_des_segments()) return tuple(des_managers) class SIDDWriter(NITFWriter): """ Writer class for a SIDD file - a NITF file following certain rules. **Changed in version 1.3.0** to reflect NITFWriter changes. """ def __init__( self, file_object: Union[str, BinaryIO], sidd_meta: Optional[Union[SIDDType3, SIDDType2, SIDDType1, Sequence[SIDDType3], Sequence[SIDDType2], Sequence[SIDDType1]]] = None, sicd_meta: Optional[Union[SICDType, Sequence[SICDType]]] = None, sidd_writing_details: Optional[SIDDWritingDetails] = None, check_existence: bool = True): """ Parameters ---------- file_object : str|BinaryIO sidd_meta : None|SIDDType3|SIDDType2|SIDDType1|Sequence[SIDDType3]|Sequence[SIDDType2]|Sequence[SIDDType1] sicd_meta : None|SICDType|Sequence[SICDType] sidd_writing_details : None|SIDDWritingDetails check_existence : bool Should we check if the given file already exists? """ if sidd_meta is None and sidd_writing_details is None: raise ValueError('One of sidd_meta or sidd_writing_details must be provided.') if sidd_writing_details is None: sidd_writing_details = SIDDWritingDetails(sidd_meta, sicd_meta=sicd_meta) NITFWriter.__init__( self, file_object, sidd_writing_details, check_existence=check_existence) @property def nitf_writing_details(self) -> SIDDWritingDetails: """ SIDDWritingDetails: The SIDD/NITF subheader details. """ # noinspection PyTypeChecker return self._nitf_writing_details @nitf_writing_details.setter def nitf_writing_details(self, value): if self._nitf_writing_details is not None: raise ValueError('nitf_writing_details is read-only') if not isinstance(value, SIDDWritingDetails): raise TypeError('nitf_writing_details must be of type {}'.format(SIDDWritingDetails)) self._nitf_writing_details = value
35,176
36.784103
146
py
sarpy
sarpy-master/sarpy/io/product/converter.py
""" This module provide utilities for opening any files analogous to Sensor Independent Derived Data, namely detected images in the ground plane. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" import os from typing import Callable from sarpy.io.general.base import SarpyIOError, check_for_openers from sarpy.io.product.base import SIDDTypeReader ########### # Module variables _openers = [] _parsed_openers = False def register_opener(open_func: Callable) -> None: """ Provide a new opener. Parameters ---------- open_func This is required to be a function which takes a single argument (file name). This function should return a sarpy.io.product.base.SIDDTypeReader instance if the referenced file is viable for the underlying type, and None otherwise. Returns ------- None """ if not callable(open_func): raise TypeError('open_func must be a callable') if open_func not in _openers: _openers.append(open_func) def parse_openers() -> None: """ Automatically find the viable openers (i.e. :func:`is_a`) in the various modules. Returns ------- """ global _parsed_openers if _parsed_openers: return _parsed_openers = True check_for_openers('sarpy.io.product', register_opener) def open_product(file_name: str) -> SIDDTypeReader: """ Given a file, try to find and return the appropriate reader object. Parameters ---------- file_name : str Returns ------- SIDDTypeReader Raises ------ SarpyIOError """ if not os.path.exists(file_name): raise SarpyIOError('File {} does not exist.'.format(file_name)) # parse openers, if not already done parse_openers() # see if we can find a reader though trial and error for opener in _openers: reader = opener(file_name) if reader is not None: return reader # If for loop completes, no matching file format was found. raise SarpyIOError('Unable to determine product image format.')
2,104
22.388889
85
py
sarpy
sarpy-master/sarpy/io/product/__init__.py
""" This package contains the elements for interpreting product data. """ __classification__ = 'UNCLASSIFIED' def open(*args, **kwargs): from .converter import open_product return open_product(*args, **kwargs)
221
19.181818
65
py
sarpy
sarpy-master/sarpy/io/product/sidd_schema/__init__.py
__classification__ = 'UNCLASSIFIED' __author__ = "Thomas McCullough" import os import re import logging from typing import List, Dict, Optional logger = logging.getLogger('validation') _the_directory = os.path.split(__file__)[0] urn_mapping = { 'urn:SIDD:1.0.0': { 'ism_urn': 'urn:us:gov:ic:ism', 'sfa_urn': 'urn:SFA:1.2.0', 'sicommon_urn': 'urn:SICommon:0.1', 'version': '1.0.0', 'release': '1.0.0', 'date': '2011-08-31T00:00:00Z', 'schema': os.path.join(_the_directory, 'version1', 'SIDD_schema_V1.0.0_2011_08_31.xsd')}, 'urn:SIDD:2.0.0': { 'ism_urn': 'urn:us:gov:ic:ism:13', 'sfa_urn': 'urn:SFA:1.2.0', 'sicommon_urn': 'urn:SICommon:1.0', 'version': '2.0.0', 'release': '2.0.0', 'date': '2019-05-31T00:00:00Z', 'schema': os.path.join(_the_directory, 'version2', 'SIDD_schema_V2.0.0_2019_05_31.xsd')}, 'urn:SIDD:3.0.0': { 'ism_urn': 'urn:us:gov:ic:ism:13', 'sfa_urn': 'urn:SFA:1.2.0', 'sicommon_urn': 'urn:SICommon:1.0', 'version': '3.0.0', 'release': '3.0.0', 'date': '2020-06-02T00:00:00Z', 'schema': os.path.join(_the_directory, 'version3', 'SIDD_schema_V3.0.0.xsd')}, } _SIDD_SPECIFICATION_IDENTIFIER = 'SIDD Volume 1 Design & Implementation Description Document' def get_specification_identifier() -> str: """ Get the SIDD specification identifier string. Returns ------- str """ return _SIDD_SPECIFICATION_IDENTIFIER def check_urn(urn_string: str) -> str: """ Checks that the urn string follows the correct pattern. Parameters ---------- urn_string : str Returns ------- str Raises ------ ValueError This raises an exception for a poorly formed or unmapped SIDD urn. """ if not isinstance(urn_string, str): raise TypeError( 'Expected a urn input of string type, got type {}'.format(type(urn_string))) the_match = re.match(r'^\d.\d.\d$', urn_string) if the_match is not None: urn_string = 'urn:SIDD:{}'.format(urn_string) the_match = re.match(r'^urn:SIDD:\d.\d.\d$', urn_string) if the_match is None: raise ValueError( 'Input provided as `{}`,\nbut should be of the form ' '`urn:SIDD:<major>.<minor>.<release>'.format(urn_string)) return urn_string def get_urn_details(urn_string: str) -> Dict[str, str]: """ Gets the associated details for the given SIDD urn, or raise an exception for poorly formatted or unrecognized urn. Parameters ---------- urn_string : str Returns ------- Dict[str, str] """ urn_string = check_urn(urn_string) out = urn_mapping.get(urn_string, None) if out is None: raise KeyError( 'Got correctly formatted, but unmapped SIDD urn {}.'.format(urn_string)) return out def get_schema_path(the_urn: str) -> Optional[str]: """ Gets the path to the proper schema file for the given SIDD urn. Parameters ---------- the_urn : str Returns ------- None|str """ result = get_urn_details(the_urn) return result.get('schema', None) def get_versions() -> List[str]: """ Gets a list of recognized SIDD urn. Returns ------- List[str] """ return list(sorted(urn_mapping.keys())) def validate_xml_ns(xml_ns: Dict[str, str], ns_key: str = 'default') -> bool: """ Validate the parsed SIDD xml namespace dictionary. This is expected to accompany the use of :func:`sarpy.io.general.utils.parse_xml_from_string`. Parameters ---------- xml_ns : dict The xml namespace dictionary. ns_key : str The main SIDD element or default namespace. Returns ------- bool """ if not isinstance(xml_ns, dict): raise ValueError('xml_ns must be a dictionary for SIDD interpretation.') if ns_key not in xml_ns: raise ValueError('ns_key must be a key in xml_ns.') sidd_urn = xml_ns[ns_key] try: details = get_urn_details(sidd_urn) except KeyError: logger.error('Got unmapped sidd urn `{}`'.format(sidd_urn)) return False # key => (expected prefix, required) expected_ns = { 'ism': ('urn:us:gov:ic:ism', True), 'sfa': ('urn:sfa:', False), 'sicommon': ('urn:sicommon:', True), } ns_to_add = dict() for expected_key, (expected_prefix, _) in expected_ns.items(): if expected_key not in xml_ns: for actual_ns in xml_ns.values(): if isinstance(actual_ns, str) and actual_ns.lower().startswith(expected_prefix): ns_to_add[expected_key] = actual_ns break xml_ns.update(ns_to_add) valid = True for key, (_, required) in expected_ns.items(): if key in xml_ns and xml_ns[key] != details[f'{key}_urn']: valid = False logger.error( 'SIDD: SIDD {} `{}` namespace urn is expected to be "{}", but we got "{}".\n\t' 'Differences in standard may lead to deserialization and/or ' 'validation errors.'.format(sidd_urn, key, details[f'{key}_urn'], xml_ns[key])) if required and key not in xml_ns: valid = False logger.error(f'SIDD: No `{key}` namespace defined.') return valid
5,450
26.39196
97
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/Compression.py
""" The CompressionType definition. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" from typing import Union import numpy from sarpy.io.xml.base import Serializable from sarpy.io.xml.descriptors import SerializableDescriptor, IntegerDescriptor, \ FloatArrayDescriptor from .base import DEFAULT_STRICT, FLOAT_FORMAT class J2KSubtype(Serializable): """ The Jpeg 2000 subtype. """ _fields = ('NumWaveletLevels', 'NumBands', 'LayerInfo') _required = ('NumWaveletLevels', 'NumBands') _collections_tags = {'LayerInfo': {'array': True, 'child_tag': 'Bitrate', 'size_attribute': 'numLayers'}} _numeric_format = {'LayerInfo': FLOAT_FORMAT} # Descriptor NumWaveletLevels = IntegerDescriptor( 'NumWaveletLevels', _required, strict=DEFAULT_STRICT, docstring='') # type: int NumBands = IntegerDescriptor( 'NumBands', _required, strict=DEFAULT_STRICT, docstring='') # type: int LayerInfo = FloatArrayDescriptor( 'LayerInfo', _collections_tags, _required, strict=DEFAULT_STRICT, docstring='Original Layer Information. This is an array of bit rate target associated with each ' 'layer. It may happen that the bit rate was not achieved due to data characteristics. ' '**Note -** for JPEG 2000 numerically loss-less quality, the bit rate for the final layer is ' 'an expected value, based on performance.') # type: Union[None, numpy.ndarray] def __init__(self, NumWaveletLevels=None, NumBands=None, LayerInfo=None, **kwargs): """ Parameters ---------- NumWaveletLevels : int NumBands : int LayerInfo : None|numpy.ndarray|list|tuple kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.NumWaveletLevels = NumWaveletLevels self.NumBands = NumBands self.LayerInfo = LayerInfo super(J2KSubtype, self).__init__(**kwargs) class J2KType(Serializable): """ Jpeg 2000 parameters. """ _fields = ('Original', 'Parsed') _required = ('Original', ) # Descriptor Original = SerializableDescriptor( 'Original', J2KSubtype, _required, strict=DEFAULT_STRICT, docstring='') # type: J2KSubtype Parsed = SerializableDescriptor( 'Parsed', J2KSubtype, _required, strict=DEFAULT_STRICT, docstring='Conditional fields that exist only for parsed images.') # type: Union[None, J2KSubtype] def __init__(self, Original=None, Parsed=None, **kwargs): if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Original = Original self.Parsed = Parsed super(J2KType, self).__init__(**kwargs) class CompressionType(Serializable): """ Contains information regarding any compression that has occurred to the image data. """ _fields = ('J2K', ) _required = ('J2K', ) # Descriptor J2K = SerializableDescriptor( 'J2K', J2KType, _required, strict=DEFAULT_STRICT, docstring='Block describing details of JPEG 2000 compression.') # type: J2KType def __init__(self, J2K=None, **kwargs): """ Parameters ---------- J2K : J2KType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.J2K = J2K super(CompressionType, self).__init__(**kwargs)
3,752
31.921053
112
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/Measurement.py
""" The MeasurementType definition. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" from typing import Union, List from sarpy.io.xml.base import Serializable, SerializableArray from sarpy.io.xml.descriptors import SerializableDescriptor, UnitVectorDescriptor, \ FloatDescriptor, StringEnumDescriptor, SerializableArrayDescriptor from .base import DEFAULT_STRICT, FLOAT_FORMAT from .blocks import ReferencePointType, RowColDoubleType, Poly2DType, XYZType, RowColIntType, \ XYZPolyType, RowColArrayElement class BaseProjectionType(Serializable): """ The base geometric projection system. """ _fields = ('ReferencePoint', ) _required = ('ReferencePoint', ) # Descriptor ReferencePoint = SerializableDescriptor( 'ReferencePoint', ReferencePointType, _required, strict=DEFAULT_STRICT, docstring='Reference point for the geometrical system.') # type: ReferencePointType def __init__(self, ReferencePoint=None, **kwargs): """ Parameters ---------- ReferencePoint : ReferencePointType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.ReferencePoint = ReferencePoint super(BaseProjectionType, self).__init__(**kwargs) class MeasurableProjectionType(BaseProjectionType): """ A physical base projection. """ _fields = ('ReferencePoint', 'SampleSpacing', 'TimeCOAPoly') _required = ('ReferencePoint', 'SampleSpacing', 'TimeCOAPoly') # Descriptor SampleSpacing = SerializableDescriptor( 'SampleSpacing', RowColDoubleType, _required, strict=DEFAULT_STRICT, docstring='Sample spacing in row and column.') # type: RowColDoubleType TimeCOAPoly = SerializableDescriptor( 'TimeCOAPoly', Poly2DType, _required, strict=DEFAULT_STRICT, docstring='Time (units = seconds) at which center of aperture for a given pixel ' 'coordinate in the product occurs.') # type: Poly2DType def __init__(self, ReferencePoint=None, SampleSpacing=None, TimeCOAPoly=None, **kwargs): """ Parameters ---------- ReferencePoint : ReferencePointType SampleSpacing : RowColDoubleType|numpy.ndarray|list|tuple TimeCOAPoly : Poly2DType|numpy.ndarray|list|tuple kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] super(MeasurableProjectionType, self).__init__(ReferencePoint=ReferencePoint, **kwargs) self.SampleSpacing = SampleSpacing self.TimeCOAPoly = TimeCOAPoly class ProductPlaneType(Serializable): """ Plane definition for the product. """ _fields = ('RowUnitVector', 'ColUnitVector') _required = _fields # Descriptor RowUnitVector = UnitVectorDescriptor( 'RowUnitVector', XYZType, _required, strict=DEFAULT_STRICT, docstring='Unit vector of the plane defined to be aligned in the increasing row direction ' 'of the product. (Defined as Rpgd in Design and Exploitation document)') # type: XYZType ColUnitVector = UnitVectorDescriptor( 'ColUnitVector', XYZType, _required, strict=DEFAULT_STRICT, docstring='Unit vector of the plane defined to be aligned in the increasing column direction ' 'of the product. (Defined as Cpgd in Design and Exploitation document)') # type: XYZType def __init__(self, RowUnitVector=None, ColUnitVector=None, **kwargs): """ Parameters ---------- RowUnitVector : XYZType|numpy.ndarray|list|tuple ColUnitVector : XYZType|numpy.ndarray|list|tuple kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.RowUnitVector = RowUnitVector self.ColUnitVector = ColUnitVector super(ProductPlaneType, self).__init__(**kwargs) class PlaneProjectionType(MeasurableProjectionType): """ Planar representation of the pixel grid. """ _fields = ('ReferencePoint', 'SampleSpacing', 'TimeCOAPoly', 'ProductPlane') _required = ('ReferencePoint', 'SampleSpacing', 'TimeCOAPoly', 'ProductPlane') # Descriptor ProductPlane = SerializableDescriptor( 'ProductPlane', ProductPlaneType, _required, strict=DEFAULT_STRICT, docstring='') # type: ProductPlaneType def __init__(self, ReferencePoint=None, SampleSpacing=None, TimeCOAPoly=None, ProductPlane=None, **kwargs): """ Parameters ---------- ReferencePoint : ReferencePointType SampleSpacing : RowColDoubleType|numpy.ndarray|list|tuple TimeCOAPoly : Poly2DType|numpy.ndarray|list|tuple ProductPlane : ProductPlaneType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] super(PlaneProjectionType, self).__init__( ReferencePoint=ReferencePoint, SampleSpacing=SampleSpacing, TimeCOAPoly=TimeCOAPoly, **kwargs) self.ProductPlane = ProductPlane class GeographicProjectionType(MeasurableProjectionType): """ Geographic mapping of the pixel grid. """ pass class CylindricalProjectionType(MeasurableProjectionType): """ Cylindrical mapping of the pixel grid. """ _fields = ('ReferencePoint', 'SampleSpacing', 'TimeCOAPoly', 'StripmapDirection', 'CurvatureRadius') _required = ('ReferencePoint', 'SampleSpacing', 'TimeCOAPoly', 'StripmapDirection') _numeric_format = {'CurvatureRadius': FLOAT_FORMAT} # Descriptor StripmapDirection = SerializableDescriptor( 'StripmapDirection', XYZType, _required, strict=DEFAULT_STRICT, docstring='Along stripmap direction.') # type: XYZType CurvatureRadius = FloatDescriptor( 'CurvatureRadius', _required, strict=DEFAULT_STRICT, docstring='Radius of Curvature defined at scene center. If not present, the radius of ' 'curvature will be derived based upon the equations provided in the ' 'Design and Exploitation Document') # type: Union[None, float] def __init__(self, ReferencePoint=None, SampleSpacing=None, TimeCOAPoly=None, StripmapDirection=None, CurvatureRadius=None, **kwargs): """ Parameters ---------- ReferencePoint : ReferencePointType SampleSpacing : RowColDoubleType|numpy.ndarray|list|tuple TimeCOAPoly : Poly2DType|numpy.ndarray|list|tuple StripmapDirection : XYZType|numpy.ndarray|list|tuple CurvatureRadius : None|float kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] super(CylindricalProjectionType, self).__init__( ReferencePoint=ReferencePoint, SampleSpacing=SampleSpacing, TimeCOAPoly=TimeCOAPoly, **kwargs) self.StripmapDirection = StripmapDirection self.CurvatureRadius = CurvatureRadius class PolynomialProjectionType(BaseProjectionType): """ Polynomial pixel to ground. This should only used for sensor systems where the radar geometry parameters are not recorded. """ _fields = ('ReferencePoint', 'RowColToLat', 'RowColToLon', 'RowColToAlt', 'LatLonToRow', 'LatLonToCol') _required = ('ReferencePoint', 'RowColToLat', 'RowColToLon', 'LatLonToRow', 'LatLonToCol') # Descriptor RowColToLat = SerializableDescriptor( 'RowColToLat', Poly2DType, _required, strict=DEFAULT_STRICT, docstring='Polynomial that converts Row/Col to Latitude (degrees).') # type: Poly2DType RowColToLon = SerializableDescriptor( 'RowColToLon', Poly2DType, _required, strict=DEFAULT_STRICT, docstring='Polynomial that converts Row/Col to Longitude (degrees).') # type: Poly2DType RowColToAlt = SerializableDescriptor( 'RowColToAlt', Poly2DType, _required, strict=DEFAULT_STRICT, docstring='Polynomial that converts Row/Col to Altitude (meters above ' 'WGS-84 ellipsoid).') # type: Union[None, Poly2DType] LatLonToRow = SerializableDescriptor( 'LatLonToRow', Poly2DType, _required, strict=DEFAULT_STRICT, docstring='Polynomial that converts Latitude (degrees) and Longitude (degrees) to ' 'pixel row location.') # type: Poly2DType LatLonToCol = SerializableDescriptor( 'LatLonToCol', Poly2DType, _required, strict=DEFAULT_STRICT, docstring='Polynomial that converts Latitude (degrees) and Longitude (degrees) to ' 'pixel col location.') # type: Poly2DType def __init__(self, ReferencePoint=None, RowColToLat=None, RowColToLon=None, RowColToAlt=None, LatLonToRow=None, LatLonToCol=None, **kwargs): """ Parameters ---------- ReferencePoint : ReferencePointType RowColToLat : Poly2DType|numpy.ndarray|list|tuple RowColToLon : Poly2DType|numpy.ndarray|list|tuple RowColToAlt : None|Poly2DType|numpy.ndarray|list|tuple LatLonToRow : Poly2DType|numpy.ndarray|list|tuple LatLonToCol : Poly2DType|numpy.ndarray|list|tuple kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] super(PolynomialProjectionType, self).__init__(ReferencePoint=ReferencePoint, **kwargs) self.RowColToLat = RowColToLat self.RowColToLon = RowColToLon self.RowColToAlt = RowColToAlt self.LatLonToRow = LatLonToRow self.LatLonToCol = LatLonToCol class MeasurementType(Serializable): """ Geometric SAR information required for measurement/geolocation. """ _fields = ( 'PolynomialProjection', 'GeographicProjection', 'PlaneProjection', 'CylindricalProjection', 'PixelFootprint', 'ARPFlag', 'ARPPoly', 'ValidData') _required = ('PixelFootprint', 'ARPPoly', 'ValidData') _collections_tags = {'ValidData': {'array': True, 'child_tag': 'Vertex'}} _numeric_format = {'ValidData': FLOAT_FORMAT} _choice = ({'required': False, 'collection': ('PolynomialProjection', 'GeographicProjection', 'PlaneProjection', 'CylindricalProjection')}, ) # Descriptor PolynomialProjection = SerializableDescriptor( 'PolynomialProjection', PolynomialProjectionType, _required, strict=DEFAULT_STRICT, docstring='Polynomial pixel to ground. Should only used for sensor systems where the radar ' 'geometry parameters are not recorded.') # type: Union[None, PolynomialProjectionType] GeographicProjection = SerializableDescriptor( 'GeographicProjection', GeographicProjectionType, _required, strict=DEFAULT_STRICT, docstring='Geographic mapping of the pixel grid referred to as GGD in the ' 'Design and Exploitation document.') # type: Union[None, GeographicProjectionType] PlaneProjection = SerializableDescriptor( 'PlaneProjection', PlaneProjectionType, _required, strict=DEFAULT_STRICT, docstring='Planar representation of the pixel grid referred to as PGD in the ' 'Design and Exploitation document.') # type: Union[None, PlaneProjectionType] CylindricalProjection = SerializableDescriptor( 'CylindricalProjection', CylindricalProjectionType, _required, strict=DEFAULT_STRICT, docstring='Cylindrical mapping of the pixel grid referred to as CGD in the ' 'Design and Exploitation document.') # type: Union[None, CylindricalProjectionType] PixelFootprint = SerializableDescriptor( 'PixelFootprint', RowColIntType, _required, strict=DEFAULT_STRICT, docstring='Size of the image in pixels.') # type: RowColIntType ARPFlag = StringEnumDescriptor( 'ARPFlag', ('REALTIME', 'PREDICTED', 'POST PROCESSED'), _required, strict=DEFAULT_STRICT, docstring='Flag indicating whether ARP polynomial is based on the best available (`collect time` or ' '`predicted`) ephemeris.') # type: Union[None, str] ARPPoly = SerializableDescriptor( 'ARPPoly', XYZPolyType, _required, strict=DEFAULT_STRICT, docstring='') # type: XYZPolyType ValidData = SerializableArrayDescriptor( 'ValidData', RowColArrayElement, _collections_tags, _required, strict=DEFAULT_STRICT, minimum_length=3, docstring='Indicates the full image includes both valid data and some zero filled pixels. ' 'Simple polygon encloses the valid data (may include some zero filled pixels for simplification). ' 'Vertices in clockwise order.') # type: Union[SerializableArray, List[RowColArrayElement]] def __init__(self, PolynomialProjection=None, GeographicProjection=None, PlaneProjection=None, CylindricalProjection=None, PixelFootprint=None, ARPFlag=None, ARPPoly=None, ValidData=None, **kwargs): """ Parameters ---------- PolynomialProjection : PolynomialProjectionType GeographicProjection : GeographicProjectionType PlaneProjection : PlaneProjectionType CylindricalProjection : CylindricalProjectionType PixelFootprint : RowColIntType|numpy.ndarray|list|tuple ARPFlag : str ARPPoly : XYZPolyType|numpy.ndarray|list|tuple ValidData : SerializableArray|List[RowColArrayElement]|numpy.ndarray|list|tuple kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.PolynomialProjection = PolynomialProjection self.GeographicProjection = GeographicProjection self.PlaneProjection = PlaneProjection self.CylindricalProjection = CylindricalProjection self.PixelFootprint = PixelFootprint self.ARPFlag = ARPFlag self.ARPPoly = ARPPoly self.ValidData = ValidData super(MeasurementType, self).__init__(**kwargs) @property def ProjectionType(self): """str: *READ ONLY* Identifies the specific image projection type supplied.""" for attribute in self._choice[0]['collection']: if getattr(self, attribute) is not None: return attribute return None @property def ReferencePoint(self): """ None|ReferencePointType: *READ ONLY* Gets the reference point. """ for attribute in self._choice[0]['collection']: if getattr(self, attribute) is not None: return attribute.ReferencePoint return None
15,215
42.350427
120
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/base.py
__classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" DEFAULT_STRICT = False FLOAT_FORMAT = '0.17G'
118
13.875
35
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/DigitalElevationData.py
""" The DigitalElevationDataType definition. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" from typing import Union, List import numpy from sarpy.io.xml.base import Serializable from sarpy.io.xml.descriptors import SerializableDescriptor, IntegerDescriptor, \ FloatDescriptor, FloatListDescriptor, StringEnumDescriptor from .base import DEFAULT_STRICT, FLOAT_FORMAT from .blocks import LatLonType class GeographicCoordinatesType(Serializable): """ Describes the Local Geographic Coordinate system linking row/column to the absolute geographic coordinate (lat/lon). """ _fields = ('LongitudeDensity', 'LatitudeDensity', 'ReferenceOrigin') _required = ('LongitudeDensity', 'LatitudeDensity', 'ReferenceOrigin') _numeric_format = {'LongitudeDensity': FLOAT_FORMAT, 'LatitudeDensity': FLOAT_FORMAT} # Descriptor LongitudeDensity = FloatDescriptor( 'LongitudeDensity', _required, strict=DEFAULT_STRICT, docstring='Pixel ground spacing in E/W direction that is the number of pixels ' 'or element intervals in 360 degrees.') # type: float LatitudeDensity = FloatDescriptor( 'LatitudeDensity', _required, strict=DEFAULT_STRICT, docstring='Pixel ground spacing in N/S direction that is the number of pixels ' 'or element intervals in 360 degrees.') # type: float ReferenceOrigin = SerializableDescriptor( 'ReferenceOrigin', LatLonType, _required, strict=DEFAULT_STRICT, docstring='Northwest corner Latitude/Longitude - product NW corner') # type: LatLonType def __init__(self, LongitudeDensity=None, LatitudeDensity=None, ReferenceOrigin=None, **kwargs): """ Parameters ---------- LongitudeDensity : float LatitudeDensity : float ReferenceOrigin : LatLonType|numpy.ndarray|list|tuple kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] self.LongitudeDensity = LongitudeDensity self.LatitudeDensity = LatitudeDensity self.ReferenceOrigin = ReferenceOrigin super(GeographicCoordinatesType, self).__init__(**kwargs) class GeopositioningType(Serializable): """ Describes the absolute coordinate system to which the data is referenced. """ _fields = ( 'CoordinateSystemType', 'GeodeticDatum', 'ReferenceEllipsoid', 'VerticalDatum', 'SoundingDatum', 'FalseOrigin', 'UTMGridZoneNumber') _required = ( 'CoordinateSystemType', 'GeodeticDatum', 'ReferenceEllipsoid', 'VerticalDatum', 'SoundingDatum', 'FalseOrigin') # Descriptor CoordinateSystemType = StringEnumDescriptor( 'CoordinateSystemType', ('GGS', 'UTM'), _required, strict=DEFAULT_STRICT, docstring='') # type: str GeodeticDatum = StringEnumDescriptor( 'GeodeticDatum', ('World Geodetic System 1984', ), _required, strict=DEFAULT_STRICT, default_value='World Geodetic System 1984', docstring='') # type: str ReferenceEllipsoid = StringEnumDescriptor( 'ReferenceEllipsoid', ('World Geodetic System 1984', ), _required, strict=DEFAULT_STRICT, default_value='World Geodetic System 1984', docstring='') # type: str VerticalDatum = StringEnumDescriptor( 'VerticalDatum', ('Mean Sea Level', ), _required, strict=DEFAULT_STRICT, default_value='Mean Sea Level', docstring='') # type: str SoundingDatum = StringEnumDescriptor( 'SoundingDatum', ('Mean Sea Level', ), _required, strict=DEFAULT_STRICT, default_value='Mean Sea Level', docstring='') # type: str FalseOrigin = IntegerDescriptor( 'FalseOrigin', _required, strict=DEFAULT_STRICT, docstring='Z values false origin.') # type: int UTMGridZoneNumber = IntegerDescriptor( 'UTMGridZoneNumber', _required, strict=DEFAULT_STRICT, docstring='Gride zone number, required for UTM, not include for GCS. ' '**Values -** `+001` to `+060` (northern hemisphere) and `-001` to `-060` ' '(southern hemisphere)') # type: int def __init__(self, CoordinateSystemType=None, GeodeticDatum='World Geodetic System 1984', ReferenceEllipsoid='World Geodetic System 1984', VerticalDatum='Mean Sea Level', SoundingDatum='Mean Sea Level', FalseOrigin=None, UTMGridZoneNumber=None, **kwargs): """ Parameters ---------- CoordinateSystemType : str GeodeticDatum : str ReferenceEllipsoid : str VerticalDatum : str SoundingDatum : str FalseOrigin : int UTMGridZoneNumber : None|int kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] self.CoordinateSystemType = CoordinateSystemType self.GeodeticDatum = GeodeticDatum self.ReferenceEllipsoid = ReferenceEllipsoid self.VerticalDatum = VerticalDatum self.SoundingDatum = SoundingDatum self.FalseOrigin = FalseOrigin self.UTMGridZoneNumber = UTMGridZoneNumber super(GeopositioningType, self).__init__(**kwargs) class AccuracyType(Serializable): """ The accuracy estimate. """ _fields = ('Horizontals', 'Verticals') _required = ('Horizontals', 'Verticals') _collections_tags = { 'Horizontals': {'array': False, 'child_tag': 'Horizontal'}, 'Verticals': {'array': False, 'child_tag': 'Vertical'}} _numeric_format = {key: FLOAT_FORMAT for key in _fields} # Descriptor Horizontals = FloatListDescriptor( 'Horizontals', _collections_tags, _required, strict=DEFAULT_STRICT, docstring='') # type: List[float] Verticals = FloatListDescriptor( 'Verticals', _collections_tags, _required, strict=DEFAULT_STRICT, docstring='') # type: List[float] def __init__(self, Horizontals=None, Verticals=None, **kwargs): """ Parameters ---------- Horizontals : List[float] Verticals : List[float] kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] self.Horizontals = Horizontals self.Verticals = Verticals super(AccuracyType, self).__init__(**kwargs) class PositionalAccuracyType(Serializable): """ Describes the horizontal and vertical point and regional information for the DED. """ _fields = ('NumRegions', 'AbsoluteAccuracy', 'PointToPointAccuracy') _required = ('NumRegions', 'AbsoluteAccuracy', 'PointToPointAccuracy') # Descriptor NumRegions = IntegerDescriptor( 'NumRegions', _required, strict=DEFAULT_STRICT, docstring='Number of positional accuracy regions.') # type: int AbsoluteAccuracy = SerializableDescriptor( 'AbsoluteAccuracy', AccuracyType, _required, strict=DEFAULT_STRICT, docstring='') # type: AccuracyType PointToPointAccuracy = SerializableDescriptor( 'PointToPointAccuracy', AccuracyType, _required, strict=DEFAULT_STRICT, docstring='') # type: AccuracyType def __init__(self, NumRegions=None, AbsoluteAccuracy=None, PointToPointAccuracy=None, **kwargs): """ Parameters ---------- NumRegions : int AbsoluteAccuracy : AccuracyType PointToPointAccuracy : AccuracyType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.NumRegions = NumRegions self.AbsoluteAccuracy = AbsoluteAccuracy self.PointToPointAccuracy = PointToPointAccuracy super(PositionalAccuracyType, self).__init__(**kwargs) class DigitalElevationDataType(Serializable): """ This describes any Digital Elevation Data included with the SIDD product. """ _fields = ('GeographicCoordinates', 'Geopositioning', 'PositionalAccuracy', 'NullValue') _required = ('GeographicCoordinates', 'Geopositioning', 'PositionalAccuracy') # Descriptor GeographicCoordinates = SerializableDescriptor( 'GeographicCoordinates', GeographicCoordinatesType, _required, strict=DEFAULT_STRICT, docstring='Describes the Local Geographic Coordinate system linking row/column to the ' 'absolute geographic coordinate (lat/lon)') # type: GeographicCoordinatesType Geopositioning = SerializableDescriptor( 'Geopositioning', GeopositioningType, _required, strict=DEFAULT_STRICT, docstring='Describes the absolute coordinate system to which the data is ' 'referenced.') # type: GeopositioningType PositionalAccuracy = SerializableDescriptor( 'PositionalAccuracy', PositionalAccuracyType, _required, strict=DEFAULT_STRICT, docstring='Describes the horizontal and vertical point and regional information ' 'for the DED.') # type: PositionalAccuracyType NullValue = IntegerDescriptor( 'NullValue', _required, strict=DEFAULT_STRICT, docstring='The value in the DEM corresponding to `No Value`.') # type: Union[None, int] def __init__(self, GeographicCoordinates=None, Geopositioning=None, PositionalAccuracy=None, NullValue=None, **kwargs): """ Parameters ---------- GeographicCoordinates : GeographicCoordinatesType Geopositioning : GeopositioningType PositionalAccuracy : PositionalAccuracyType NullValue : int kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.GeographicCoordinates = GeographicCoordinates self.Geopositioning = Geopositioning self.PositionalAccuracy = PositionalAccuracy self.NullValue = NullValue super(DigitalElevationDataType, self).__init__(**kwargs)
10,095
39.384
101
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/ExploitationFeatures.py
""" The ExploitationFeaturesType definition. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" import logging import datetime from typing import Union, List import numpy from sarpy.io.xml.base import Serializable, ParametersCollection from sarpy.io.xml.descriptors import SerializableDescriptor, ParametersDescriptor, \ FloatDescriptor, FloatModularDescriptor, StringDescriptor, StringEnumDescriptor, \ DateTimeDescriptor, SerializableListDescriptor from sarpy.io.complex.sicd_elements.SCPCOA import GeometryCalculator from sarpy.io.complex.sicd_elements.SICD import SICDType from sarpy.geometry.geocoords import wgs_84_norm, ecf_to_geodetic from .base import DEFAULT_STRICT, FLOAT_FORMAT from .blocks import RowColIntType, RowColDoubleType, RangeAzimuthType, \ AngleMagnitudeType, RadarModeType TX_POLARIZATION_VALUES = ('V', 'H', 'RHC', 'LHC', 'OTHER', 'UNKNOWN', 'SEQUENCE') RCV_POLARIZATION_VALUES = ('V', 'H', 'RHC', 'LHC', 'OTHER', 'UNKNOWN') logger = logging.getLogger(__name__) _sicd_type_text = 'Requires instance of SICDType,\n\tgot type `{}`' _exp_calc_text = 'Requires input which is an instance of ExploitationCalculator,\n\tgot type `{}`' class ExploitationCalculator(object): """ Helper class for calculating the various geometric values for exploitation features. This is predominantly using the ontology presented in the SIDD standards document. """ def __init__(self, geometry_calculator, row_vector, col_vector): """ Parameters ---------- geometry_calculator : GeometryCalculator row_vector : numpy.ndarray col_vector : numpy.ndarray """ # extract sicd based parameters self.geometry_calculator = geometry_calculator self.ARPPos = geometry_calculator.ARP self.ARPVel = geometry_calculator.ARP_vel self.SCP = geometry_calculator.SCP self.slant_x = self._make_unit(self.ARPPos - self.SCP) self.slant_z = self._make_unit(numpy.cross(self.slant_x, self.ARPVel)) if self.slant_z.dot(self.ARPPos) < 0: self.slant_z *= -1 self.slant_y = self._make_unit(numpy.cross(self.slant_z, self.slant_x)) self.ETP = wgs_84_norm(self.SCP) # store SIDD grid parameters self.row_vector = self._make_unit(row_vector) self.col_vector = self._make_unit(col_vector) self.normal_vector = self._make_unit(numpy.cross(self.row_vector, self.col_vector)) @staticmethod def _make_unit(vec): vec_norm = numpy.linalg.norm(vec) if vec_norm < 1e-6: logger.error( 'input vector to be normalized has norm {}, this may be a mistake'.format(vec_norm)) return vec/vec_norm # The geometry properties @property def AzimuthAngle(self): return self.geometry_calculator.AzimAng @property def SlopeAngle(self): """ float: The angle between the ground plane and slant plane. Note that the standard outlines this is angle between the Earth Tangent Plane and slant plane, with the expectation that the "ground plane" will always be defined as the Earth Tangent Plane. """ return numpy.rad2deg(numpy.arccos(self.slant_z.dot(self.ETP))) @property def DopplerConeAngle(self): return self.geometry_calculator.DopplerConeAng @property def SquintAngle(self): return self.geometry_calculator.SquintAngle @property def GrazeAngle(self): """ float: The angle between the ground plane and line of sight vector. """ return numpy.rad2deg(numpy.arcsin(self.slant_x.dot(self.ETP))) @property def TiltAngle(self): """ float: The angle between the ground plane and cross range vector. """ return numpy.rad2deg(numpy.arctan(self.ETP.dot(self.slant_y)/self.ETP.dot(self.slant_z))) # The phenomenology properties @property def Shadow(self): # type: () -> AngleMagnitudeType """ AngleMagnitudeType: The shadow angle and magnitude. """ shadow = self.ETP - self.slant_x/(self.slant_x.dot(self.ETP)) shadow_prime = shadow - (shadow.dot(self.normal_vector)/self.slant_z.dot(self.normal_vector))*self.slant_z return AngleMagnitudeType( Angle=numpy.rad2deg(numpy.arctan2(self.col_vector.dot(shadow_prime), self.row_vector.dot(shadow_prime))), Magnitude=numpy.linalg.norm(shadow_prime)) @property def Layover(self): # type: () -> AngleMagnitudeType """ AngleMagnitudeType: The layover angle and magnitude. """ layover = self.normal_vector - self.slant_z/(self.slant_z.dot(self.normal_vector)) return AngleMagnitudeType( Angle=numpy.rad2deg(numpy.arctan2(self.col_vector.dot(layover), self.row_vector.dot(layover))), Magnitude=numpy.linalg.norm(layover)) @property def North(self): """ float: The north angle. """ lat, lon, hae = ecf_to_geodetic(self.SCP) lat_r = numpy.deg2rad(lat) lon_r = numpy.deg2rad(lon) north = numpy.array( [-numpy.sin(lat_r)*numpy.cos(lon_r), -numpy.sin(lat_r)*numpy.sin(lon_r), numpy.cos(lat_r)]) north_prime = north - self.slant_z*(north.dot(self.normal_vector)/self.slant_z.dot(self.normal_vector)) return numpy.rad2deg(numpy.arctan2(self.col_vector.dot(north_prime), self.row_vector.dot(north_prime))) @property def MultiPath(self): """ float: The multipath angle. """ multipath = self.slant_x - self.slant_z*( self.slant_x.dot(self.normal_vector)/self.slant_z.dot(self.normal_vector)) return numpy.rad2deg(numpy.arctan2(self.col_vector.dot(multipath), self.row_vector.dot(multipath))) @property def GroundTrack(self): """ float: The ground track angle. """ track = self.ARPVel - (self.ARPVel.dot(self.normal_vector))*self.normal_vector return numpy.rad2deg(numpy.arctan2(self.col_vector.dot(track), self.row_vector.dot(track))) def get_ground_plane_resolution(self, row_ss, col_ss): """ Get the resolution in the ground plane. Parameters ---------- row_ss : float col_ss : float Returns ------- float, float """ x_g = self.slant_x - (self.slant_x.dot(self.normal_vector))*self.normal_vector theta_r = -numpy.arctan2(self.col_vector.dot(x_g), self.row_vector.dot(x_g)) graze = numpy.deg2rad(self.GrazeAngle) tilt = numpy.deg2rad(self.TiltAngle) k_r1 = (numpy.cos(theta_r)/numpy.cos(graze))**2 + \ (numpy.sin(theta_r)**2*numpy.tan(graze)*numpy.tan(tilt) - numpy.sin(2*theta_r)/numpy.cos(graze))*numpy.tan(graze)*numpy.tan(tilt) k_r2 = (numpy.sin(theta_r)/numpy.cos(tilt))**2 k_c1 = (numpy.sin(theta_r)**2/numpy.cos(graze) - numpy.sin(2*theta_r)*numpy.tan(graze)*numpy.tan(tilt))/numpy.cos(graze) + \ (numpy.cos(theta_r)*numpy.tan(graze)*numpy.tan(tilt))**2 k_c2 = (numpy.cos(theta_r)/numpy.cos(tilt))**2 r2 = row_ss*row_ss c2 = col_ss*col_ss return float(numpy.sqrt(k_r1*r2 + k_r2*c2)), float(numpy.sqrt(k_c1*r2 + k_c2*c2)) @classmethod def from_sicd(cls, sicd, row_vector, col_vector): """ Construct from SICD structure. Parameters ---------- sicd : SICDType row_vector : numpy.ndarray col_vector : numpy.ndarray """ calculator = GeometryCalculator( sicd.GeoData.SCP.ECF.get_array(), sicd.SCPCOA.ARPPos.get_array(), sicd.SCPCOA.ARPVel.get_array()) return cls(calculator, row_vector, col_vector) def _extract_sicd_tx_rcv_pol(str_in): """ Extract the tx and rcv components from the sicd style tx/rcv polarization string. Parameters ---------- str_in : str Returns ------- str, str """ if str_in is None: return 'UNKNOWN', 'UNKNOWN' if not isinstance(str_in, str): raise TypeError('requires a string type input.') if str_in in ['OTHER', 'UNKNOWN']: return 'UNKNOWN', 'UNKNOWN' return str_in.split(':') class InputROIType(Serializable): """ ROI representing portion of input data used to make this product. """ _fields = ('Size', 'UpperLeft') _required = ('Size', 'UpperLeft') # Descriptor Size = SerializableDescriptor( 'Size', RowColIntType, _required, strict=DEFAULT_STRICT, docstring='Number of rows and columns extracted from the input.') # type: RowColIntType UpperLeft = SerializableDescriptor( 'UpperLeft', RowColIntType, _required, strict=DEFAULT_STRICT, docstring='The upper-left pixel extracted from the input.') # type: RowColIntType def __init__(self, Size=None, UpperLeft=None, **kwargs): """ Parameters ---------- Size : RowColIntType|numpy.ndarray|list|tuple UpperLeft : RowColIntType|numpy.ndarray|list|tuple kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Size = Size self.UpperLeft = UpperLeft super(InputROIType, self).__init__(**kwargs) class TxRcvPolarizationType(Serializable): """ The transmit/receive polarization information. """ _fields = ('TxPolarization', 'RcvPolarization', 'RcvPolarizationOffset') _required = ('TxPolarization', 'RcvPolarization') _numeric_format = {'RcvPolarizationOffset': FLOAT_FORMAT} # Descriptor TxPolarization = StringEnumDescriptor( 'TxPolarization', TX_POLARIZATION_VALUES, _required, strict=DEFAULT_STRICT, docstring='Transmit polarization type.') # type: str RcvPolarization = StringEnumDescriptor( 'RcvPolarization', RCV_POLARIZATION_VALUES, _required, strict=DEFAULT_STRICT, docstring='Receive polarization type.') # type: str RcvPolarizationOffset = FloatModularDescriptor( 'RcvPolarizationOffset', 180.0, _required, strict=DEFAULT_STRICT, docstring='Angle offset for the receive polarization defined at aperture center.') # type: float def __init__(self, TxPolarization=None, RcvPolarization=None, RcvPolarizationOffset=None, **kwargs): """ Parameters ---------- TxPolarization : str RcvPolarization : str RcvPolarizationOffset : None|float kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.TxPolarization = TxPolarization self.RcvPolarization = RcvPolarization self.RcvPolarizationOffset = RcvPolarizationOffset super(TxRcvPolarizationType, self).__init__(**kwargs) @classmethod def from_sicd_value(cls, str_in): """ Construct from the sicd style tx/rcv polarization string. Parameters ---------- str_in : str Returns ------- TxRcvPolarizationType """ tx, rcv = _extract_sicd_tx_rcv_pol(str_in) return cls(TxPolarization=tx, RcvPolarization=rcv) class ProcTxRcvPolarizationType(Serializable): """ The processed transmit/receive polarization. """ _fields = ('TxPolarizationProc', 'RcvPolarizationProc') _required = ('TxPolarizationProc', 'RcvPolarizationProc') # Descriptor TxPolarizationProc = StringEnumDescriptor( 'TxPolarizationProc', TX_POLARIZATION_VALUES, _required, strict=DEFAULT_STRICT, docstring='Transmit polarization type.') # type: str RcvPolarizationProc = StringEnumDescriptor( 'RcvPolarizationProc', RCV_POLARIZATION_VALUES, _required, strict=DEFAULT_STRICT, docstring='Receive polarization type.') # type: str def __init__(self, TxPolarizationProc=None, RcvPolarizationProc=None, **kwargs): """ Parameters ---------- TxPolarizationProc : str RcvPolarizationProc : str kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.TxPolarizationProc = TxPolarizationProc self.RcvPolarizationProc = RcvPolarizationProc super(ProcTxRcvPolarizationType, self).__init__(**kwargs) @classmethod def from_sicd_value(cls, str_in): """ Construct from the sicd style tx/rcv polarization string. Parameters ---------- str_in : str Returns ------- ProcTxRcvPolarizationType """ tx, rcv = _extract_sicd_tx_rcv_pol(str_in) return cls(TxPolarizationProc=tx, RcvPolarizationProc=rcv) class ExploitationFeaturesCollectionInformationType(Serializable): """ General collection information. """ _fields = ( 'SensorName', 'RadarMode', 'CollectionDateTime', 'LocalDateTime', 'CollectionDuration', 'Resolution', 'InputROI', 'Polarizations') _required = ('SensorName', 'RadarMode', 'CollectionDateTime', 'CollectionDuration') _collections_tags = {'Polarizations': {'array': False, 'child_tag': 'Polarization'}} _numeric_format = {'CollectionDuration': FLOAT_FORMAT} # Descriptor SensorName = StringDescriptor( 'SensorName', _required, strict=DEFAULT_STRICT, docstring='The name of the sensor.') # str RadarMode = SerializableDescriptor( 'RadarMode', RadarModeType, _required, strict=DEFAULT_STRICT, docstring='Radar collection mode.') # type: RadarModeType CollectionDateTime = DateTimeDescriptor( 'CollectionDateTime', _required, strict=DEFAULT_STRICT, docstring='Collection date and time defined in Coordinated Universal Time (UTC). The seconds ' 'should be followed by a Z to indicate UTC.') # type: numpy.datetime64 CollectionDuration = FloatDescriptor( 'CollectionDuration', _required, strict=DEFAULT_STRICT, docstring='The duration of the collection (units = seconds).') # type: float Resolution = SerializableDescriptor( 'Resolution', RangeAzimuthType, _required, strict=DEFAULT_STRICT, docstring='Uniformly-weighted resolution (range and azimuth) processed in ' 'the slant plane.') # type: Union[None, RangeAzimuthType] InputROI = SerializableDescriptor( 'InputROI', InputROIType, _required, strict=DEFAULT_STRICT, docstring='ROI representing portion of input data used to make ' 'this product.') # type: Union[None, InputROIType] Polarizations = SerializableListDescriptor( 'Polarizations', TxRcvPolarizationType, _collections_tags, _required, strict=DEFAULT_STRICT, docstring='Transmit and receive polarization(s).') # type: Union[None, List[TxRcvPolarizationType]] def __init__(self, SensorName=None, RadarMode=None, CollectionDateTime=None, LocalDateTime=None, CollectionDuration=None, Resolution=None, Polarizations=None, **kwargs): """ Parameters ---------- SensorName : str RadarMode : RadarModeType CollectionDateTime : numpy.datetime64|datetime.datetime|datetime.date|str LocalDateTime : None|str|datetime.datetime CollectionDuration : float Resolution : None|RangeAzimuthType|numpy.ndarray|list|tuple Polarizations : None|List[TxRcvPolarizationType] kwargs """ self._local_date_time = None if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.SensorName = SensorName self.RadarMode = RadarMode self.CollectionDateTime = CollectionDateTime self.CollectionDuration = CollectionDuration self.LocalDateTime = LocalDateTime self.Resolution = Resolution self.Polarizations = Polarizations super(ExploitationFeaturesCollectionInformationType, self).__init__(**kwargs) @property def LocalDateTime(self): """None|str: The local date/time string of the collection. *Optional.*""" return self._local_date_time @LocalDateTime.setter def LocalDateTime(self, value): # type: (Union[None, str, datetime.datetime]) -> None if value is None: self._local_date_time = None return elif isinstance(value, datetime.datetime): value = value.isoformat('T') if isinstance(value, str): self._local_date_time = value else: logger.error( 'Attribute LocalDateTime of class ExploitationFeaturesCollectionInformationType\n\t' 'requires a datetime.datetime or string. Got unsupported type {}.\n\t' 'Setting value to None.'.format(type(value))) self._local_date_time = None @classmethod def from_sicd(cls, sicd): """ Construct from a sicd element. Parameters ---------- sicd : SICDType Returns ------- ExploitationFeaturesCollectionInformationType """ if not isinstance(sicd, SICDType): raise TypeError(_sicd_type_text.format(type(sicd))) polarizations = [ TxRcvPolarizationType.from_sicd_value(entry.TxRcvPolarization) for entry in sicd.RadarCollection.RcvChannels] return cls(SensorName=sicd.CollectionInfo.CollectorName, RadarMode=RadarModeType(**sicd.CollectionInfo.RadarMode.to_dict()), CollectionDateTime=sicd.Timeline.CollectStart, CollectionDuration=sicd.Timeline.CollectDuration, Resolution=(sicd.Grid.Row.SS, sicd.Grid.Col.SS), Polarizations=polarizations) class ExploitationFeaturesCollectionGeometryType(Serializable): """ Key geometry parameters independent of product processing. All values computed at the center time of the full collection. """ _fields = ('Azimuth', 'Slope', 'Squint', 'Graze', 'Tilt', 'DopplerConeAngle', 'Extensions') _required = () _collections_tags = {'Extensions': {'array': False, 'child_tag': 'Extension'}} _numeric_format = { 'Azimuth': FLOAT_FORMAT, 'Slope': FLOAT_FORMAT, 'Squint': FLOAT_FORMAT, 'Graze': FLOAT_FORMAT, 'Tilt': FLOAT_FORMAT, 'DopplerConeAngle': FLOAT_FORMAT} # Descriptor Azimuth = FloatDescriptor( 'Azimuth', _required, strict=DEFAULT_STRICT, bounds=(0.0, 360.0), docstring='Angle clockwise from north indicating the ETP line of sight vector.') # type: float Slope = FloatDescriptor( 'Slope', _required, strict=DEFAULT_STRICT, bounds=(0.0, 90.0), docstring='Angle between the ETP at scene center and the range vector perpendicular to ' 'the direction of motion.') # type: float Squint = FloatModularDescriptor( 'Squint', 180.0, _required, strict=DEFAULT_STRICT, docstring='Angle from the ground track to platform velocity vector at nadir. ' 'Left-look is positive, right-look is negative.') # type: float Graze = FloatDescriptor( 'Graze', _required, strict=DEFAULT_STRICT, bounds=(0.0, 90.0), docstring='Angle between the ETP and the line of sight vector.') # type: float Tilt = FloatModularDescriptor( 'Tilt', 180.0, _required, strict=DEFAULT_STRICT, docstring='Angle between the ETP and the cross range vector. ' 'Also known as the twist angle.') # type: float DopplerConeAngle = FloatDescriptor( 'DopplerConeAngle', _required, strict=DEFAULT_STRICT, bounds=(0.0, 180.0), docstring='The angle between the velocity vector and the radar line-of-sight vector. ' 'Also known as the slant plane squint angle.') # type: float Extensions = ParametersDescriptor( 'Extensions', _collections_tags, _required, strict=DEFAULT_STRICT, docstring='Exploitation feature extension related to geometry for a ' 'single input image.') # type: ParametersCollection def __init__(self, Azimuth=None, Slope=None, Squint=None, Graze=None, Tilt=None, DopplerConeAngle=None, Extensions=None, **kwargs): """ Parameters ---------- Azimuth : None|float Slope : None|float Squint : None|float Graze : None|float Tilt : None|float DopplerConeAngle : None|float Extensions : None|ParametersCollection|dict kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Azimuth = Azimuth self.Slope = Slope self.Squint = Squint self.Graze = Graze self.Tilt = Tilt self.DopplerConeAngle = DopplerConeAngle self.Extensions = Extensions super(ExploitationFeaturesCollectionGeometryType, self).__init__(**kwargs) @classmethod def from_calculator(cls, calculator): """ Create from an ExploitationCalculator object. Parameters ---------- calculator : ExploitationCalculator Returns ------- ExploitationFeaturesCollectionGeometryType """ if not isinstance(calculator, ExploitationCalculator): raise TypeError(_exp_calc_text.format(type(calculator))) return cls(Azimuth=calculator.AzimuthAngle, Slope=calculator.SlopeAngle, Graze=calculator.SlopeAngle, Tilt=calculator.TiltAngle, DopplerConeAngle=calculator.DopplerConeAngle, Squint=calculator.SquintAngle) class ExploitationFeaturesCollectionPhenomenologyType(Serializable): """ Phenomenology related to both the geometry and the final product processing. All values computed at the center time of the full collection. """ _fields = ('Shadow', 'Layover', 'MultiPath', 'GroundTrack', 'Extensions') _required = () _collections_tags = {'Extensions': {'array': False, 'child_tag': 'Extension'}} _numeric_format = {'MultiPath': FLOAT_FORMAT, 'GroundTrack': FLOAT_FORMAT} # Descriptor Shadow = SerializableDescriptor( 'Shadow', AngleMagnitudeType, _required, strict=DEFAULT_STRICT, docstring='The phenomenon where vertical objects occlude radar ' 'energy.') # type: Union[None, AngleMagnitudeType] Layover = SerializableDescriptor( 'Layover', AngleMagnitudeType, _required, strict=DEFAULT_STRICT, docstring='The phenomenon where vertical objects appear as ground objects with ' 'the same range/range rate.') # type: Union[None, AngleMagnitudeType] MultiPath = FloatModularDescriptor( 'MultiPath', 180.0, _required, strict=DEFAULT_STRICT, docstring='This is a range dependent phenomenon which describes the energy from a ' 'single scatter returned to the radar via more than one path and results ' 'in a nominally constant direction in the ETP.') # type: Union[None, float] GroundTrack = FloatModularDescriptor( 'GroundTrack', 180.0, _required, strict=DEFAULT_STRICT, docstring='Counter-clockwise angle from increasing row direction to ground track ' 'at the center of the image.') # type: Union[None, float] Extensions = ParametersDescriptor( 'Extensions', _collections_tags, _required, strict=DEFAULT_STRICT, docstring='Exploitation feature extension related to geometry for a ' 'single input image.') # type: ParametersCollection def __init__(self, Shadow=None, Layover=None, MultiPath=None, GroundTrack=None, Extensions=None, **kwargs): """ Parameters ---------- Shadow : None|AngleMagnitudeType|numpy.ndarray|list|tuple Layover : None|AngleMagnitudeType|numpy.ndarray|list|tuple MultiPath : None|float GroundTrack : None|float Extensions : None|ParametersCollection|dict kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Shadow = Shadow self.Layover = Layover self.MultiPath = MultiPath self.GroundTrack = GroundTrack self.Extensions = Extensions super(ExploitationFeaturesCollectionPhenomenologyType, self).__init__(**kwargs) @classmethod def from_calculator(cls, calculator): """ Create from an ExploitationCalculator object. Parameters ---------- calculator : ExploitationCalculator Returns ------- ExploitationFeaturesCollectionPhenomenologyType """ if not isinstance(calculator, ExploitationCalculator): raise TypeError(_exp_calc_text.format(type(calculator))) return cls(Shadow=calculator.Shadow, Layover=calculator.Layover, MultiPath=calculator.MultiPath, GroundTrack=calculator.GroundTrack) class CollectionType(Serializable): """ Metadata regarding one of the input collections. """ _fields = ('Information', 'Geometry', 'Phenomenology', 'identifier') _required = ('Information', 'identifier') _set_as_attribute = ('identifier', ) # Descriptor Information = SerializableDescriptor( 'Information', ExploitationFeaturesCollectionInformationType, _required, strict=DEFAULT_STRICT, docstring='General collection information.') # type: ExploitationFeaturesCollectionInformationType Geometry = SerializableDescriptor( 'Geometry', ExploitationFeaturesCollectionGeometryType, _required, strict=DEFAULT_STRICT, docstring='Key geometry parameters independent of product ' 'processing.') # type: Union[None, ExploitationFeaturesCollectionGeometryType] Phenomenology = SerializableDescriptor( 'Phenomenology', ExploitationFeaturesCollectionPhenomenologyType, _required, strict=DEFAULT_STRICT, docstring='Phenomenology related to both the geometry and the final ' 'product processing.') # type: Union[None, ExploitationFeaturesCollectionPhenomenologyType] identifier = StringDescriptor( 'identifier', _required, strict=DEFAULT_STRICT, docstring='The exploitation feature identifier.') # type: str def __init__(self, Information=None, Geometry=None, Phenomenology=None, identifier=None, **kwargs): """ Parameters ---------- Information : ExploitationFeaturesCollectionInformationType Geometry : None|ExploitationFeaturesCollectionGeometryType Phenomenology : None|ExploitationFeaturesCollectionPhenomenologyType identifier : str kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Information = Information self.Geometry = Geometry self.Phenomenology = Phenomenology self.identifier = identifier super(CollectionType, self).__init__(**kwargs) @classmethod def from_calculator(cls, calculator, sicd): """ Create from an ExploitationCalculator object. Parameters ---------- calculator : ExploitationCalculator sicd : SICDType Returns ------- CollectionType """ if not isinstance(calculator, ExploitationCalculator): raise TypeError(_exp_calc_text.format(type(calculator))) return cls(identifier=sicd.CollectionInfo.CoreName, Information=ExploitationFeaturesCollectionInformationType.from_sicd(sicd), Geometry=ExploitationFeaturesCollectionGeometryType.from_calculator(calculator), Phenomenology=ExploitationFeaturesCollectionPhenomenologyType.from_calculator(calculator)) class ExploitationFeaturesProductType(Serializable): """ Metadata regarding the product. """ _fields = ('Resolution', 'Ellipticity', 'Polarizations', 'North', 'Extensions') _required = ('Resolution', 'Ellipticity', 'Polarizations') _collections_tags = { 'Polarizations': {'array': False, 'child_tag': 'Polarization'}, 'Extensions': {'array': False, 'child_tag': 'Extension'}} _numeric_format = {'Ellipticity': FLOAT_FORMAT, 'North': FLOAT_FORMAT} # Descriptor Resolution = SerializableDescriptor( 'Resolution', RowColDoubleType, _required, strict=DEFAULT_STRICT, docstring='Uniformly-weighted resolution projected into the Earth Tangent ' 'Plane (ETP).') # type: RowColDoubleType Ellipticity = FloatDescriptor( 'Ellipticity', _required, strict=DEFAULT_STRICT, docstring="Ellipticity of the 2D-IPR at the ORP, measured in the *Earth Geodetic " "Tangent Plane (EGTP)*. Ellipticity is the ratio of the IPR ellipse's " "major axis to minor axis.") # type: float Polarizations = SerializableListDescriptor( 'Polarizations', ProcTxRcvPolarizationType, _collections_tags, _required, strict=DEFAULT_STRICT, docstring='Describes the processed transmit and receive polarizations for the ' 'product.') # type: List[ProcTxRcvPolarizationType] North = FloatModularDescriptor( 'North', 180.0, _required, strict=DEFAULT_STRICT, docstring='Counter-clockwise angle from increasing row direction to north at the center ' 'of the image.') # type: float Extensions = ParametersDescriptor( 'Extensions', _collections_tags, _required, strict=DEFAULT_STRICT, docstring='Exploitation feature extension related to geometry for a ' 'single input image.') # type: ParametersCollection def __init__(self, Resolution=None, Ellipticity=None, Polarizations=None, North=None, Extensions=None, **kwargs): """ Parameters ---------- Resolution : RowColDoubleType|numpy.ndarray|list|tuple Ellipticity : float Polarizations : List[ProcTxRcvPolarizationType] North : None|float Extensions : None|ParametersCollection|dict kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Resolution = Resolution self.Ellipticity = Ellipticity self.Polarizations = Polarizations self.North = North self.Extensions = Extensions super(ExploitationFeaturesProductType, self).__init__(**kwargs) @classmethod def from_calculator(cls, calculator, sicd): """ Construct from a sicd element. Parameters ---------- calculator : ExploitationCalculator sicd : SICDType Returns ------- ExploitationFeaturesProductType """ if not isinstance(sicd, SICDType): raise TypeError(_sicd_type_text.format(type(sicd))) row_ground, col_ground = sicd.get_ground_resolution() ellipticity = row_ground/col_ground if row_ground >= col_ground else col_ground/row_ground return cls(Resolution=(row_ground, col_ground), Ellipticity=ellipticity, Polarizations=[ ProcTxRcvPolarizationType.from_sicd_value(sicd.ImageFormation.TxRcvPolarizationProc), ], North=calculator.North) class ExploitationFeaturesType(Serializable): """ Computed metadata regarding the collect. """ _fields = ('Collections', 'Products') _required = ('Collections', 'Products') _collections_tags = { 'Collections': {'array': False, 'child_tag': 'Collection'}, 'Products': {'array': False, 'child_tag': 'Product'}} # Descriptor Collections = SerializableListDescriptor( 'Collections', CollectionType, _collections_tags, _required, strict=DEFAULT_STRICT, docstring='') # type: List[CollectionType] Products = SerializableListDescriptor( 'Products', ExploitationFeaturesProductType, _collections_tags, _required, strict=DEFAULT_STRICT, docstring='') # type: List[ExploitationFeaturesProductType] def __init__(self, Collections=None, Products=None, **kwargs): """ Parameters ---------- Collections : List[CollectionType] Products : List[ExploitationFeaturesProductType] kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Collections = Collections self.Products = Products super(ExploitationFeaturesType, self).__init__(**kwargs) @classmethod def from_sicd(cls, sicd, row_vector, col_vector): """ Construct from a sicd element. Parameters ---------- sicd : SICDType|List[SICDType] row_vector : numpy.ndarray col_vector : numpy.ndarray Returns ------- ExploitationFeaturesType """ if isinstance(sicd, (list, tuple)): collections = [] feats = [] for i, entry in sicd: calculator = ExploitationCalculator.from_sicd(entry, row_vector, col_vector) collections.append(CollectionType.from_calculator(calculator, entry)) feats.append(ExploitationFeaturesProductType.from_calculator(calculator, entry)) return cls(Collections=collections, Products=feats) if not isinstance(sicd, SICDType): raise TypeError(_sicd_type_text.format(type(sicd))) calculator = ExploitationCalculator.from_sicd(sicd, row_vector, col_vector) return cls( Collections=[CollectionType.from_calculator(calculator, sicd), ], Products=[ExploitationFeaturesProductType.from_calculator(calculator, sicd)])
34,922
37.461454
117
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/Annotations.py
""" The AnnotationsType definition. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" import logging from typing import Union, List import numpy from .base import DEFAULT_STRICT, FLOAT_FORMAT from sarpy.io.xml.base import Serializable, create_new_node, create_text_node, \ get_node_value, find_first_child, find_children from sarpy.io.xml.descriptors import SerializableDescriptor, SerializableListDescriptor, \ FloatDescriptor, StringDescriptor, StringListDescriptor from sarpy.geometry.geometry_elements import Point as PointType, \ LineString as LineStringType, \ LinearRing as LinearRingType, \ Polygon as PolygonType, \ MultiPoint as MultiPointType, \ MultiLineString as MultiLineStringType, \ MultiPolygon as MultiPolygonType logger = logging.getLogger(__name__) class ParameterType(Serializable): """ The parameter type. """ _fields = ('ParameterName', 'Value') _required = _fields _numeric_format = {'Value': FLOAT_FORMAT} # Descriptor ParameterName = StringDescriptor( 'ParameterName', _required, strict=DEFAULT_STRICT, docstring='') # type: str Value = FloatDescriptor( 'Value', _required, strict=DEFAULT_STRICT, docstring='') # type: float def __init__(self, ParameterName=None, Value=None, **kwargs): """ Parameters ---------- ParameterName : str Value : float kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.ParameterName = ParameterName self.Value = Value super(ParameterType, self).__init__(**kwargs) class ProjectionType(Serializable): """ The projection type. """ _fields = ('ProjectionName', ) _required = ('ProjectionName', ) # Descriptor ProjectionName = StringDescriptor( 'ProjectionName', _required, strict=DEFAULT_STRICT, docstring='') # type: str def __init__(self, ProjectionName=None, **kwargs): """ Parameters ---------- ProjectionName : str kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.ProjectionName = ProjectionName super(ProjectionType, self).__init__(**kwargs) class PrimeMeridianType(Serializable): """ The prime meridian location. """ _fields = ('Name', 'Longitude') _required = _fields _numeric_format = {'Longitude': FLOAT_FORMAT} # Descriptor Name = StringDescriptor( 'Name', _required, strict=DEFAULT_STRICT, docstring='') # type: str Longitude = FloatDescriptor( 'Longitude', _required, strict=DEFAULT_STRICT, docstring='') # type: float def __init__(self, Name=None, Longitude=None, **kwargs): """ Parameters ---------- Name : str Longitude : float kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Name = Name self.Longitude = Longitude super(PrimeMeridianType, self).__init__(**kwargs) class SpheroidType(Serializable): """ """ _fields = ('SpheroidName', 'SemiMajorAxis', 'InverseFlattening') _required = _fields _numeric_format = {'SemiMajorAxis': FLOAT_FORMAT, 'InverseFlattening': FLOAT_FORMAT} # Descriptor SpheroidName = StringDescriptor( 'SpheroidName', _required, strict=DEFAULT_STRICT, docstring='') # type: str SemiMajorAxis = FloatDescriptor( 'SemiMajorAxis', _required, strict=DEFAULT_STRICT, docstring='') # type: float InverseFlattening = FloatDescriptor( 'InverseFlattening', _required, strict=DEFAULT_STRICT, docstring='') # type: float def __init__(self, SpheroidName=None, SemiMajorAxis=None, InverseFlattening=None, **kwargs): """ Parameters ---------- SpheroidName : str SemiMajorAxis : float InverseFlattening : float kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.SpheroidName = SpheroidName self.SemiMajorAxis = SemiMajorAxis self.InverseFlattening = InverseFlattening super(SpheroidType, self).__init__(**kwargs) class DatumType(Serializable): """ """ _fields = ('Spheroid', ) _required = ('Spheroid', ) # Descriptor Spheroid = SerializableDescriptor( 'Spheroid', SpheroidType, _required, strict=DEFAULT_STRICT, docstring='') # type: SpheroidType def __init__(self, Spheroid=None, **kwargs): """ Parameters ---------- Spheroid : SpheroidType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Spheroid = Spheroid super(DatumType, self).__init__(**kwargs) class GeographicCoordinateSystemType(Serializable): """ """ _fields = ('Csname', 'Datum', 'PrimeMeridian', 'AngularUnit', 'LinearUnit') _required = ('Csname', 'Datum', 'PrimeMeridian', 'AngularUnit') # Descriptor Csname = StringDescriptor( 'Csname', _required, strict=DEFAULT_STRICT, docstring='') # type: str Datum = SerializableDescriptor( 'Datum', DatumType, _required, strict=DEFAULT_STRICT, docstring='') # type: DatumType PrimeMeridian = SerializableDescriptor( 'PrimeMeridian', PrimeMeridianType, _required, strict=DEFAULT_STRICT, docstring='') # type: PrimeMeridianType AngularUnit = StringDescriptor( 'AngularUnit', _required, strict=DEFAULT_STRICT, docstring='') # type: str LinearUnit = StringDescriptor( 'LinearUnit', _required, strict=DEFAULT_STRICT, docstring='') # type: str def __init__(self, Csname=None, Datum=None, PrimeMeridian=None, AngularUnit=None, LinearUnit=None, **kwargs): """ Parameters ---------- Csname : str Datum : DatumType PrimeMeridian : PrimeMeridianType AngularUnit : str LinearUnit : str kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Csname = Csname self.Datum = Datum self.PrimeMeridian = PrimeMeridian self.AngularUnit = AngularUnit self.LinearUnit = LinearUnit super(GeographicCoordinateSystemType, self).__init__(**kwargs) class ProjectedCoordinateSystemType(Serializable): """ """ _fields = ('Csname', 'GeographicCoordinateSystem', 'Projection', 'Parameter', 'LinearUnit') _required = ('Csname', 'GeographicCoordinateSystem', 'Projection', 'LinearUnit') # Descriptor Csname = StringDescriptor( 'Csname', _required, strict=DEFAULT_STRICT, docstring='') # type: str GeographicCoordinateSystem = SerializableDescriptor( 'GeographicCoordinateSystem', GeographicCoordinateSystemType, _required, strict=DEFAULT_STRICT, docstring='') # type: GeographicCoordinateSystemType Projection = SerializableDescriptor( 'Projection', ProjectionType, _required, strict=DEFAULT_STRICT, docstring='') # type: ProjectionType Parameter = SerializableDescriptor( 'Parameter', ParameterType, _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, ParameterType] LinearUnit = StringDescriptor( 'LinearUnit', _required, strict=DEFAULT_STRICT, docstring='') # type: str def __init__(self, Csname=None, GeographicCoordinateSystem=None, Projection=None, Parameter=None, LinearUnit=None, **kwargs): """ Parameters ---------- Csname : str GeographicCoordinateSystem : GeographicCoordinateSystemType Projection : ProjectionType Parameter : None|ParameterType LinearUnit : str kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Csname = Csname self.GeographicCoordinateSystem = GeographicCoordinateSystem self.Projection = Projection self.Parameter = Parameter self.LinearUnit = LinearUnit super(ProjectedCoordinateSystemType, self).__init__(**kwargs) class GeocentricCoordinateSystemType(Serializable): """ """ _fields = ('Name', 'Datum', 'PrimeMeridian', 'LinearUnit') _required = ('Name', 'Datum', 'PrimeMeridian', 'LinearUnit') # Descriptor Name = StringDescriptor( 'Name', _required, strict=DEFAULT_STRICT, docstring='') # type: str Datum = SerializableDescriptor( 'Datum', DatumType, _required, strict=DEFAULT_STRICT, docstring='') # type: DatumType PrimeMeridian = SerializableDescriptor( 'PrimeMeridian', PrimeMeridianType, _required, strict=DEFAULT_STRICT, docstring='') # type: PrimeMeridianType LinearUnit = StringDescriptor( 'LinearUnit', _required, strict=DEFAULT_STRICT, docstring='') # type: str def __init__(self, Name=None, Datum=None, PrimeMeridian=None, LinearUnit=None, **kwargs): """ Parameters ---------- Name : str Datum : DatumType PrimeMeridian : PrimeMeridianType LinearUnit : str kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Name = Name self.Datum = Datum self.PrimeMeridian = PrimeMeridian self.LinearUnit = LinearUnit super(GeocentricCoordinateSystemType, self).__init__(**kwargs) class ReferenceSystemType(Serializable): """ The reference system. """ _fields = ('ProjectedCoordinateSystem', 'GeographicCoordinateSystem', 'GeocentricCoordinateSystem', 'AxisNames') _required = ('ProjectedCoordinateSystem', 'GeographicCoordinateSystem', 'GeocentricCoordinateSystem', 'AxisNames') _collections_tags = {'AxisNames': {'array': False, 'child_tag': 'AxisName'}} # Descriptor ProjectedCoordinateSystem = SerializableDescriptor( 'ProjectedCoordinateSystem', ProjectedCoordinateSystemType, _required, strict=DEFAULT_STRICT, docstring='') # type: ProjectedCoordinateSystemType GeographicCoordinateSystem = SerializableDescriptor( 'GeographicCoordinateSystem', GeographicCoordinateSystemType, _required, strict=DEFAULT_STRICT, docstring='') # type: GeographicCoordinateSystemType GeocentricCoordinateSystem = SerializableDescriptor( 'GeocentricCoordinateSystem', GeocentricCoordinateSystemType, _required, strict=DEFAULT_STRICT, docstring='') # type: GeocentricCoordinateSystemType AxisNames = StringListDescriptor( 'AxisNames', _required, strict=DEFAULT_STRICT, docstring='') # type: List[str] def __init__(self, ProjectedCoordinateSystem=None, GeographicCoordinateSystem=None, GeocentricCoordinateSystem=None, AxisNames=None, **kwargs): """ Parameters ---------- ProjectedCoordinateSystem : ProjectedCoordinateSystemType GeographicCoordinateSystem : GeographicCoordinateSystemType GeocentricCoordinateSystem : GeocentricCoordinateSystemType AxisNames : List[str] kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.ProjectedCoordinateSystem = ProjectedCoordinateSystem self.GeographicCoordinateSystem = GeographicCoordinateSystem self.GeocentricCoordinateSystem = GeocentricCoordinateSystem self.AxisNames = AxisNames super(ReferenceSystemType, self).__init__(**kwargs) class AnnotationObjectType(Serializable): """ Geometrical representation of the annotation. Only one of the geometry elements should be populated. It will not be enforced, but the order of preference will be `('Point', 'Line', 'LinearRing', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon')`. Note that PolyhedralSurface is not currently supported. """ _fields = ('Point', 'Line', 'LinearRing', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon') _choice = ({'required': True, 'collection': _fields}, ) def __init__(self, Point=None, Line=None, LinearRing=None, Polygon=None, MultiPoint=None, MultiLineString=None, MultiPolygon=None, **kwargs): """ Parameters ---------- Point : sarpy.geometry.geometry_elements.Point|numpy.array|list|tuple Line : sarpy.geometry.geometry_elements.LineString|numpy.array|list|tuple LinearRing : sarpy.geometry.geometry_elements.LinearRing|numpy.array|list|tuple Polygon : sarpy.geometry.geometry_elements.Polygon|list MultiPoint : sarpy.geometry.geometry_elements.MultiPoint|list MultiLineString : sarpy.geometry.geometry_elements.MultiLineString|list MultiPolygon : sarpy.geometry.geometry_elements.MultiPolygon|list kwargs """ self._Point = None self._Line = None self._LinearRing = None self._Polygon = None self._MultiPoint = None self._MultiLineString = None self._MultiPolygon = None if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] if Point is not None: self.Point = Point elif Line is not None: self.Line = Line elif LinearRing is not None: self.LinearRing = LinearRing elif Polygon is not None: self.Polygon = Polygon elif MultiPoint is not None: self.MultiPoint = MultiPoint elif MultiLineString is not None: self.MultiLineString = MultiLineString elif MultiPolygon is not None: self.MultiPolygon = MultiPolygon else: logger.error( "One of (Point, Line, LinearRing, Polygon, MultiPoint, MultiLineString, MultiPolygon)\n\t" "should have been provided to the AnnotationObjectType constructor.") super(AnnotationObjectType, self).__init__(**kwargs) @property def GeometryType(self): """ str: **READ ONLY** The type of geometric element which is set, from ('Point', 'Line', 'LinearRing', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon') """ for attribute in self._choice[0]['collection']: if getattr(self, attribute) is not None: return attribute return None @property def Point(self): """ None|sarpy.geometry.geometry_elements.Point: The point. """ return self._Point @Point.setter def Point(self, value): if value is None: self._Point = None elif isinstance(value, (numpy.ndarray, list, tuple)): self._Point = PointType(coordinates=value) elif isinstance(value, PointType): self._Point = value else: raise TypeError( 'Point requires and instance of sarpy.geometry.geometry_elements.Point, ' 'got {}'.format(type(value))) @property def Line(self): """ None|sarpy.geometry.geometry_elements.LineString: The line. """ return self._Line @Line.setter def Line(self, value): if value is None: self._Line = None elif isinstance(value, (numpy.ndarray, list, tuple)): self._Line = LineStringType(coordinates=value) elif isinstance(value, LineStringType): self._Line = value else: raise TypeError( 'Line requires and instance of sarpy.geometry.geometry_elements.LineString, ' 'got {}'.format(type(value))) @property def LinearRing(self): """ None|sarpy.geometry.geometry_elements.LinearRing: The linear ring. """ return self._LinearRing @LinearRing.setter def LinearRing(self, value): if value is None: self._LinearRing = None elif isinstance(value, (numpy.ndarray, list, tuple)): self._LinearRing = LinearRingType(coordinates=value) elif isinstance(value, LinearRingType): self._LinearRing = value else: raise TypeError( 'LinearRing requires and instance of sarpy.geometry.geometry_elements.LinearRing, ' 'got {}'.format(type(value))) @property def Polygon(self): """ None|sarpy.geometry.geometry_elements.Polygon: The polygon. """ return self._Polygon @Polygon.setter def Polygon(self, value): if value is None: self._Polygon = None elif isinstance(value, list): self._Polygon = PolygonType(coordinates=value) elif isinstance(value, PolygonType): self._Polygon = value else: raise TypeError( 'Polygon requires and instance of sarpy.geometry.geometry_elements.Polygon, ' 'got {}'.format(type(value))) @property def MultiPoint(self): """ None|sarpy.geometry.geometry_elements.MultiPoint: The multipoint. """ return self._MultiPoint @MultiPoint.setter def MultiPoint(self, value): if value is None: self._MultiPoint = None elif isinstance(value, list): self._MultiPoint = MultiPointType(coordinates=value) elif isinstance(value, MultiPointType): self._MultiPoint = value else: raise TypeError( 'MultiPoint requires and instance of sarpy.geometry.geometry_elements.MultiPoint, ' 'got {}'.format(type(value))) @property def MultiLineString(self): """ None|sarpy.geometry.geometry_elements.MultiLineString: The multi-linestring. """ return self._MultiLineString @MultiLineString.setter def MultiLineString(self, value): if value is None: self._MultiLineString = None elif isinstance(value, list): self._MultiLineString = MultiLineStringType(coordinates=value) elif isinstance(value, MultiLineStringType): self._MultiLineString = value else: raise TypeError( 'MultiLineString requires and instance of sarpy.geometry.geometry_elements.MultiLineString, ' 'got {}'.format(type(value))) @property def MultiPolygon(self): """ None|sarpy.geometry.geometry_elements.MultiPolygon: The multi-polygon. """ return self._MultiPolygon @MultiPolygon.setter def MultiPolygon(self, value): if value is None: self._MultiPolygon = None elif isinstance(value, list): self._MultiPolygon = MultiPolygonType(coordinates=value) elif isinstance(value, MultiPolygonType): self._MultiPolygon = value else: raise TypeError( 'MultiPolygon requires and instance of sarpy.geometry.geometry_elements.MultiPolygon, ' 'got {}'.format(type(value))) def to_dict(self, check_validity=False, strict=DEFAULT_STRICT, exclude=()): for attr in self._fields: val = getattr(self, attr) if val is not None: return val.to_dict() return {} @classmethod def from_dict(cls, input_dict): typ = input_dict.get('type', None) if typ is None: return cls() elif typ == 'Point': return cls(Point=PointType.from_dict(input_dict)) elif typ == 'LineString': return cls(Line=LineStringType.from_dict(input_dict)) elif typ == 'LinearRing': return cls(LinearRing=LinearRingType.from_dict(input_dict)) elif typ == 'Polygon': return cls(Polygon=PolygonType.from_dict(input_dict)) elif typ == 'MultiPoint': return cls(MultiPoint=MultiPointType.from_dict(input_dict)) elif typ == 'MultiLineString': return cls(MultiLineString=MultiLineStringType.from_dict(input_dict)) elif typ == 'MultiPolygon': return cls(MultiPolygon=MultiPolygonType.from_dict(input_dict)) else: logger.error( 'AnnotationObjectType got unsupported input dictionary {}.\n\t' 'Returning None.'.format(input_dict)) return None @staticmethod def _serialize_point(coords, doc, tag, parent): if len(coords) < 2: raise ValueError('coords must have at least two elements') fmt_func = '{0:0.17E}'.format node = create_new_node(doc, tag, parent=parent) create_text_node(doc, 'sfa:X', fmt_func(coords[0]), parent=node) create_text_node(doc, 'sfa:Y', fmt_func(coords[1]), parent=node) if len(coords) > 2: create_text_node(doc, 'sfa:Z', fmt_func(coords[2]), parent=node) if len(coords) > 3: create_text_node(doc, 'sfa:M', fmt_func(coords[3]), parent=node) def _serialize_line(self, coords, doc, tag, parent): node = create_new_node(doc, tag, parent=parent) for entry in coords: self._serialize_point(entry, doc, 'sfa:Vertex', node) def _serialize_polygon(self, coords, doc, tag, parent): node = create_new_node(doc, tag, parent=parent) for entry in coords: self._serialize_line(entry, doc, 'sfa:Ring', node) def _serialize_multilinestring(self, coords, doc, tag, parent): node = create_new_node(doc, tag, parent=parent) for entry in coords: self._serialize_line(entry, doc, 'sfa:Element', node) def _serialize_multipolygon(self, coords, doc, tag, parent): node = create_new_node(doc, tag, parent=parent) for entry in coords: self._serialize_polygon(entry, doc, 'sfa:Element', node) def to_node(self, doc, tag, ns_key=None, parent=None, check_validity=False, strict=DEFAULT_STRICT, exclude=()): if parent is None: parent = doc.getroot() if ns_key is None: node = create_new_node(doc, tag, parent=parent) else: node = create_new_node(doc, '{}:{}'.format(ns_key, tag), parent=parent) typ = self.GeometryType if typ is None: return node coords = getattr(self, typ).get_coordinate_list() if typ == 'Point': self._serialize_point(coords, doc, 'sfa:Point', node) elif typ == 'Line': self._serialize_line(coords, doc, 'sfa:Line', node) elif typ == 'LinearRing': self._serialize_line(coords, doc, 'sfa:LinearRing', node) elif typ == 'Polygon': self._serialize_polygon(coords, doc, 'sfa:Polygon', node) elif typ == 'MultiPoint': self._serialize_line(coords, doc, 'sfa:MultiPoint', node) elif typ == 'MultiLineString': self._serialize_multilinestring(coords, doc, 'sfa:MultiLineString', node) elif typ == 'MultiPolygon': self._serialize_multipolygon(coords, doc, 'sfa:MultiPolygon', node) else: raise ValueError('Unsupported serialization type {}'.format(typ)) return node @staticmethod def _get_value(node, tag, xml_ns, ns_key): t_node = find_first_child(node, tag, xml_ns, ns_key) if t_node is None: return None else: return float(get_node_value(t_node)) @classmethod def _extract_point(cls, node, xml_ns): out = [cls._get_value(node, 'X', xml_ns, 'sfa'), cls._get_value(node, 'Y', xml_ns, 'sfa')] z = cls._get_value(node, 'Z', xml_ns, 'sfa') if z in None: return out out.append(z) m = cls._get_value(node, 'M', xml_ns, 'sfa') if m in None: return out out.append(m) return out @classmethod def _extract_line(cls, node, xml_ns, tag='Vertex'): v_nodes = find_children(node, tag, xml_ns, 'sfa') return [cls._extract_point(v_node, xml_ns) for v_node in v_nodes] @classmethod def _extract_polygon(cls, node, xml_ns, tag='Ring'): v_nodes = find_children(node, tag, xml_ns, 'sfa') return [cls._extract_line(v_node, xml_ns, tag='Vertex') for v_node in v_nodes] @classmethod def _deserialize_point(cls, node, xml_ns, tag='Point'): point_node = find_first_child(node, tag, xml_ns, 'sfa') if point_node is None: return None return cls._extract_point(point_node, xml_ns) @classmethod def _deserialize_line(cls, node, xml_ns, tag='Line'): line_node = find_first_child(node, tag, xml_ns, 'sfa') if line_node is None: return None return cls._extract_line(line_node, xml_ns, tag='Vertex') @classmethod def _deserialize_polygon(cls, node, xml_ns, tag='Polygon'): poly_node = find_first_child(node, tag, xml_ns, 'sfa') if poly_node is None: return None return cls._extract_polygon(poly_node, xml_ns, tag='Ring') @classmethod def _deserialize_multilinestring(cls, node, xml_ns, tag='MultiLineString'): mls_node = find_first_child(node, tag, xml_ns, 'sfa') if mls_node is None: return None ls_nodes = find_children(mls_node, 'Element', xml_ns, 'sfa') return [cls._extract_line(ls_node, xml_ns, tag='Vertex') for ls_node in ls_nodes] @classmethod def _deserialize_multipolygon(cls, node, xml_ns, tag='MultiPolygon'): mp_node = find_first_child(node, tag, xml_ns, 'sfa') if mp_node is None: return None p_nodes = find_children(mp_node, 'Element', xml_ns, 'sfa') return [cls._extract_polygon(p_node, xml_ns, tag='Ring') for p_node in p_nodes] @classmethod def from_node(cls, node, xml_ns, ns_key=None, kwargs=None): if xml_ns is None or 'sfa' not in xml_ns: raise ValueError('xml_ns must contain an entry for key "sfa"') coords = cls._deserialize_point(node, xml_ns, 'Point') if coords is not None: return cls(Point=PointType(coordinates=coords)) coords = cls._deserialize_line(node, xml_ns, tag='Line') if coords is not None: return cls(Line=LineStringType(coordinates=coords)) coords = cls._deserialize_line(node, xml_ns, tag='LinearRing') if coords is not None: return cls(LinearRing=LinearRingType(coordinates=coords)) coords = cls._deserialize_polygon(node, xml_ns, tag='Polygon') if coords is not None: return cls(Polygon=PolygonType(coordinates=coords)) coords = cls._deserialize_line(node, xml_ns, tag='MultiPoint') if coords is not None: return cls(MultiPoint=MultiPointType(coordinates=coords)) coords = cls._deserialize_multilinestring(node, xml_ns, tag='MultiLineString') if coords is not None: return cls(MultiLineString=MultiLineStringType(coordinates=coords)) coords = cls._deserialize_multipolygon(node, xml_ns, tag='MultiPolygon') if coords is not None: return cls(MultiPolygon=MultiPolygonType(coordinates=coords)) return cls() class AnnotationType(Serializable): """ The annotation type. """ _fields = ('Identifier', 'SpatialReferenceSystem', 'Objects') _required = ('Identifier', 'Objects') _collections_tags = {'Objects': {'array': False, 'child_tag': 'Object'}} # Descriptor Identifier = StringDescriptor( 'Identifier', _required, strict=DEFAULT_STRICT, docstring='') # type: str SpatialReferenceSystem = SerializableDescriptor( 'SpatialReferenceSystem', ReferenceSystemType, _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, ReferenceSystemType] Objects = SerializableListDescriptor( 'Objects', AnnotationObjectType, _collections_tags, _required, strict=DEFAULT_STRICT, docstring='') # type: List[AnnotationObjectType] def __init__(self, Identifier=None, SpatialReferenceSystem=None, Objects=None, **kwargs): """ Parameters ---------- Identifier : str SpatialReferenceSystem : None|ReferenceSystemType Objects : List[AnnotationObjectType] kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Identifier = Identifier self.SpatialReferenceSystem = SpatialReferenceSystem self.Objects = Objects super(AnnotationType, self).__init__(**kwargs) class AnnotationsType(Serializable): """ The list of annotations. """ _fields = ('Annotations', ) _required = ('Annotations', ) _collections_tags = {'Annotations': {'array': False, 'child_tag': 'Annotation'}} # Descriptor Annotations = SerializableListDescriptor( 'Annotations', AnnotationType, _collections_tags, _required, strict=DEFAULT_STRICT, docstring='') # type: List[AnnotationType] def __init__(self, Annotations=None, **kwargs): """ Parameters ---------- Annotations : List[AnnotationType] kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Annotations = Annotations super(AnnotationsType, self).__init__(**kwargs) def __len__(self): return len(self.Annotations) def __getitem__(self, item): return self.Annotations[item]
30,854
34.303204
118
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/SIDD.py
""" The SIDDType 2.0 definition. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" import logging from typing import Union, Tuple from collections import OrderedDict from copy import deepcopy import numpy from sarpy.io.xml.base import Serializable, parse_xml_from_string, parse_xml_from_file from sarpy.io.xml.descriptors import SerializableDescriptor from sarpy.geometry import point_projection from sarpy.io.product.sidd_schema import get_specification_identifier, \ get_urn_details, validate_xml_ns from .base import DEFAULT_STRICT from .ProductCreation import ProductCreationType from .Display import ProductDisplayType from .GeoData import GeoDataType from .Measurement import MeasurementType from .ExploitationFeatures import ExploitationFeaturesType from .DownstreamReprocessing import DownstreamReprocessingType from .Compression import CompressionType from .DigitalElevationData import DigitalElevationDataType from .ProductProcessing import ProductProcessingType from .Annotations import AnnotationsType from ..sidd1_elements.SIDD import SIDDType as SIDDType1 from .blocks import ErrorStatisticsType, RadiometricType, MatchInfoType logger = logging.getLogger(__name__) ############ # namespace validate and definition of required entries in the namespace dictionary _SIDD_SPECIFICATION_IDENTIFIER = get_specification_identifier() _SIDD_URN = 'urn:SIDD:2.0.0' _sidd_details = get_urn_details(_SIDD_URN) _SIDD_SPECIFICATION_VERSION = _sidd_details['version'] _SIDD_SPECIFICATION_DATE = _sidd_details['date'] _ISM_URN = _sidd_details['ism_urn'] _SFA_URN = _sidd_details['sfa_urn'] _SICOMMON_URN = _sidd_details['sicommon_urn'] ########## # The SIDD object class SIDDType(Serializable): """ The root element of the SIDD 2.0 document. """ _fields = ( 'ProductCreation', 'Display', 'GeoData', 'Measurement', 'ExploitationFeatures', 'DownstreamReprocessing', 'ErrorStatistics', 'Radiometric', 'MatchInfo', 'Compression', 'DigitalElevationData', 'ProductProcessing', 'Annotations') _required = ( 'ProductCreation', 'Display', 'GeoData', 'Measurement', 'ExploitationFeatures') # Descriptor ProductCreation = SerializableDescriptor( 'ProductCreation', ProductCreationType, _required, strict=DEFAULT_STRICT, docstring='Information related to processor, classification, and product type.') # type: ProductCreationType Display = SerializableDescriptor( 'Display', ProductDisplayType, _required, strict=DEFAULT_STRICT, docstring='Contains information on the parameters needed to display the product in ' 'an exploitation tool.') # type: ProductDisplayType GeoData = SerializableDescriptor( 'GeoData', GeoDataType, _required, strict=DEFAULT_STRICT, docstring='Contains generic and extensible targeting and geographic region ' 'information.') # type: GeoDataType Measurement = SerializableDescriptor( 'Measurement', MeasurementType, _required, strict=DEFAULT_STRICT, docstring='Contains the metadata necessary for performing measurements.') # type: MeasurementType ExploitationFeatures = SerializableDescriptor( 'ExploitationFeatures', ExploitationFeaturesType, _required, strict=DEFAULT_STRICT, docstring='Computed metadata regarding the input collections and ' 'final product.') # type: ExploitationFeaturesType DownstreamReprocessing = SerializableDescriptor( 'DownstreamReprocessing', DownstreamReprocessingType, _required, strict=DEFAULT_STRICT, docstring='Metadata describing any downstream processing of the ' 'product.') # type: Union[None, DownstreamReprocessingType] ErrorStatistics = SerializableDescriptor( 'ErrorStatistics', ErrorStatisticsType, _required, strict=DEFAULT_STRICT, docstring='Error statistics passed through from the SICD metadata.') # type: Union[None, ErrorStatisticsType] Radiometric = SerializableDescriptor( 'Radiometric', RadiometricType, _required, strict=DEFAULT_STRICT, docstring='Radiometric information about the product.') # type: Union[None, RadiometricType] MatchInfo = SerializableDescriptor( 'MatchInfo', MatchInfoType, _required, strict=DEFAULT_STRICT, docstring='Information about other collections that are matched to the current ' 'collection. The current collection is the collection from which this ' 'SIDD product was generated.') # type: MatchInfoType Compression = SerializableDescriptor( 'Compression', CompressionType, _required, strict=DEFAULT_STRICT, docstring='Contains information regarding any compression that has occurred ' 'to the image data.') # type: CompressionType DigitalElevationData = SerializableDescriptor( 'DigitalElevationData', DigitalElevationDataType, _required, strict=DEFAULT_STRICT, docstring='This describes any Digital ElevationData included with ' 'the SIDD product.') # type: DigitalElevationDataType ProductProcessing = SerializableDescriptor( 'ProductProcessing', ProductProcessingType, _required, strict=DEFAULT_STRICT, docstring='Contains metadata related to algorithms used during ' 'product generation.') # type: ProductProcessingType Annotations = SerializableDescriptor( 'Annotations', AnnotationsType, _required, strict=DEFAULT_STRICT, docstring='List of annotations for the imagery.') # type: AnnotationsType def __init__(self, ProductCreation=None, Display=None, GeoData=None, Measurement=None, ExploitationFeatures=None, DownstreamReprocessing=None, ErrorStatistics=None, Radiometric=None, MatchInfo=None, Compression=None, DigitalElevationData=None, ProductProcessing=None, Annotations=None, **kwargs): """ Parameters ---------- ProductCreation : ProductCreationType Display : ProductDisplayType GeoData : GeoDataType Measurement : MeasurementType ExploitationFeatures : ExploitationFeaturesType DownstreamReprocessing : None|DownstreamReprocessingType ErrorStatistics : None|ErrorStatisticsType Radiometric : None|RadiometricType MatchInfo : None|MatchInfoType Compression : None|CompressionType DigitalElevationData : None|DigitalElevationDataType ProductProcessing : None|ProductProcessingType Annotations : None|AnnotationsType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] nitf = kwargs.get('_NITF', {}) if not isinstance(nitf, dict): raise TypeError('Provided NITF options are required to be in dictionary form.') self._NITF = nitf self._coa_projection = None self.ProductCreation = ProductCreation self.Display = Display self.GeoData = GeoData self.Measurement = Measurement self.ExploitationFeatures = ExploitationFeatures self.DownstreamReprocessing = DownstreamReprocessing self.ErrorStatistics = ErrorStatistics self.Radiometric = Radiometric self.MatchInfo = MatchInfo self.Compression = Compression self.DigitalElevationData = DigitalElevationData self.ProductProcessing = ProductProcessing self.Annotations = Annotations super(SIDDType, self).__init__(**kwargs) @property def coa_projection(self): """ The COA Projection object, if previously defined through using :func:`define_coa_projection`. Returns ------- None|sarpy.geometry.point_projection.COAProjection """ return self._coa_projection @property def NITF(self): """ Optional dictionary of NITF header information, pertains only to subsequent SIDD file writing. Returns ------- Dict """ return self._NITF def can_project_coordinates(self): """ Determines whether the necessary elements are populated to permit projection between image and physical coordinates. If False, then the (first discovered) reason why not will be logged at error level. Returns ------- bool """ if self._coa_projection is not None: return True if self.Measurement.ProjectionType != 'PlaneProjection': logger.error( 'Formulating a projection is only supported for PlaneProjection, ' 'got {}.'.format(self.Measurement.ProjectionType)) return False return True def define_coa_projection(self, delta_arp=None, delta_varp=None, range_bias=None, adj_params_frame='ECF', override=True): """ Define the COAProjection object. Parameters ---------- delta_arp : None|numpy.ndarray|list|tuple ARP position adjustable parameter (ECF, m). Defaults to 0 in each coordinate. delta_varp : None|numpy.ndarray|list|tuple VARP position adjustable parameter (ECF, m/s). Defaults to 0 in each coordinate. range_bias : float|int Range bias adjustable parameter (m), defaults to 0. adj_params_frame : str One of ['ECF', 'RIC_ECF', 'RIC_ECI'], specifying the coordinate frame used for expressing `delta_arp` and `delta_varp` parameters. override : bool should we redefine, if it is previously defined? Returns ------- None """ if not self.can_project_coordinates(): logger.error('The COAProjection object cannot be defined.') return if self._coa_projection is not None and not override: return self._coa_projection = point_projection.COAProjection.from_sidd( self, delta_arp=delta_arp, delta_varp=delta_varp, range_bias=range_bias, adj_params_frame=adj_params_frame) def project_ground_to_image(self, coords, **kwargs): """ Transforms a 3D ECF point to pixel (row/column) coordinates. This is implemented in accordance with the SICD Image Projections Description Document. **Really Scene-To-Image projection.**" Parameters ---------- coords : numpy.ndarray|tuple|list ECF coordinate to map to scene coordinates, of size `N x 3`. kwargs The keyword arguments for the :func:`sarpy.geometry.point_projection.ground_to_image` method. Returns ------- Tuple[numpy.ndarray, float, int] * `image_points` - the determined image point array, of size `N x 2`. Following the SICD convention, he upper-left pixel is [0, 0]. * `delta_gpn` - residual ground plane displacement (m). * `iterations` - the number of iterations performed. See Also -------- sarpy.geometry.point_projection.ground_to_image """ if 'use_structure_coa' not in kwargs: kwargs['use_structure_coa'] = True return point_projection.ground_to_image(coords, self, **kwargs) def project_ground_to_image_geo(self, coords, ordering='latlong', **kwargs): """ Transforms a 3D Lat/Lon/HAE point to pixel (row/column) coordinates. This is implemented in accordance with the SICD Image Projections Description Document. **Really Scene-To-Image projection.**" Parameters ---------- coords : numpy.ndarray|tuple|list ECF coordinate to map to scene coordinates, of size `N x 3`. ordering : str If 'longlat', then the input is `[longitude, latitude, hae]`. Otherwise, the input is `[latitude, longitude, hae]`. Passed through to :func:`sarpy.geometry.geocoords.geodetic_to_ecf`. kwargs The keyword arguments for the :func:`sarpy.geometry.point_projection.ground_to_image_geo` method. Returns ------- Tuple[numpy.ndarray, float, int] * `image_points` - the determined image point array, of size `N x 2`. Following the SICD convention, he upper-left pixel is [0, 0]. * `delta_gpn` - residual ground plane displacement (m). * `iterations` - the number of iterations performed. See Also -------- sarpy.geometry.point_projection.ground_to_image_geo """ if 'use_structure_coa' not in kwargs: kwargs['use_structure_coa'] = True return point_projection.ground_to_image_geo(coords, self, ordering=ordering, **kwargs) def project_image_to_ground(self, im_points, projection_type='HAE', **kwargs): """ Transforms image coordinates to ground plane ECF coordinate via the algorithm(s) described in SICD Image Projections document. Parameters ---------- im_points : numpy.ndarray|list|tuple the image coordinate array projection_type : str One of `['PLANE', 'HAE', 'DEM']`. Type `DEM` is a work in progress. kwargs The keyword arguments for the :func:`sarpy.geometry.point_projection.image_to_ground` method. Returns ------- numpy.ndarray Ground Plane Point (in ECF coordinates) corresponding to the input image coordinates. See Also -------- sarpy.geometry.point_projection.image_to_ground """ if 'use_structure_coa' not in kwargs: kwargs['use_structure_coa'] = True return point_projection.image_to_ground( im_points, self, projection_type=projection_type, **kwargs) def project_image_to_ground_geo(self, im_points, ordering='latlong', projection_type='HAE', **kwargs): """ Transforms image coordinates to ground plane WGS-84 coordinate via the algorithm(s) described in SICD Image Projections document. Parameters ---------- im_points : numpy.ndarray|list|tuple the image coordinate array projection_type : str One of `['PLANE', 'HAE', 'DEM']`. Type `DEM` is a work in progress. ordering : str Determines whether return is ordered as `[lat, long, hae]` or `[long, lat, hae]`. Passed through to :func:`sarpy.geometry.geocoords.ecf_to_geodetic`. kwargs The keyword arguments for the :func:`sarpy.geometry.point_projection.image_to_ground_geo` method. Returns ------- numpy.ndarray Ground Plane Point (in ECF coordinates) corresponding to the input image coordinates. See Also -------- sarpy.geometry.point_projection.image_to_ground_geo """ if 'use_structure_coa' not in kwargs: kwargs['use_structure_coa'] = True return point_projection.image_to_ground_geo( im_points, self, ordering=ordering, projection_type=projection_type, **kwargs) @staticmethod def get_xmlns_collection(): """ Gets the correct SIDD 2.0 dictionary of xml namespace details. Returns ------- dict """ return OrderedDict([ ('xmlns', _SIDD_URN), ('xmlns:sicommon', _SICOMMON_URN), ('xmlns:sfa', _SFA_URN), ('xmlns:ism', _ISM_URN)]) @staticmethod def get_des_details(): """ Gets the correct SIDD 2.0 DES subheader details. Returns ------- dict """ return OrderedDict([ ('DESSHSI', _SIDD_SPECIFICATION_IDENTIFIER), ('DESSHSV', _SIDD_SPECIFICATION_VERSION), ('DESSHSD', _SIDD_SPECIFICATION_DATE), ('DESSHTN', _SIDD_URN)]) @classmethod def from_node(cls, node, xml_ns, ns_key='default', kwargs=None): if ns_key is None: raise ValueError('ns_key must be defined.') if ns_key not in xml_ns: raise ValueError('ns_key {} is not in the xml namespace'.format(ns_key)) if xml_ns[ns_key].startswith('urn:SIDD:1.'): return SIDDType1.from_node(node, xml_ns, ns_key=ns_key, kwargs=kwargs) valid_ns = validate_xml_ns(xml_ns, ns_key) if not xml_ns[ns_key].startswith('urn:SIDD:2.'): raise ValueError('Cannot use urn {} for SIDD version 2.0'.format(xml_ns[ns_key])) if not valid_ns: logger.warning( 'SIDD namespace validation failed,\n\t' 'which may lead to subsequent deserialization failures') return super(SIDDType, cls).from_node(node, xml_ns, ns_key=ns_key, kwargs=kwargs) def to_xml_bytes(self, urn=None, tag='SIDD', check_validity=False, strict=DEFAULT_STRICT): if urn is None: urn = self.get_xmlns_collection() return super(SIDDType, self).to_xml_bytes(urn=urn, tag=tag, check_validity=check_validity, strict=strict) def to_xml_string(self, urn=None, tag='SIDD', check_validity=False, strict=DEFAULT_STRICT): return self.to_xml_bytes(urn=urn, tag=tag, check_validity=check_validity, strict=strict).decode('utf-8') def copy(self): """ Provides a deep copy. Returns ------- SIDDType """ out = super(SIDDType, self).copy() out._NITF = deepcopy(self._NITF) return out @classmethod def from_xml_file(cls, file_path): """ Construct the sidd object from a stand-alone xml file path. Parameters ---------- file_path : str Returns ------- SIDDType """ root_node, xml_ns = parse_xml_from_file(file_path) ns_key = 'default' if 'default' in xml_ns else None return cls.from_node(root_node, xml_ns=xml_ns, ns_key=ns_key) @classmethod def from_xml_string(cls, xml_string): """ Construct the sidd object from a xml string. Parameters ---------- xml_string : str|bytes Returns ------- SIDDType """ root_node, xml_ns = parse_xml_from_string(xml_string) ns_key = 'default' if 'default' in xml_ns else None return cls.from_node(root_node, xml_ns=xml_ns, ns_key=ns_key)
18,656
38.360759
118
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/ProductCreation.py
""" The ProductCreationType definition. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" import logging from typing import Union from datetime import datetime import numpy from sarpy.io.xml.base import Serializable, ParametersCollection from sarpy.io.xml.descriptors import SerializableDescriptor, IntegerDescriptor, \ StringDescriptor, StringEnumDescriptor, DateTimeDescriptor, ParametersDescriptor from sarpy.io.complex.sicd_elements.SICD import SICDType from .base import DEFAULT_STRICT logger = logging.getLogger(__name__) def extract_classification_from_sicd(sicd): """ Extract a SIDD style classification from a SICD classification string. Parameters ---------- sicd : SICDType Returns ------- str """ if not isinstance(sicd, SICDType): raise TypeError('Requires SICDType instance, got type {}'.format(type(sicd))) c_str = sicd.CollectionInfo.Classification.upper().split('//')[0].strip() clas = None if c_str.startswith('UNCLASS') or c_str == 'U': clas = 'U' elif c_str.startswith('CONF') or c_str == 'C': clas = 'C' elif c_str.startswith('TOP ') or c_str == 'TS': clas = 'TS' elif c_str.startswith('SEC') or c_str == 'S': clas = 'S' elif c_str == 'FOUO' or c_str.startswith('REST') or c_str == 'R': clas = 'R' else: logger.critical( 'Unclear how to extract classification code for classification string {}.\n\t' 'It will default to unclassified, and should be set appropriately.'.format(c_str)) return clas class ProcessorInformationType(Serializable): """ Details regarding the processor. """ _fields = ('Application', 'ProcessingDateTime', 'Site', 'Profile') _required = ('Application', 'ProcessingDateTime', 'Site') # descriptors Application = StringDescriptor( 'Application', _required, strict=DEFAULT_STRICT, docstring='Name and version of the application used to create the image.') # type: str ProcessingDateTime = DateTimeDescriptor( 'ProcessingDateTime', _required, strict=DEFAULT_STRICT, numpy_datetime_units='us', docstring='Date and time the image creation application processed the image (UTC).') # type: numpy.datetime64 Site = StringDescriptor( 'Site', _required, strict=DEFAULT_STRICT, docstring='The creation site of this SICD product.') # type: str Profile = StringDescriptor( 'Profile', _required, strict=DEFAULT_STRICT, docstring='Identifies what profile was used to create this SICD product.') # type: str def __init__(self, Application=None, ProcessingDateTime=None, Site=None, Profile=None, **kwargs): """ Parameters ---------- Application : str ProcessingDateTime : numpy.datetime64|datetime|date|str Site : str Profile : str kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Application = Application self.ProcessingDateTime = ProcessingDateTime self.Site = Site self.Profile = Profile super(ProcessorInformationType, self).__init__(**kwargs) class ProductClassificationType(Serializable): """ The overall classification of the product. """ _fields = ( 'DESVersion', 'resourceElement', 'createDate', 'compliesWith', 'ISMCATCESVersion', 'classification', 'ownerProducer', 'SCIcontrols', 'SARIdentifier', 'disseminationControls', 'FGIsourceOpen', 'FGIsourceProtected', 'releasableTo', 'nonICmarkings', 'classifiedBy', 'compilationReason', 'derivativelyClassifiedBy', 'classificationReason', 'nonUSControls', 'derivedFrom', 'declassDate', 'declassEvent', 'declassException', 'typeOfExemptedSource', 'dateOfExemptedSource', 'SecurityExtensions') _required = ( 'DESVersion', 'createDate', 'classification', 'ownerProducer', 'compliesWith', 'ISMCATCESVersion') _collections_tags = {'SecurityExtensions': {'array': False, 'child_tag': 'SecurityExtension'}} _set_as_attribute = ( 'DESVersion', 'resourceElement', 'createDate', 'compliesWith', 'ISMCATCESVersion', 'classification', 'ownerProducer', 'SCIcontrols', 'SARIdentifier', 'disseminationControls', 'FGIsourceOpen', 'FGIsourceProtected', 'releasableTo', 'nonICmarkings', 'classifiedBy', 'compilationReason', 'derivativelyClassifiedBy', 'classificationReason', 'nonUSControls', 'derivedFrom', 'declassDate', 'declassEvent', 'declassException', 'typeOfExemptedSource', 'dateOfExemptedSource') _child_xml_ns_key = {the_field: 'ism' for the_field in _fields if the_field != 'SecurityExtensions'} # Descriptor DESVersion = IntegerDescriptor( 'DESVersion', _required, strict=DEFAULT_STRICT, default_value=13, docstring='The version number of the DES. Should there be multiple specified in an instance document ' 'the one at the root node is the one that will apply to the entire document.') # type: int createDate = StringDescriptor( 'createDate', _required, strict=DEFAULT_STRICT, docstring='This should be a date of format :code:`YYYY-MM-DD`, but this is not checked.') # type: str compliesWith = StringEnumDescriptor( 'compliesWith', ('USGov', 'USIC', 'USDOD', 'OtherAuthority'), _required, strict=DEFAULT_STRICT, default_value='USGov', docstring='The ISM rule sets with which the document may complies.') # type: Union[None, str] ISMCATCESVersion = StringDescriptor( 'ISMCATCESVersion', _required, strict=DEFAULT_STRICT, default_value='201903', docstring='') # type: Union[None, str] classification = StringEnumDescriptor( 'classification', ('U', 'C', 'R', 'S', 'TS'), _required, strict=DEFAULT_STRICT, docstring='') # type: str ownerProducer = StringDescriptor( 'ownerProducer', _required, strict=DEFAULT_STRICT, # default_value='USA', docstring='') # type: str SCIcontrols = StringDescriptor( 'SCIcontrols', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] SARIdentifier = StringDescriptor( 'SARIdentifier', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] disseminationControls = StringDescriptor( 'disseminationControls', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] FGIsourceOpen = StringDescriptor( 'FGIsourceOpen', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] FGIsourceProtected = StringDescriptor( 'FGIsourceProtected', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] releasableTo = StringDescriptor( 'releasableTo', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] nonICmarkings = StringDescriptor( 'nonICmarkings', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] classifiedBy = StringDescriptor( 'classifiedBy', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] compilationReason = StringDescriptor( 'compilationReason', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] derivativelyClassifiedBy = StringDescriptor( 'derivativelyClassifiedBy', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] classificationReason = StringDescriptor( 'classificationReason', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] nonUSControls = StringDescriptor( 'nonUSControls', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] derivedFrom = StringDescriptor( 'derivedFrom', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] declassDate = StringDescriptor( 'declassDate', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] declassEvent = StringDescriptor( 'declassEvent', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] declassException = StringDescriptor( 'declassException', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] typeOfExemptedSource = StringDescriptor( 'typeOfExemptedSource', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] dateOfExemptedSource = StringDescriptor( 'dateOfExemptedSource', _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, str] SecurityExtensions = ParametersDescriptor( 'SecurityExtensions', _collections_tags, _required, strict=DEFAULT_STRICT, docstring='Extensible parameters used to support profile-specific needs related to ' 'product security.') # type: ParametersCollection def __init__(self, DESVersion=13, createDate=None, compliesWith='USGov', ISMCATCESVersion='201903', classification='U', ownerProducer='USA', SCIcontrols=None, SARIdentifier=None, disseminationControls=None, FGIsourceOpen=None, FGIsourceProtected=None, releasableTo=None, nonICmarkings=None, classifiedBy=None, compilationReason=None, derivativelyClassifiedBy=None, classificationReason=None, nonUSControls=None, derivedFrom=None, declassDate=None, declassEvent=None, declassException=None, typeOfExemptedSource=None, dateOfExemptedSource=None, SecurityExtensions=None, **kwargs): """ Parameters ---------- DESVersion : int createDate : str compliesWith : None|str ISMCATCESVersion : None|str classification : str ownerProducer : str SCIcontrols : None|str SARIdentifier : None|str disseminationControls : None|str FGIsourceOpen : None|str FGIsourceProtected : None|str releasableTo : None|str nonICmarkings : None|str classifiedBy : None|str compilationReason : None|str derivativelyClassifiedBy : None|str classificationReason : None|str nonUSControls : None|str derivedFrom : None|str declassDate : None|str declassEvent : None|str declassException : None|str typeOfExemptedSource : None|str dateOfExemptedSource : None|str SecurityExtensions : None|ParametersCollection|dict kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.DESVersion = DESVersion self.createDate = createDate self.compliesWith = compliesWith self.ISMCATCESVersion = ISMCATCESVersion self.classification = classification self.ownerProducer = ownerProducer self.SCIcontrols = SCIcontrols self.SARIdentifier = SARIdentifier self.disseminationControls = disseminationControls self.FGIsourceOpen = FGIsourceOpen self.FGIsourceProtected = FGIsourceProtected self.releasableTo = releasableTo self.nonICmarkings = nonICmarkings self.classifiedBy = classifiedBy self.compilationReason = compilationReason self.derivativelyClassifiedBy = derivativelyClassifiedBy self.classificationReason = classificationReason self.nonUSControls = nonUSControls self.derivedFrom = derivedFrom self.declassDate = declassDate self.declassEvent = declassEvent self.declassException = declassException self.typeOfExemptedSource = typeOfExemptedSource self.dateOfExemptedSource = dateOfExemptedSource self.SecurityExtensions = SecurityExtensions super(ProductClassificationType, self).__init__(**kwargs) @property def resourceElement(self): return 'true' @classmethod def from_sicd(cls, sicd, create_date=None): """ Extract best guess from SICD. Parameters ---------- sicd : SICDType create_date : str Returns ------- ProductClassificationType """ clas = extract_classification_from_sicd(sicd) if create_date is None: create_date = datetime.now().strftime('%Y-%m-%d') return cls(classification=clas, createDate=create_date) class ProductCreationType(Serializable): """ Contains general information about product creation. """ _fields = ( 'ProcessorInformation', 'Classification', 'ProductName', 'ProductClass', 'ProductType', 'ProductCreationExtensions') _required = ( 'ProcessorInformation', 'Classification', 'ProductName', 'ProductClass') _collections_tags = {'ProductCreationExtensions': {'array': False, 'child_tag': 'ProductCreationExtension'}} # Descriptors ProcessorInformation = SerializableDescriptor( 'ProcessorInformation', ProcessorInformationType, _required, strict=DEFAULT_STRICT, docstring='Details regarding processor.') # type: ProcessorInformationType Classification = SerializableDescriptor( 'Classification', ProductClassificationType, _required, strict=DEFAULT_STRICT, docstring='The overall classification of the product.') # type: ProductClassificationType ProductName = StringDescriptor( 'ProductName', _required, strict=DEFAULT_STRICT, docstring='The output product name defined by the processor.') # type: str ProductClass = StringDescriptor( 'ProductClass', _required, strict=DEFAULT_STRICT, docstring='Class of product. Examples - :code:`Dynamic Image, Amplitude Change Detection, ' 'Coherent Change Detection`') # type: str ProductType = StringDescriptor( 'ProductType', _required, strict=DEFAULT_STRICT, docstring='Type of sub-product. Examples - :code:`Frame #, Reference, Match`. ' 'This field is only needed if there is a suite of associated ' 'products.') # type: Union[None, str] ProductCreationExtensions = ParametersDescriptor( 'ProductCreationExtensions', _collections_tags, _required, strict=DEFAULT_STRICT, docstring='Extensible parameters used to support profile-specific needs related to ' 'product creation.') # type: ParametersCollection def __init__(self, ProcessorInformation=None, Classification=None, ProductName=None, ProductClass=None, ProductType=None, ProductCreationExtensions=None, **kwargs): """ Parameters ---------- ProcessorInformation : ProcessorInformationType Classification : ProductClassificationType ProductName : str ProductClass : str ProductType : str ProductCreationExtensions : ParametersCollection|dict kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.ProcessorInformation = ProcessorInformation self.Classification = Classification self.ProductName = ProductName self.ProductClass = ProductClass self.ProductType = ProductType self.ProductCreationExtensions = ProductCreationExtensions super(ProductCreationType, self).__init__(**kwargs) @classmethod def from_sicd(cls, sicd, product_class): """ Generate from a SICD for the given product class. Parameters ---------- sicd : SICDType product_class : str Returns ------- ProductCreationType """ if not isinstance(sicd, SICDType): raise TypeError('Requires SICDType instance, got type {}'.format(type(sicd))) from sarpy.__about__ import __title__, __version__ proc_info = ProcessorInformationType( Application='{} {}'.format(__title__, __version__), ProcessingDateTime=numpy.datetime64(datetime.now()), Site='Unknown') classification = ProductClassificationType.from_sicd(sicd) return cls(ProcessorInformation=proc_info, Classification=classification, ProductName=product_class, ProductClass=product_class)
16,798
41.421717
118
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/ProductProcessing.py
""" The ProductProcessingType definition. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" from collections import OrderedDict from xml.etree import ElementTree from typing import List from sarpy.io.xml.base import Serializable, ParametersCollection, \ find_children, find_first_child, get_node_value, create_text_node from sarpy.io.xml.descriptors import ParametersDescriptor, StringDescriptor from .base import DEFAULT_STRICT class ProcessingModuleType(Serializable): """ Flexibly structured processing module definition to keep track of the name and any parameters associated with the algorithms used to produce the SIDD. """ _fields = ('ModuleName', 'name', 'ModuleParameters') _required = ('ModuleName', 'name', 'ModuleParameters') _set_as_attribute = ('name', ) _collections_tags = { 'ModuleParameters': {'array': False, 'child_tag': 'ModuleParameter'}} # Descriptor ModuleName = StringDescriptor( 'ModuleName', _required, strict=DEFAULT_STRICT, docstring='The module name.') # type: str name = StringDescriptor( 'name', _required, strict=DEFAULT_STRICT, docstring='The module identifier.') # type: str ModuleParameters = ParametersDescriptor( 'ModuleParameters', _collections_tags, _required, strict=DEFAULT_STRICT, docstring='Free form parameters.') # type: ParametersCollection def __init__(self, ModuleName=None, name=None, ModuleParameters=None, ProcessingModules=None, **kwargs): """ Parameters ---------- ModuleName : str name : str ModuleParameters : None|ParametersCollection|dict ProcessingModules : None|List[ProcessingModuleType] kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.ModuleName = ModuleName self.name = name self.ModuleParameters = ModuleParameters self._ProcessingModules = [] if ProcessingModules is None: pass elif isinstance(ProcessingModules, ProcessingModuleType): self.addProcessingModule(ProcessingModules) elif isinstance(ProcessingModules, (list, tuple)): for el in ProcessingModules: self.addProcessingModule(el) else: raise ValueError('ProcessingModules got unexpected type {}'.format(type(ProcessingModules))) super(ProcessingModuleType, self).__init__(**kwargs) @property def ProcessingModules(self): """List[ProcessingModuleType]: list of ProcessingModules.""" return self._ProcessingModules def getProcessingModule(self, key): """ Get ProcessingModule(s) with name attribute == `key`. Parameters ---------- key : str Returns ------- List[ProcessingModuleType] """ return [entry for entry in self._ProcessingModules if entry.name == key] def addProcessingModule(self, value): """ Add the ProcessingModule to the list. Parameters ---------- value : ProcessingModuleType Returns ------- None """ if isinstance(value, ElementTree.Element): pm_key = self._child_xml_ns_key.get('ProcessingModules', self._xml_ns_key) value = ProcessingModuleType.from_node(value, self._xml_ns, ns_key=pm_key) elif isinstance(value, dict): value = ProcessingModuleType.from_dict(value) if isinstance(value, ProcessingModuleType): self._ProcessingModules.append(value) else: raise TypeError('Trying to set ProcessingModule with unexpected type {}'.format(type(value))) @classmethod def from_node(cls, node, xml_ns, ns_key=None, kwargs=None): if kwargs is None: kwargs = OrderedDict() # parse the ModuleName mn_key = cls._child_xml_ns_key.get('ModuleName', ns_key) mn_node = find_first_child(node, 'ModuleName', xml_ns, mn_key) kwargs['ModuleName'] = get_node_value(mn_node) kwargs['name'] = mn_node.attrib.get('name', None) # parse the ProcessingModule children pm_key = cls._child_xml_ns_key.get('ProcessingModules', ns_key) kwargs['ProcessingModules'] = find_children(node, 'ProcessingModule', xml_ns, pm_key) return super(ProcessingModuleType, cls).from_node(node, xml_ns, ns_key=ns_key, kwargs=kwargs) def to_node(self, doc, tag, ns_key=None, parent=None, check_validity=False, strict=DEFAULT_STRICT, exclude=()): exclude = exclude + ('ModuleName', 'name', 'ProcessingModules') node = super(ProcessingModuleType, self).to_node( doc, tag, ns_key=ns_key, parent=parent, check_validity=check_validity, strict=strict, exclude=exclude) # add the ModuleName and name children if self.ModuleName is not None: mn_key = self._child_xml_ns_key.get('ModuleName', ns_key) mn_tag = '{}:ModuleName'.format(mn_key) if mn_key is not None and mn_key != 'default' else 'ModuleName' mn_node = create_text_node(doc, mn_tag, self.ModuleName, parent=node) if self.name is not None: mn_node.attrib['name'] = self.name # add the ProcessingModule children pm_key = self._child_xml_ns_key.get('ProcessingModules', ns_key) for entry in self._ProcessingModules: entry.to_node(doc, tag, ns_key=pm_key, parent=node, strict=strict) return node def to_dict(self, check_validity=False, strict=DEFAULT_STRICT, exclude=()): out = super(ProcessingModuleType, self).to_dict(check_validity=check_validity, strict=strict, exclude=exclude) # slap on the GeoInfo children if len(self.ProcessingModules) > 0: out['ProcessingModules'] = [ entry.to_dict(check_validity=check_validity, strict=strict) for entry in self._ProcessingModules] return out class ProductProcessingType(Serializable): """ Computed metadata regarding one or more of the input collections and final product. """ _fields = () _required = () def __init__(self, ProcessingModules=None, **kwargs): """ Parameters ---------- ProcessingModules : None|List[ProcessingModuleType] kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self._ProcessingModules = [] if ProcessingModules is None: pass elif isinstance(ProcessingModules, ProcessingModuleType): self.addProcessingModule(ProcessingModules) elif isinstance(ProcessingModules, (list, tuple)): for el in ProcessingModules: self.addProcessingModule(el) else: raise ValueError('ProcessingModules got unexpected type {}'.format(type(ProcessingModules))) super(ProductProcessingType, self).__init__(**kwargs) @property def ProcessingModules(self): """List[ProcessingModuleType]: list of ProcessingModules.""" return self._ProcessingModules def getProcessingModule(self, key): """ Get ProcessingModule(s) with name attribute == `key`. Parameters ---------- key : str Returns ------- List[ProcessingModuleType] """ return [entry for entry in self._ProcessingModules if entry.name == key] def addProcessingModule(self, value): """ Add the ProcessingModule to the list. Parameters ---------- value : ProcessingModuleType Returns ------- None """ if isinstance(value, ElementTree.Element): pm_key = self._child_xml_ns_key.get('ProcessingModules', self._xml_ns_key) value = ProcessingModuleType.from_node(value, self._xml_ns, ns_key=pm_key) elif isinstance(value, dict): value = ProcessingModuleType.from_dict(value) if isinstance(value, ProcessingModuleType): self._ProcessingModules.append(value) else: raise TypeError('Trying to set ProcessingModule with unexpected type {}'.format(type(value))) @classmethod def from_node(cls, node, xml_ns, ns_key=None, kwargs=None): if kwargs is None: kwargs = OrderedDict() pm_key = cls._child_xml_ns_key.get('ProcessingModules', ns_key) kwargs['ProcessingModules'] = find_children(node, 'ProcessingModule', xml_ns, pm_key) return super(ProductProcessingType, cls).from_node(node, xml_ns, ns_key=ns_key, kwargs=kwargs) def to_node(self, doc, tag, ns_key=None, parent=None, check_validity=False, strict=DEFAULT_STRICT, exclude=()): node = super(ProductProcessingType, self).to_node( doc, tag, ns_key=ns_key, parent=parent, check_validity=check_validity, strict=strict, exclude=exclude) # slap on the ProcessingModule children pm_key = self._child_xml_ns_key.get('ProcessingModules', ns_key) for entry in self._ProcessingModules: entry.to_node(doc, 'ProcessingModule', ns_key=pm_key, parent=node, strict=strict) return node def to_dict(self, check_validity=False, strict=DEFAULT_STRICT, exclude=()): out = super(ProductProcessingType, self).to_dict(check_validity=check_validity, strict=strict, exclude=exclude) # slap on the GeoInfo children if len(self.ProcessingModules) > 0: out['ProcessingModules'] = [ entry.to_dict(check_validity=check_validity, strict=strict) for entry in self._ProcessingModules] return out
9,935
37.215385
119
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/__init__.py
__classification__ = 'UNCLASSIFIED'
37
11.666667
35
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/GeoData.py
""" The GeoDataType definition. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" from collections import OrderedDict from typing import Union, List from xml.etree import ElementTree from sarpy.io.xml.base import Serializable, SerializableArray, find_children from sarpy.io.xml.descriptors import SerializableArrayDescriptor, StringEnumDescriptor from sarpy.io.complex.sicd_elements.base import SerializableCPArray, SerializableCPArrayDescriptor from .base import DEFAULT_STRICT, FLOAT_FORMAT from .blocks import LatLonCornerStringType, LatLonArrayElementType, GeoInfoType class GeoDataType(Serializable): """ Container specifying the image coverage area in geographic coordinates. .. Note: The SICD.GeoData class is an extension of this class. Implementation remain separate to allow the possibility of different functionality. """ _fields = ('EarthModel', 'ImageCorners', 'ValidData') _required = ('EarthModel', 'ImageCorners', 'ValidData') _collections_tags = { 'ValidData': {'array': True, 'child_tag': 'Vertex'}, 'ImageCorners': {'array': True, 'child_tag': 'ICP'}} _numeric_format = {'ImageCorners': FLOAT_FORMAT, 'ValidData': FLOAT_FORMAT} # other class variables _EARTH_MODEL_VALUES = ('WGS_84', ) # descriptors EarthModel = StringEnumDescriptor( 'EarthModel', _EARTH_MODEL_VALUES, _required, strict=True, default_value='WGS_84', docstring='Identifies the earth model used for latitude, longitude and height parameters. ' 'All height values are *Height Above The Ellipsoid ' '(HAE)*.'.format(_EARTH_MODEL_VALUES)) # type: str ImageCorners = SerializableCPArrayDescriptor( 'ImageCorners', LatLonCornerStringType, _collections_tags, _required, strict=DEFAULT_STRICT, docstring='The geographic image corner points array. Image corners points projected to the ' 'ground/surface level. Points may be projected to the same height as the SCP if ground/surface ' 'height data is not available. The corner positions are approximate geographic locations and ' 'not intended for analytical ' 'use.') # type: Union[SerializableCPArray, List[LatLonCornerStringType]] ValidData = SerializableArrayDescriptor( 'ValidData', LatLonArrayElementType, _collections_tags, _required, strict=DEFAULT_STRICT, minimum_length=3, docstring='The full image array includes both valid data and some zero filled pixels. Simple convex ' 'polygon enclosed the valid data (may include some zero filled pixels for simplification). ' 'Vertices in clockwise order.') # type: Union[SerializableArray, List[LatLonArrayElementType]] def __init__(self, EarthModel='WGS_84', ImageCorners=None, ValidData=None, GeoInfos=None, **kwargs): """ Parameters ---------- EarthModel : str ImageCorners : SerializableCPArray|List[LatLonCornerStringType]|numpy.ndarray|list|tuple ValidData : SerializableArray|List[LatLonArrayElementType]|numpy.ndarray|list|tuple GeoInfos : List[GeoInfoType] kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.EarthModel = EarthModel self.ImageCorners = ImageCorners self.ValidData = ValidData self._GeoInfos = [] if GeoInfos is None: pass elif isinstance(GeoInfos, GeoInfoType): self.setGeoInfo(GeoInfos) elif isinstance(GeoInfos, (list, tuple)): for el in GeoInfos: self.setGeoInfo(el) else: raise ValueError('GeoInfos got unexpected type {}'.format(type(GeoInfos))) super(GeoDataType, self).__init__(**kwargs) @property def GeoInfos(self): """ List[GeoInfoType]: list of GeoInfos. """ return self._GeoInfos def getGeoInfo(self, key): """ Get the GeoInfo(s) with name attribute == `key` Parameters ---------- key : str Returns ------- List[GeoInfoType] """ return [entry for entry in self._GeoInfos if entry.name == key] def setGeoInfo(self, value): """ Add the given GeoInfo to the GeoInfos list. Parameters ---------- value : GeoInfoType Returns ------- None """ if isinstance(value, ElementTree.Element): gi_key = self._child_xml_ns_key.get('GeoInfos', self._xml_ns_key) value = GeoInfoType.from_node(value, self._xml_ns, ns_key=gi_key) elif isinstance(value, dict): value = GeoInfoType.from_dict(value) if isinstance(value, GeoInfoType): self._GeoInfos.append(value) else: raise TypeError('Trying to set GeoInfo element with unexpected type {}'.format(type(value))) @classmethod def from_node(cls, node, xml_ns, ns_key=None, kwargs=None): if kwargs is None: kwargs = OrderedDict() gkey = cls._child_xml_ns_key.get('GeoInfos', ns_key) kwargs['GeoInfos'] = find_children(node, 'GeoInfo', xml_ns, gkey) return super(GeoDataType, cls).from_node(node, xml_ns, ns_key=ns_key, kwargs=kwargs) def to_node(self, doc, tag, ns_key=None, parent=None, check_validity=False, strict=DEFAULT_STRICT, exclude=()): node = super(GeoDataType, self).to_node( doc, tag, ns_key=ns_key, parent=parent, check_validity=check_validity, strict=strict, exclude=exclude) # slap on the GeoInfo children for entry in self._GeoInfos: entry.to_node(doc, 'GeoInfo', ns_key=ns_key, parent=node, strict=strict) return node def to_dict(self, check_validity=False, strict=DEFAULT_STRICT, exclude=()): out = super(GeoDataType, self).to_dict( check_validity=check_validity, strict=strict, exclude=exclude) # slap on the GeoInfo children if len(self.GeoInfos) > 0: out['GeoInfos'] = [entry.to_dict(check_validity=check_validity, strict=strict) for entry in self._GeoInfos] return out
6,375
39.35443
119
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/Display.py
""" The ProductDisplayType definition. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" from typing import Union, List from sarpy.io.xml.base import Serializable, SerializableArray, ParametersCollection from sarpy.io.xml.descriptors import SerializableDescriptor, SerializableListDescriptor, \ IntegerDescriptor, FloatDescriptor, StringDescriptor, StringEnumDescriptor, \ ParametersDescriptor, SerializableArrayDescriptor from .base import DEFAULT_STRICT, FLOAT_FORMAT from .blocks import FilterType, NewLookupTableType ######### # NonInteractiveProcessing class BandLUTType(NewLookupTableType): _fields = ('Predefined', 'Custom', 'k') _required = ('k', ) _set_as_attribute = ('k', ) # Descriptor k = IntegerDescriptor( 'k', _required, strict=DEFAULT_STRICT, bounds=(1, 2**32), default_value=1, docstring='The array index.') def __init__(self, Predefined=None, Custom=None, k=None, **kwargs): """ Parameters ---------- Predefined : sarpy.io.product.sidd2_elements.blocks.PredefinedLookupType Custom : sarpy.io.product.sidd2_elements.blocks.CustomLookupType k : int kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.k = k super(BandLUTType, self).__init__(Predefined=Predefined, Custom=Custom, **kwargs) class BandLUTArray(SerializableArray): _set_size = False _set_index = True _index_var_name = 'k' class BandEqualizationType(Serializable): """ """ _fields = ('Algorithm', 'BandLUTs') _required = ('Algorithm', 'BandLUTs') _collections_tags = {'BandLUTs': {'array': True, 'child_tag': 'BandLUT'}} # Descriptor Algorithm = StringEnumDescriptor( 'Algorithm', ('1DLUT', ), _required, strict=DEFAULT_STRICT, default_value='1DLUT', docstring='The algorithm type.') # type: str BandLUTs = SerializableArrayDescriptor( 'BandLUTs', BandLUTType, _collections_tags, _required, strict=DEFAULT_STRICT, array_extension=BandLUTArray, docstring='') # type: Union[BandLUTArray, List[BandLUTType]] def __init__(self, Algorithm='1DLUT', BandLUTs=None, **kwargs): """ Parameters ---------- Algorithm : str `1DLUT` is currently the only allowed value. BandLUTs : BandLUTArray|List[BandLUTType] kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Algorithm = Algorithm self.BandLUTs = BandLUTs super(BandEqualizationType, self).__init__(**kwargs) class ProductGenerationOptionsType(Serializable): """ """ _fields = ('BandEqualization', 'ModularTransferFunctionRestoration', 'DataRemapping', 'AsymmetricPixelCorrection') _required = ('DataRemapping', ) # Descriptor BandEqualization = SerializableDescriptor( 'BandEqualization', BandEqualizationType, _required, strict=DEFAULT_STRICT, docstring='Band equalization ensures that real-world neutral colors have equal digital count values ' '(i.e. are represented as neutral colors) across the dynamic range ' 'of the imaged scene.') # type: BandEqualizationType ModularTransferFunctionRestoration = SerializableDescriptor( 'ModularTransferFunctionRestoration', FilterType, _required, strict=DEFAULT_STRICT, docstring=r'If present, the filter must not exceed :math:`15 \times 15`.') # type: FilterType DataRemapping = SerializableDescriptor( 'DataRemapping', NewLookupTableType, _required, strict=DEFAULT_STRICT, docstring='Data remapping refers to the specific need to convert the data of incoming, expanded or ' 'uncompressed image band data to non-mapped image data.') # type: NewLookupTableType AsymmetricPixelCorrection = SerializableDescriptor( 'AsymmetricPixelCorrection', FilterType, _required, strict=DEFAULT_STRICT, docstring='The asymmetric pixel correction.') # type: FilterType def __init__(self, BandEqualization=None, ModularTransferFunctionRestoration=None, DataRemapping=None, **kwargs): if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.BandEqualization = BandEqualization self.ModularTransferFunctionRestoration = ModularTransferFunctionRestoration self.DataRemapping = DataRemapping super(ProductGenerationOptionsType, self).__init__(**kwargs) class RRDSType(Serializable): """ RRDS type. """ _fields = ('DownsamplingMethod', 'AntiAlias', 'Interpolation') _required = ('DownsamplingMethod', ) # Descriptor DownsamplingMethod = StringEnumDescriptor( 'DownsamplingMethod', ('DECIMATE', 'MAX PIXEL', 'AVERAGE', 'NEAREST NEIGHBOR', 'BILINEAR', 'LAGRANGE'), _required, strict=DEFAULT_STRICT, docstring='Algorithm used to perform RRDS downsampling') # type: str AntiAlias = SerializableDescriptor( 'AntiAlias', FilterType, _required, strict=DEFAULT_STRICT, docstring='The anti-aliasing filter. Should only be included if ' '`DownsamplingMethod= "DECIMATE"`') # type: FilterType Interpolation = SerializableDescriptor( 'Interpolation', FilterType, _required, strict=DEFAULT_STRICT, docstring='The interpolation filter. Should only be included if ' '`DownsamplingMethod= "DECIMATE"`') # type: FilterType def __init__(self, DownsamplingMethod=None, AntiAlias=None, Interpolation=None, **kwargs): """ Parameters ---------- DownsamplingMethod : str AntiAlias : None|FilterType Interpolation : None|FilterType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.DownsamplingMethod = DownsamplingMethod self.AntiAlias = AntiAlias self.Interpolation = Interpolation super(RRDSType, self).__init__(**kwargs) class NonInteractiveProcessingType(Serializable): """ The non-interactive processing information. """ _fields = ('ProductGenerationOptions', 'RRDS', 'band') _required = ('ProductGenerationOptions', 'RRDS', 'band') _set_as_attribute = ('band', ) # Descriptor ProductGenerationOptions = SerializableDescriptor( 'ProductGenerationOptions', ProductGenerationOptionsType, _required, strict=DEFAULT_STRICT, docstring='Performs several key actions on an image to prepare it for necessary additional processing to ' 'achieve the desired output product.') # type: ProductGenerationOptionsType RRDS = SerializableDescriptor( 'RRDS', RRDSType, _required, strict=DEFAULT_STRICT, docstring='Creates a set of sub-sampled versions of an image to provide processing chains ' 'with quick access to lower magnification values for faster computation ' 'speeds and performance.') # type: RRDSType band = IntegerDescriptor( 'band', _required, strict=DEFAULT_STRICT, docstring='The image band to which this applies.') # type: int def __init__(self, ProductGenerationOptions=None, RRDS=None, band=1, **kwargs): if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.ProductGenerationOptions = ProductGenerationOptions self.RRDS = RRDS self.band = band super(NonInteractiveProcessingType, self).__init__(**kwargs) ########## # InteractiveProcessing class ScalingType(Serializable): """ Scaling for geometric transformation """ _fields = ('AntiAlias', 'Interpolation') _required = _fields # Descriptor AntiAlias = SerializableDescriptor( 'AntiAlias', FilterType, _required, strict=DEFAULT_STRICT, docstring='The Anti-Alias Filter used for scaling. Refer to program-specific ' 'documentation for population guidance.') # type: FilterType Interpolation = SerializableDescriptor( 'Interpolation', FilterType, _required, strict=DEFAULT_STRICT, docstring='The Interpolation Filter used for scaling. Refer to program-specific ' 'documentation for population guidance.') # type: FilterType def __init__(self, AntiAlias=None, Interpolation=None, **kwargs): """ Parameters ---------- AntiAlias : FilterType Interpolation : FilterType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.AntiAlias = AntiAlias self.Interpolation = Interpolation super(ScalingType, self).__init__(**kwargs) class OrientationType(Serializable): """ Parameters describing the default orientation of the product. """ _fields = ('ShadowDirection', ) _required = _fields # Descriptor ShadowDirection = StringEnumDescriptor( 'ShadowDirection', ('UP', 'DOWN', 'LEFT', 'RIGHT', 'ARBITRARY'), _required, strict=DEFAULT_STRICT, default_value='DOWN', docstring='Describes the shadow direction relative to the ' 'pixels in the file.') # type: str def __init__(self, ShadowDirection='DOWN', **kwargs): if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.ShadowDirection = ShadowDirection super(OrientationType, self).__init__(**kwargs) class GeometricTransformType(Serializable): """ The geometric transform element is used to perform various geometric distortions to each band of image data. These distortions include image chipping, scaling, rotation, shearing, etc. """ _fields = ('Scaling', 'Orientation') _required = _fields # Descriptor Scaling = SerializableDescriptor( 'Scaling', ScalingType, _required, strict=DEFAULT_STRICT, docstring='The scaling filters.') # type: ScalingType Orientation = SerializableDescriptor( 'Orientation', OrientationType, _required, strict=DEFAULT_STRICT, docstring='Parameters describing the default orientation of the product.') # type: OrientationType def __init__(self, Scaling=None, Orientation=None, **kwargs): """ Parameters ---------- Scaling : ScalingType Orientation : OrientationType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Scaling = Scaling self.Orientation = Orientation super(GeometricTransformType, self).__init__(**kwargs) class SharpnessEnhancementType(Serializable): """ Sharpness enhancement filter parameters. """ _fields = ('ModularTransferFunctionCompensation', 'ModularTransferFunctionEnhancement') _required = () _choice = ({'required': True, 'collection': ('ModularTransferFunctionCompensation', 'ModularTransferFunctionEnhancement')}, ) # Descriptor ModularTransferFunctionCompensation = SerializableDescriptor( 'ModularTransferFunctionCompensation', FilterType, _required, strict=DEFAULT_STRICT, docstring=r'If defining a custom Filter, it must be no larger than :math:`5\times 5`.') # type: FilterType ModularTransferFunctionEnhancement = SerializableDescriptor( 'ModularTransferFunctionEnhancement', FilterType, _required, strict=DEFAULT_STRICT, docstring=r'If defining a custom Filter, it must be no larger than :math:`5\times 5`.') # type: FilterType def __init__(self, ModularTransferFunctionCompensation=None, ModularTransferFunctionEnhancement=None, **kwargs): """ Parameters ---------- ModularTransferFunctionCompensation : FilterType ModularTransferFunctionEnhancement : FilterType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.ModularTransferFunctionCompensation = ModularTransferFunctionCompensation self.ModularTransferFunctionEnhancement = ModularTransferFunctionEnhancement super(SharpnessEnhancementType, self).__init__(**kwargs) class ColorManagementModuleType(Serializable): """ Parameters describing the Color Management Module (CMM). """ _fields = ('RenderingIntent', 'SourceProfile', 'DisplayProfile', 'ICCProfile') _required = ('RenderingIntent', 'SourceProfile') # Descriptor RenderingIntent = StringEnumDescriptor( 'RenderingIntent', ('PERCEPTUAL', 'SATURATION', 'RELATIVE', 'ABSOLUTE'), _required, strict=DEFAULT_STRICT, default_value='PERCEPTUAL', docstring='The rendering intent for this color management.') # type: str SourceProfile = StringDescriptor( 'SourceProfile', _required, strict=DEFAULT_STRICT, docstring='Name of sensor profile in ICC Profile database.') # type: str DisplayProfile = StringDescriptor( 'DisplayProfile', _required, strict=DEFAULT_STRICT, docstring='Name of display profile in ICC Profile database.') # type: str ICCProfile = StringDescriptor( 'ICCProfile', _required, strict=DEFAULT_STRICT, docstring='Valid ICC profile signature.') # type: str def __init__(self, RenderingIntent='PERCEPTUAL', SourceProfile=None, DisplayProfile=None, ICCProfile=None, **kwargs): """ Parameters ---------- RenderingIntent : str SourceProfile : str DisplayProfile : str ICCProfile : str kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.RenderingIntent = RenderingIntent self.SourceProfile = SourceProfile self.DisplayProfile = DisplayProfile self.ICCProfile = ICCProfile super(ColorManagementModuleType, self).__init__(**kwargs) class ColorSpaceTransformType(Serializable): """ Parameters describing any color transformation. """ _fields = ('ColorManagementModule', ) _required = _fields # Descriptor ColorManagementModule = SerializableDescriptor( 'ColorManagementModule', ColorManagementModuleType, _required, strict=DEFAULT_STRICT, docstring='Parameters describing the Color Management Module (CMM).') # type: ColorManagementModuleType def __init__(self, ColorManagementModule=None, **kwargs): """ Parameters ---------- ColorManagementModule : ColorManagementModuleType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.ColorManagementModule = ColorManagementModule super(ColorSpaceTransformType, self).__init__(**kwargs) class DRAParametersType(Serializable): """ The basic dynamic range adjustment parameters. """ _fields = ('Pmin', 'Pmax', 'EminModifier', 'EmaxModifier') _required = _fields _numeric_format = {key: FLOAT_FORMAT for key in _fields} # Descriptor Pmin = FloatDescriptor( 'Pmin', _required, strict=DEFAULT_STRICT, bounds=(0, 1), docstring='DRA clip low point. This is the cumulative histogram percentage value ' 'that defines the lower end-point of the dynamic range to be displayed.') # type: float Pmax = FloatDescriptor( 'Pmax', _required, strict=DEFAULT_STRICT, bounds=(0, 1), docstring='DRA clip high point. This is the cumulative histogram percentage value ' 'that defines the upper end-point of the dynamic range to be displayed.') # type: float EminModifier = FloatDescriptor( 'EminModifier', _required, strict=DEFAULT_STRICT, bounds=(0, 1), docstring='The pixel value corresponding to the Pmin percentage point in the ' 'image histogram.') # type: float EmaxModifier = FloatDescriptor( 'EmaxModifier', _required, strict=DEFAULT_STRICT, bounds=(0, 1), docstring='The pixel value corresponding to the Pmax percentage point in the ' 'image histogram.') # type: float def __init__(self, Pmin=None, Pmax=None, EminModifier=None, EmaxModifier=None, **kwargs): """ Parameters ---------- Pmin : float Pmax : float EminModifier : float EmaxModifier : float kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Pmin = Pmin self.Pmax = Pmax self.EminModifier = EminModifier self.EmaxModifier = EmaxModifier super(DRAParametersType, self).__init__(**kwargs) class DRAOverridesType(Serializable): """ The dynamic range adjustment overrides. """ _fields = ('Subtractor', 'Multiplier') _required = _fields _numeric_format = {key: FLOAT_FORMAT for key in _fields} # Descriptor Subtractor = FloatDescriptor( 'Subtractor', _required, strict=DEFAULT_STRICT, bounds=(0, 2047), docstring='Subtractor value used to reduce haze in the image.') # type: float Multiplier = FloatDescriptor( 'Multiplier', _required, strict=DEFAULT_STRICT, bounds=(0, 2047), docstring='Multiplier value used to reduce haze in the image.') # type: float def __init__(self, Subtractor=None, Multiplier=None, **kwargs): """ Parameters ---------- Subtractor : float Multiplier : float kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Subtractor = Subtractor self.Multiplier = Multiplier super(DRAOverridesType, self).__init__(**kwargs) class DynamicRangeAdjustmentType(Serializable): """ The dynamic range adjustment (DRA) parameters. """ _fields = ('AlgorithmType', 'BandStatsSource', 'DRAParameters', 'DRAOverrides') _required = ('AlgorithmType', 'BandStatsSource', ) # Descriptor AlgorithmType = StringEnumDescriptor( 'AlgorithmType', ('AUTO', 'MANUAL', 'NONE'), _required, strict=DEFAULT_STRICT, default_value='NONE', docstring='Algorithm used for dynamic range adjustment.') # type: str BandStatsSource = IntegerDescriptor( 'BandStatsSource', _required, strict=DEFAULT_STRICT, docstring='') # type: int DRAParameters = SerializableDescriptor( 'DRAParameters', DRAParametersType, _required, strict=DEFAULT_STRICT, docstring='The dynamic range adjustment parameters.') # type: DRAParametersType DRAOverrides = SerializableDescriptor( 'DRAOverrides', DRAOverridesType, _required, strict=DEFAULT_STRICT, docstring='The dynamic range adjustment overrides.') # type: DRAOverridesType def __init__(self, AlgorithmType='NONE', BandStatsSource=None, DRAParameters=None, DRAOverrides=None, **kwargs): """ Parameters ---------- AlgorithmType : str BandStatsSource : int DRAParameters : DRAParametersType DRAOverrides : DRAOverridesType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.AlgorithmType = AlgorithmType self.BandStatsSource = BandStatsSource self.DRAParameters = DRAParameters self.DRAOverrides = DRAOverrides super(DynamicRangeAdjustmentType, self).__init__(**kwargs) class InteractiveProcessingType(Serializable): """ The interactive processing information. """ _fields = ( 'GeometricTransform', 'SharpnessEnhancement', 'ColorSpaceTransform', 'DynamicRangeAdjustment', 'TonalTransferCurve', 'band') _required = ( 'GeometricTransform', 'SharpnessEnhancement', 'DynamicRangeAdjustment', 'band') _set_as_attribute = ('band', ) # Descriptor GeometricTransform = SerializableDescriptor( 'GeometricTransform', GeometricTransformType, _required, strict=DEFAULT_STRICT, docstring='The geometric transform element is used to perform various geometric distortions ' 'to each band of image data. These distortions include image ' 'chipping, scaling, rotation, shearing, etc.') # type: GeometricTransformType SharpnessEnhancement = SerializableDescriptor( 'SharpnessEnhancement', SharpnessEnhancementType, _required, strict=DEFAULT_STRICT, docstring='Sharpness enhancement.') # type: SharpnessEnhancementType ColorSpaceTransform = SerializableDescriptor( 'ColorSpaceTransform', ColorSpaceTransformType, _required, strict=DEFAULT_STRICT, docstring='Color space transform.') # type: ColorSpaceTransformType DynamicRangeAdjustment = SerializableDescriptor( 'DynamicRangeAdjustment', DynamicRangeAdjustmentType, _required, strict=DEFAULT_STRICT, docstring='Specifies the recommended ELT DRA overrides.') # type: DynamicRangeAdjustmentType TonalTransferCurve = SerializableDescriptor( 'TonalTransferCurve', NewLookupTableType, _required, strict=DEFAULT_STRICT, docstring="The 1-D LUT element uses one or more 1-D LUTs to stretch or compress tone data " "in valorous regions within a digital image's dynamic range. 1-D LUT can be " "implemented using a Tonal Transfer Curve (TTC). There are 12 families of TTCs " "- Range = [0, 11]. There are 64 members for each " "family - Range=[0, 63].") # type: NewLookupTableType band = IntegerDescriptor( 'band', _required, strict=DEFAULT_STRICT, docstring='The image band to which this applies.') def __init__(self, GeometricTransform=None, SharpnessEnhancement=None, ColorSpaceTransform=None, DynamicRangeAdjustment=None, band=1, **kwargs): if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.GeometricTransform = GeometricTransform self.SharpnessEnhancement = SharpnessEnhancement self.ColorSpaceTransform = ColorSpaceTransform self.DynamicRangeAdjustment = DynamicRangeAdjustment self.band = band super(InteractiveProcessingType, self).__init__(**kwargs) ########## class ProductDisplayType(Serializable): """ """ _fields = ( 'PixelType', 'NumBands', 'DefaultBandDisplay', 'NonInteractiveProcessing', 'InteractiveProcessing', 'DisplayExtensions') _required = ( 'PixelType', 'NumBands', 'NonInteractiveProcessing', 'InteractiveProcessing') _collections_tags = { 'NonInteractiveProcessing': {'array': False, 'child_tag': 'NonInteractiveProcessing'}, 'InteractiveProcessing': {'array': False, 'child_tag': 'InteractiveProcessing'}, 'DisplayExtensions': {'array': False, 'child_tag': 'DisplayExtension'}} # Descriptors PixelType = StringEnumDescriptor( 'PixelType', ('MONO8I', 'MONO8LU', 'MONO16I', 'RGB8LU', 'RGB24I'), _required, strict=DEFAULT_STRICT, docstring='Enumeration of the pixel type. Definition in ' 'Design and Exploitation document.') # type: str NumBands = IntegerDescriptor( 'NumBands', _required, strict=DEFAULT_STRICT, docstring='Number of bands contained in the image. Populate with the number of bands ' 'present after remapping. For example an 8-bit RGB image (RGBLU), this will ' 'be 3.') # type: int DefaultBandDisplay = IntegerDescriptor( 'DefaultBandDisplay', _required, strict=DEFAULT_STRICT, docstring='Indicates which band to display by default. ' 'Valid range = 1 to NumBands.') # type: int NonInteractiveProcessing = SerializableListDescriptor( 'NonInteractiveProcessing', NonInteractiveProcessingType, _collections_tags, _required, strict=DEFAULT_STRICT, docstring='Non-interactive processing details.') # type: List[NonInteractiveProcessingType] InteractiveProcessing = SerializableListDescriptor( 'InteractiveProcessing', InteractiveProcessingType, _collections_tags, _required, strict=DEFAULT_STRICT, docstring='Interactive processing details.') # type: List[InteractiveProcessingType] DisplayExtensions = ParametersDescriptor( 'DisplayExtensions', _collections_tags, _required, strict=DEFAULT_STRICT, docstring='Optional extensible parameters used to support profile-specific needs related to ' 'product display. Predefined filter types.') # type: ParametersCollection def __init__(self, PixelType=None, NumBands=1, DefaultBandDisplay=None, NonInteractiveProcessing=None, InteractiveProcessing=None, DisplayExtensions=None, **kwargs): """ Parameters ---------- PixelType : PixelTypeType NumBands : int DefaultBandDisplay : int|None NonInteractiveProcessing : List[NonInteractiveProcessingType] InteractiveProcessing : List[InteractiveProcessingType] DisplayExtensions : ParametersCollection|dict kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.PixelType = PixelType self.NumBands = NumBands self.DefaultBandDisplay = DefaultBandDisplay self.NonInteractiveProcessing = NonInteractiveProcessing self.InteractiveProcessing = InteractiveProcessing self.DisplayExtensions = DisplayExtensions super(ProductDisplayType, self).__init__(**kwargs) def get_pixel_size(self) -> int: """ Gets the raw size per pixel, in bytes. Returns ------- int """ if self.PixelType == 'MONO8I': return 1 elif self.PixelType == 'MONO8LU': return 1 elif self.PixelType == 'MONO16I': return 2 elif self.PixelType == 'RGB8LU': return 1 elif self.PixelType == 'RGB24I': return 3 else: raise ValueError('Got unhandled pixel type `{}`'.format(self.PixelType))
27,598
40.192537
118
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/DownstreamReprocessing.py
""" The DownstreamReprocessingType definition. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" from typing import Union, List from datetime import datetime import numpy from sarpy.io.xml.base import Serializable, ParametersCollection from sarpy.io.xml.descriptors import SerializableDescriptor, ParametersDescriptor, \ StringDescriptor, DateTimeDescriptor, SerializableListDescriptor from .base import DEFAULT_STRICT from .blocks import RowColDoubleType, RowColIntType class GeometricChipType(Serializable): """ Contains information related to downstream chipping of the product. There is only one instance, and the instance is updated with respect to the **full image** parameters. For example, if an image is chipped out of a smaller chip, the new chip needs to be updated to the original full image corners. Since this relationship is linear, bi-linear interpolation is sufficient to determine an arbitrary chip coordinate in terms of the original full image coordinates. Chipping is typically done using an exploitation tool, and should not be done in the initial product creation. """ _fields = ( 'ChipSize', 'OriginalUpperLeftCoordinate', 'OriginalUpperRightCoordinate', 'OriginalLowerLeftCoordinate', 'OriginalLowerRightCoordinate') _required = _fields # Descriptor ChipSize = SerializableDescriptor( 'ChipSize', RowColIntType, _required, strict=DEFAULT_STRICT, docstring='Size of the chipped product in pixels.') # type: RowColIntType OriginalUpperLeftCoordinate = SerializableDescriptor( 'OriginalUpperLeftCoordinate', RowColDoubleType, _required, strict=DEFAULT_STRICT, docstring='Upper-left corner with respect to the original product.') # type: RowColDoubleType OriginalUpperRightCoordinate = SerializableDescriptor( 'OriginalUpperRightCoordinate', RowColDoubleType, _required, strict=DEFAULT_STRICT, docstring='Upper-right corner with respect to the original product.') # type: RowColDoubleType OriginalLowerLeftCoordinate = SerializableDescriptor( 'OriginalLowerLeftCoordinate', RowColDoubleType, _required, strict=DEFAULT_STRICT, docstring='Lower-left corner with respect to the original product.') # type: RowColDoubleType OriginalLowerRightCoordinate = SerializableDescriptor( 'OriginalLowerRightCoordinate', RowColDoubleType, _required, strict=DEFAULT_STRICT, docstring='Lower-right corner with respect to the original product.') # type: RowColDoubleType def __init__(self, ChipSize=None, OriginalUpperLeftCoordinate=None, OriginalUpperRightCoordinate=None, OriginalLowerLeftCoordinate=None, OriginalLowerRightCoordinate=None, **kwargs): """ Parameters ---------- ChipSize : RowColIntType|numpy.ndarray|list|tuple OriginalUpperLeftCoordinate : RowColDoubleType|numpy.ndarray|list|tuple OriginalUpperRightCoordinate : RowColDoubleType|numpy.ndarray|list|tuple OriginalLowerLeftCoordinate : RowColDoubleType|numpy.ndarray|list|tuple OriginalLowerRightCoordinate : RowColDoubleType|numpy.ndarray|list|tuple kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.ChipSize = ChipSize self.OriginalUpperLeftCoordinate = OriginalUpperLeftCoordinate self.OriginalUpperRightCoordinate = OriginalUpperRightCoordinate self.OriginalLowerLeftCoordinate = OriginalLowerLeftCoordinate self.OriginalLowerRightCoordinate = OriginalLowerRightCoordinate super(GeometricChipType, self).__init__(**kwargs) class ProcessingEventType(Serializable): """ Processing event data. """ _fields = ('ApplicationName', 'AppliedDateTime', 'InterpolationMethod', 'Descriptors') _required = ('ApplicationName', 'AppliedDateTime') _collections_tags = {'Descriptors': {'array': False, 'child_tag': 'Descriptor'}} # Descriptor ApplicationName = StringDescriptor( 'ApplicationName', _required, strict=DEFAULT_STRICT, docstring='Application which applied a modification.') # type: str AppliedDateTime = DateTimeDescriptor( 'AppliedDateTime', _required, strict=DEFAULT_STRICT, numpy_datetime_units='us', docstring='Date and time defined in Coordinated Universal Time (UTC).') # type: numpy.datetime64 InterpolationMethod = StringDescriptor( 'InterpolationMethod', _required, strict=DEFAULT_STRICT, docstring='Type of interpolation applied to the data.') # type: Union[None, str] Descriptors = ParametersDescriptor( 'Descriptors', _collections_tags, _required, strict=DEFAULT_STRICT, docstring='Descriptors for the processing event.') # type: ParametersCollection def __init__(self, ApplicationName=None, AppliedDateTime=None, InterpolationMethod=None, Descriptors=None, **kwargs): """ Parameters ---------- ApplicationName : str AppliedDateTime : numpy.datetime64|str InterpolationMethod : None|str Descriptors : None|ParametersCollection|dict kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.ApplicationName = ApplicationName self.AppliedDateTime = numpy.datetime64(datetime.now()) if AppliedDateTime is None else AppliedDateTime self.InterpolationMethod = InterpolationMethod self.Descriptors = Descriptors super(ProcessingEventType, self).__init__(**kwargs) class DownstreamReprocessingType(Serializable): """ Further processing after initial image creation. """ _fields = ('GeometricChip', 'ProcessingEvents') _required = () _collections_tags = {'ProcessingEvents': {'array': False, 'child_tag': 'ProcessingEvent'}} # Descriptor GeometricChip = SerializableDescriptor( 'GeometricChip', GeometricChipType, _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, GeometricChipType] ProcessingEvents = SerializableListDescriptor( 'ProcessingEvents', ProcessingEventType, _collections_tags, _required, strict=DEFAULT_STRICT, docstring='') # type: Union[None, List[ProcessingEventType]] def __init__(self, GeometricChip=None, ProcessingEvents=None, **kwargs): """ Parameters ---------- GeometricChip : None|GeometricChipType ProcessingEvents : None|List[ProcessingEventType] kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.GeometricChip = GeometricChip self.ProcessingEvents = ProcessingEvents super(DownstreamReprocessingType, self).__init__(**kwargs)
7,105
43.691824
111
py
sarpy
sarpy-master/sarpy/io/product/sidd2_elements/blocks.py
""" Multipurpose basic SIDD elements """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" from collections import OrderedDict from typing import Union import numpy from sarpy.io.xml.base import Serializable, Arrayable, get_node_value, create_text_node, create_new_node, find_children from sarpy.io.xml.descriptors import SerializableDescriptor, IntegerDescriptor, \ FloatDescriptor, FloatModularDescriptor, StringDescriptor, StringEnumDescriptor from .base import DEFAULT_STRICT, FLOAT_FORMAT from sarpy.io.complex.sicd_elements.blocks import XYZType as XYZTypeBase, XYZPolyType as XYZPolyTypeBase, \ LatLonType as LatLonTypeBase, LatLonCornerType as LatLonCornerTypeBase, \ RowColType as RowColIntTypeBase, RowColArrayElement as RowColArrayElementBase, \ Poly1DType as Poly1DTypeBase, Poly2DType as Poly2DTypeBase, \ LatLonCornerStringType as LatLonCornerStringTypeBase, LatLonArrayElementType as LatLonArrayElementTypeBase from sarpy.io.complex.sicd_elements.ErrorStatistics import ErrorStatisticsType as ErrorStatisticsTypeBase from sarpy.io.complex.sicd_elements.Radiometric import RadiometricType as RadiometricTypeBase from sarpy.io.complex.sicd_elements.MatchInfo import MatchInfoType as MatchInfoTypeBase from sarpy.io.complex.sicd_elements.GeoData import GeoInfoType as GeoInfoTypeBase from sarpy.io.complex.sicd_elements.CollectionInfo import RadarModeType as RadarModeTypeBase _len2_array_text = 'Expected array to be of length 2,\n\t' \ 'and received `{}`' _array_type_text = 'Expected array to be numpy.ndarray, list, or tuple,\n\t' \ 'got `{}`' ############ # the SICommon namespace elements class XYZType(XYZTypeBase): _child_xml_ns_key = {'X': 'sicommon', 'Y': 'sicommon', 'Z': 'sicommon'} class LatLonType(LatLonTypeBase): _child_xml_ns_key = {'Lat': 'sicommon', 'Lon': 'sicommon'} class LatLonCornerType(LatLonCornerTypeBase): _child_xml_ns_key = {'Lat': 'sicommon', 'Lon': 'sicommon'} class LatLonCornerStringType(LatLonCornerStringTypeBase): _child_xml_ns_key = {'Lat': 'sicommon', 'Lon': 'sicommon'} class LatLonArrayElementType(LatLonArrayElementTypeBase): _child_xml_ns_key = {'Lat': 'sicommon', 'Lon': 'sicommon'} class RangeAzimuthType(Serializable, Arrayable): """ Represents range and azimuth. """ _fields = ('Range', 'Azimuth') _required = ('Range', 'Azimuth') _numeric_format = {key: FLOAT_FORMAT for key in _fields} _child_xml_ns_key = {'Range': 'sicommon', 'Azimuth': 'sicommon'} # Descriptor Range = FloatDescriptor( 'Range', _required, strict=DEFAULT_STRICT, docstring='The range in meters.') # type: float Azimuth = FloatDescriptor( 'Azimuth', _required, strict=DEFAULT_STRICT, docstring='The azimuth in degrees.') # type: float def __init__(self, Range=None, Azimuth=None, **kwargs): """ Parameters ---------- Range : float Azimuth : float kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Range = Range self.Azimuth = Azimuth super(RangeAzimuthType, self).__init__(**kwargs) def get_array(self, dtype=numpy.float64): """ Gets an array representation of the class instance. Parameters ---------- dtype : str|numpy.dtype|numpy.number numpy data type of the return Returns ------- numpy.ndarray array of the form [Range, Azimuth] """ return numpy.array([self.Range, self.Azimuth], dtype=dtype) @classmethod def from_array(cls, array): """ Create from an array type entry. Parameters ---------- array: numpy.ndarray|list|tuple assumed [Range, Azimuth] Returns ------- RangeAzimuthType """ if array is None: return None if isinstance(array, (numpy.ndarray, list, tuple)): if len(array) < 2: raise ValueError(_len2_array_text.format(array)) return cls(Range=array[0], Azimuth=array[1]) raise ValueError(_array_type_text.format(type(array))) class AngleMagnitudeType(Serializable, Arrayable): """ Represents a magnitude and angle. """ _fields = ('Angle', 'Magnitude') _required = ('Angle', 'Magnitude') _numeric_format = {key: FLOAT_FORMAT for key in _fields} _child_xml_ns_key = {'Angle': 'sicommon', 'Magnitude': 'sicommon'} # Descriptor Angle = FloatModularDescriptor( 'Angle', 180.0, _required, strict=DEFAULT_STRICT, docstring='The angle.') # type: float Magnitude = FloatDescriptor( 'Magnitude', _required, strict=DEFAULT_STRICT, bounds=(0.0, None), docstring='The magnitude.') # type: float def __init__(self, Angle=None, Magnitude=None, **kwargs): """ Parameters ---------- Angle : float Magnitude : float kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Angle = Angle self.Magnitude = Magnitude super(AngleMagnitudeType, self).__init__(**kwargs) def get_array(self, dtype=numpy.float64): """ Gets an array representation of the class instance. Parameters ---------- dtype : str|numpy.dtype|numpy.number numpy data type of the return Returns ------- numpy.ndarray array of the form [Angle, Magnitude] """ return numpy.array([self.Angle, self.Magnitude], dtype=dtype) @classmethod def from_array(cls, array): """ Create from an array type entry. Parameters ---------- array: numpy.ndarray|list|tuple assumed [Angle, Magnitude] Returns ------- AngleMagnitudeType """ if array is None: return None if isinstance(array, (numpy.ndarray, list, tuple)): if len(array) < 2: raise ValueError(_len2_array_text.format(array)) return cls(Angle=array[0], Magnitude=array[1]) raise ValueError(_array_type_text.format(type(array))) class RowColIntType(RowColIntTypeBase): _child_xml_ns_key = {'Row': 'sicommon', 'Col': 'sicommon'} class RowColArrayElement(RowColArrayElementBase): _child_xml_ns_key = {'Row': 'sicommon', 'Col': 'sicommon'} class RowColDoubleType(Serializable, Arrayable): _fields = ('Row', 'Col') _required = _fields _numeric_format = {key: FLOAT_FORMAT for key in _fields} _child_xml_ns_key = {'Row': 'sicommon', 'Col': 'sicommon'} # Descriptors Row = FloatDescriptor( 'Row', _required, strict=True, docstring='The Row attribute.') # type: float Col = FloatDescriptor( 'Col', _required, strict=True, docstring='The Column attribute.') # type: float def __init__(self, Row=None, Col=None, **kwargs): """ Parameters ---------- Row : float Col : float kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Row, self.Col = Row, Col super(RowColDoubleType, self).__init__(**kwargs) def get_array(self, dtype=numpy.float64): """ Gets an array representation of the class instance. Parameters ---------- dtype : str|numpy.dtype|numpy.number numpy data type of the return Returns ------- numpy.ndarray array of the form [Row, Col] """ return numpy.array([self.Row, self.Col], dtype=dtype) @classmethod def from_array(cls, array): """ Create from an array type entry. Parameters ---------- array: numpy.ndarray|list|tuple assumed [Row, Col] Returns ------- RowColDoubleType """ if array is None: return None if isinstance(array, (numpy.ndarray, list, tuple)): if len(array) < 2: raise ValueError(_len2_array_text.format(array)) return cls(Row=array[0], Col=array[1]) raise ValueError(_array_type_text.format(type(array))) class Poly1DType(Poly1DTypeBase): _child_xml_ns_key = {'Coefs': 'sicommon'} class Poly2DType(Poly2DTypeBase): _child_xml_ns_key = {'Coefs': 'sicommon'} class XYZPolyType(XYZPolyTypeBase): _child_xml_ns_key = {'X': 'sicommon', 'Y': 'sicommon', 'Z': 'sicommon'} class ErrorStatisticsType(ErrorStatisticsTypeBase): _child_xml_ns_key = {'CompositeSCP': 'sicommon', 'Components': 'sicommon', 'AdditionalParms': 'sicommon'} class RadiometricType(RadiometricTypeBase): _child_xml_ns_key = { 'NoiseLevel': 'sicommon', 'RCSSFPoly': 'sicommon', 'SigmaZeroSFPoly': 'sicommon', 'BetaZeroSFPoly': 'sicommon', 'GammaZeroSFPoly': 'sicommon'} class MatchInfoType(MatchInfoTypeBase): _child_xml_ns_key = {'NumMatchTypes': 'sicommon', 'MatchTypes': 'sicommon'} class GeoInfoType(GeoInfoTypeBase): _child_xml_ns_key = { 'Descriptions': 'sicommon', 'Point': 'sicommon', 'Line': 'sicommon', 'Polygon': 'sicommon'} class RadarModeType(RadarModeTypeBase): _child_xml_ns_key = {'ModeType': 'sicommon', 'ModeID': 'sicommon'} class ReferencePointType(Serializable): """ A reference point. """ _fields = ('ECEF', 'Point', 'name') _required = ('ECEF', 'Point') _set_as_attribute = ('name', ) _child_xml_ns_key = {'ECEF': 'sicommon', 'Point': 'sicommon'} # Descriptor ECEF = SerializableDescriptor( 'ECEF', XYZType, _required, strict=DEFAULT_STRICT, docstring='The ECEF coordinates of the reference point.') # type: XYZType Point = SerializableDescriptor( 'Point', RowColDoubleType, _required, strict=DEFAULT_STRICT, docstring='The pixel coordinates of the reference point.') # type: RowColDoubleType name = StringDescriptor( 'name', _required, strict=DEFAULT_STRICT, docstring='Used for implementation specific signifier for the reference point.') # type: Union[None, str] def __init__(self, ECEF=None, Point=None, name=None, **kwargs): """ Parameters ---------- ECEF : XYZType|numpy.ndarray|list|tuple Point : RowColDoubleType|numpy.ndarray|list|tuple name : None|str kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.ECEF = ECEF self.Point = Point self.name = name super(ReferencePointType, self).__init__(**kwargs) # The end of the SICommon namespace ##################### ################# # Filter Type class PredefinedFilterType(Serializable): """ The predefined filter type. """ _fields = ('DatabaseName', 'FilterFamily', 'FilterMember') _required = () # Descriptor DatabaseName = StringEnumDescriptor( 'DatabaseName', ('BILINEAR', 'CUBIC', 'LAGRANGE', 'NEAREST NEIGHBOR'), _required, strict=DEFAULT_STRICT, docstring='The filter name.') # type: str FilterFamily = IntegerDescriptor( 'FilterFamily', _required, strict=DEFAULT_STRICT, docstring='The filter family number.') # type: int FilterMember = IntegerDescriptor( 'FilterMember', _required, strict=DEFAULT_STRICT, docstring='The filter member number.') # type: int def __init__(self, DatabaseName=None, FilterFamily=None, FilterMember=None, **kwargs): """ Parameters ---------- DatabaseName : None|str FilterFamily : None|int FilterMember : None|int kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.DatabaseName = DatabaseName self.FilterFamily = FilterFamily self.FilterMember = FilterMember super(PredefinedFilterType, self).__init__(**kwargs) class FilterKernelType(Serializable): """ The filter kernel parameters. Provides the specifics for **either** a predefined or custom filter kernel. """ _fields = ('Predefined', 'Custom') _required = () _choice = ({'required': True, 'collection': ('Predefined', 'Custom')}, ) # Descriptor Predefined = SerializableDescriptor( 'Predefined', PredefinedFilterType, _required, strict=DEFAULT_STRICT, docstring='') # type: PredefinedFilterType Custom = StringEnumDescriptor( 'Custom', ('GENERAL', 'FILTER BANK'), _required, strict=DEFAULT_STRICT, docstring='') # type: str def __init__(self, Predefined=None, Custom=None, **kwargs): """ Parameters ---------- Predefined : None|PredefinedFilterType Custom : None|str kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Predefined = Predefined self.Custom = Custom super(FilterKernelType, self).__init__(**kwargs) class BankCustomType(Serializable, Arrayable): """ A custom filter bank array. """ __slots__ = ('_coefs', ) _fields = ('Coefs', 'numPhasings', 'numPoints') _required = ('Coefs', ) _numeric_format = {'Coefs': FLOAT_FORMAT} def __init__(self, Coefs=None, **kwargs): """ Parameters ---------- Coefs : numpy.ndarray|list|tuple kwargs """ self._coefs = None if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Coefs = Coefs super(BankCustomType, self).__init__(**kwargs) @property def numPhasings(self): """ int: The number of phasings [READ ONLY] """ return self._coefs.shape[0] - 1 @property def numPoints(self): """ int: The number of points [READ ONLY] """ return self._coefs.shape[1] - 1 @property def Coefs(self): """ numpy.ndarray: The two-dimensional filter coefficient array of dtype=float64. Assignment object must be a two-dimensional numpy.ndarray, or naively convertible to one. .. Note:: this returns the direct coefficient array. Use the `get_array()` method to get a copy of the coefficient array of specified data type. """ return self._coefs @Coefs.setter def Coefs(self, value): if value is None: raise ValueError('The coefficient array for a BankCustomType instance must be defined.') if isinstance(value, (list, tuple)): value = numpy.array(value, dtype=numpy.float64) if not isinstance(value, numpy.ndarray): raise ValueError( 'Coefs for class BankCustomType must be a list or numpy.ndarray. Received type {}.'.format(type(value))) elif len(value.shape) != 2: raise ValueError( 'Coefs for class BankCustomType must be two-dimensional. Received numpy.ndarray ' 'of shape {}.'.format(value.shape)) elif not value.dtype.name == 'float64': value = numpy.cast[numpy.float64](value) self._coefs = value def __getitem__(self, item): return self._coefs[item] def __setitem__(self, item, value): self._coefs[item] = value @classmethod def from_array(cls, array): # type: (numpy.ndarray) -> BankCustomType if array is None: return None return cls(Coefs=array) def get_array(self, dtype=numpy.float64): """ Gets **a copy** of the coefficent array of specified data type. Parameters ---------- dtype : str|numpy.dtype|numpy.number numpy data type of the return Returns ------- numpy.ndarray two-dimensional coefficient array """ return numpy.array(self._coefs, dtype=dtype) @classmethod def from_node(cls, node, xml_ns, ns_key=None, kwargs=None): num_phasings = int(node.attrib['numPhasings']) num_points = int(node.attrib['numPoints']) coefs = numpy.zeros((num_phasings+1, num_points+1), dtype=numpy.float64) ckey = cls._child_xml_ns_key.get('Coefs', ns_key) coef_nodes = find_children(node, 'Coef', xml_ns, ckey) for cnode in coef_nodes: ind1 = int(cnode.attrib['phasing']) ind2 = int(cnode.attrib['point']) val = float(get_node_value(cnode)) coefs[ind1, ind2] = val return cls(Coefs=coefs) def to_node(self, doc, tag, ns_key=None, parent=None, check_validity=False, strict=DEFAULT_STRICT, exclude=()): if parent is None: parent = doc.getroot() if ns_key is None: node = create_new_node(doc, tag, parent=parent) else: node = create_new_node(doc, '{}:{}'.format(ns_key, tag), parent=parent) if 'Coefs' in self._child_xml_ns_key: ctag = '{}:Coef'.format(self._child_xml_ns_key['Coefs']) elif ns_key is not None: ctag = '{}:Coef'.format(ns_key) else: ctag = 'Coef' node.attrib['numPhasings'] = str(self.numPhasings) node.attrib['numPoints'] = str(self.numPoints) fmt_func = self._get_formatter('Coefs') for i, val1 in enumerate(self._coefs): for j, val in enumerate(val1): # if val != 0.0: # should we serialize it sparsely? cnode = create_text_node(doc, ctag, fmt_func(val), parent=node) cnode.attrib['phasing'] = str(i) cnode.attrib['point'] = str(j) return node def to_dict(self, check_validity=False, strict=DEFAULT_STRICT, exclude=()): out = OrderedDict() out['Coefs'] = self.Coefs.tolist() return out class FilterBankType(Serializable): """ The filter bank type. Provides the specifics for **either** a predefined or custom filter bank. """ _fields = ('Predefined', 'Custom') _required = () _choice = ({'required': True, 'collection': ('Predefined', 'Custom')}, ) # Descriptor Predefined = SerializableDescriptor( 'Predefined', PredefinedFilterType, _required, strict=DEFAULT_STRICT, docstring='The predefined filter bank type.') # type: PredefinedFilterType Custom = SerializableDescriptor( 'Custom', BankCustomType, _required, strict=DEFAULT_STRICT, docstring='The custom filter bank.') # type: BankCustomType def __init__(self, Predefined=None, Custom=None, **kwargs): """ Parameters ---------- Predefined : None|PredefinedFilterType Custom : None|BankCustomType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.Predefined = Predefined self.Custom = Custom super(FilterBankType, self).__init__(**kwargs) class FilterType(Serializable): """ Filter parameters for a variety of purposes. Provides **either** the filter bank or filter kernel parameters. """ _fields = ('FilterName', 'FilterKernel', 'FilterBank', 'Operation') _required = ('FilterName', 'Operation') _choice = ({'required': True, 'collection': ('FilterKernel', 'FilterBank')}, ) # Descriptor FilterName = StringDescriptor( 'FilterName', _required, strict=DEFAULT_STRICT, docstring='The name of the filter.') # type : str FilterKernel = SerializableDescriptor( 'FilterKernel', FilterKernelType, _required, strict=DEFAULT_STRICT, docstring='The filter kernel.') # type: FilterKernelType FilterBank = SerializableDescriptor( 'FilterBank', FilterBankType, _required, strict=DEFAULT_STRICT, docstring='The filter bank.') # type: FilterBankType Operation = StringEnumDescriptor( 'Operation', ('CONVOLUTION', 'CORRELATION'), _required, strict=DEFAULT_STRICT, docstring='') # type: str def __init__(self, FilterName=None, FilterKernel=None, FilterBank=None, Operation=None, **kwargs): """ Parameters ---------- FilterName : str FilterKernel : None|FilterKernelType FilterBank : None|FilterBankType Operation : str kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.FilterName = FilterName self.FilterKernel = FilterKernel self.FilterBank = FilterBank self.Operation = Operation super(FilterType, self).__init__(**kwargs) ################ # NewLookupTableType class PredefinedLookupType(Serializable): """ The predefined lookup table type. Allows for reference **either** by name, or family/member id number. """ _fields = ('DatabaseName', 'RemapFamily', 'RemapMember') _required = () # Descriptor DatabaseName = StringDescriptor( 'DatabaseName', _required, strict=DEFAULT_STRICT, docstring='Database name of LUT to use.') # type: str RemapFamily = IntegerDescriptor( 'RemapFamily', _required, strict=DEFAULT_STRICT, docstring='The lookup family number.') # type: int RemapMember = IntegerDescriptor( 'RemapMember', _required, strict=DEFAULT_STRICT, docstring='The lookup member number.') # type: int def __init__(self, DatabaseName=None, RemapFamily=None, RemapMember=None, **kwargs): """ Parameters ---------- DatabaseName : None|str RemapFamily : None|int RemapMember : None|int kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.DatabaseName = DatabaseName self.RemapFamily = RemapFamily self.RemapMember = RemapMember super(PredefinedLookupType, self).__init__(**kwargs) class LUTInfoType(Serializable, Arrayable): """ The lookup table - basically just a one or two-dimensional unsigned integer array of bit depth 8 or 16. """ __slots__ = ('_lut_values', ) _fields = ('LUTValues', 'numLuts', 'size') _required = ('LUTValues', 'numLuts', 'size') def __init__(self, LUTValues=None, **kwargs): """ Parameters ---------- LUTValues : numpy.ndarray The dtype must be `uint8` or `uint16`, and the dimension must be one or two. kwargs """ self._lut_values = None if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.LUTValues = LUTValues super(LUTInfoType, self).__init__(**kwargs) @property def LUTValues(self): """ numpy.ndarray: the two-dimensional look-up table, where the dtype must be `uint8` or `uint16`. The first dimension should correspond to entries (i.e. size of the lookup table), and the second dimension should correspond to bands (i.e. number of bands). """ return self._lut_values @LUTValues.setter def LUTValues(self, value): if value is None: self._lut_values = None return if isinstance(value, (tuple, list)): value = numpy.array(value, dtype=numpy.uint8) if not isinstance(value, numpy.ndarray) or value.dtype.name not in ('uint8', 'uint16'): raise ValueError( 'LUTValues for class LUTInfoType must be a numpy.ndarray of dtype uint8 or uint16.') if value.ndim != 2: raise ValueError('LUTValues for class LUTInfoType must be two-dimensional.') self._lut_values = value @property def size(self): """ int: the size of each lookup table """ if self._lut_values is None: return 0 else: return self._lut_values.shape[0] @property def numLUTs(self): """ int: The number of lookup tables """ if self._lut_values is None: return 0 else: return self._lut_values.shape[1] def __len__(self): if self._lut_values is None: return 0 return self._lut_values.shape[0] def __getitem__(self, item): return self._lut_values[item] @classmethod def from_array(cls, array): """ Create from the lookup table array. Parameters ---------- array: numpy.ndarray|list|tuple Must be two-dimensional. If not a numpy.ndarray, this will be naively interpreted as `uint8`. Returns ------- LUTInfoType """ if array is None: return None return cls(LUTValues=array) def get_array(self, dtype=numpy.uint8): """ Gets **a copy** of the coefficent array of specified data type. Parameters ---------- dtype : str|numpy.dtype|numpy.number numpy data type of the return Returns ------- numpy.ndarray the lookup table array """ return numpy.array(self._lut_values, dtype=dtype) @classmethod def from_node(cls, node, xml_ns, ns_key=None, kwargs=None): dim1 = int(node.attrib['size']) dim2 = int(node.attrib['numLuts']) arr = numpy.zeros((dim1, dim2), dtype=numpy.uint16) lut_key = cls._child_xml_ns_key.get('LUTValues', ns_key) lut_nodes = find_children(node, 'LUTValues', xml_ns, lut_key) for i, lut_node in enumerate(lut_nodes): arr[:, i] = [str(el) for el in get_node_value(lut_node)] if numpy.max(arr) < 256: arr = numpy.cast[numpy.uint8](arr) return cls(LUTValues=arr) def to_node(self, doc, tag, ns_key=None, parent=None, check_validity=False, strict=DEFAULT_STRICT, exclude=()): def make_entry(arr): value = ' '.join(str(el) for el in arr) entry = create_text_node(doc, ltag, value, parent=node) entry.attrib['lut'] = str(arr.size) if parent is None: parent = doc.getroot() if ns_key is None: node = create_new_node(doc, tag, parent=parent) else: node = create_new_node(doc, '{}:{}'.format(ns_key, tag), parent=parent) if 'LUTValues' in self._child_xml_ns_key: ltag = '{}:LUTValues'.format(self._child_xml_ns_key['LUTValues']) elif ns_key is not None: ltag = '{}:LUTValues'.format(ns_key) else: ltag = 'LUTValues' if self._lut_values is not None: node.attrib['numLuts'] = str(self.numLUTs) node.attrib['size'] = str(self.size) if self._lut_values.ndim == 1: make_entry(self._lut_values) else: for j in range(self._lut_values.shape[1]): make_entry(self._lut_values[:, j]) return node def to_dict(self, check_validity=False, strict=DEFAULT_STRICT, exclude=()): out = OrderedDict() if self.LUTValues is not None: out['LUTValues'] = self.LUTValues.tolist() return out class CustomLookupType(Serializable): """ A custom lookup table. """ _fields = ('LUTInfo', ) _required = ('LUTInfo', ) # Descriptor LUTInfo = SerializableDescriptor( 'LUTInfo', LUTInfoType, _required, strict=DEFAULT_STRICT, docstring='The lookup table.') # type: LUTInfoType def __init__(self, LUTInfo=None, **kwargs): """ Parameters ---------- LUTInfo: LUTInfoType|numpy.ndarray|list|tuple kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.LUTInfo = LUTInfo super(CustomLookupType, self).__init__(**kwargs) class NewLookupTableType(Serializable): """ The lookup table. Allows **either** a reference to a prefined lookup table, or custom lookup table array. """ _fields = ('LUTName', 'Predefined', 'Custom') _required = ('LUTName', ) _choice = ({'required': True, 'collection': ('Predefined', 'Custom')}, ) # Descriptor LUTName = StringDescriptor( 'LUTName', _required, strict=DEFAULT_STRICT, docstring='The lookup table name') # type: str Predefined = SerializableDescriptor( 'Predefined', PredefinedLookupType, _required, strict=DEFAULT_STRICT, docstring='') # type: PredefinedLookupType Custom = SerializableDescriptor( 'Custom', CustomLookupType, _required, strict=DEFAULT_STRICT, docstring='') # type: CustomLookupType def __init__(self, LUTName=None, Predefined=None, Custom=None, **kwargs): """ Parameters ---------- LUTName : str Predefined : None|PredefinedLookupType Custom : None|CustomLookupType kwargs """ if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.LUTName = LUTName self.Predefined = Predefined self.Custom = Custom super(NewLookupTableType, self).__init__(**kwargs)
30,510
31.252643
120
py
sarpy
sarpy-master/sarpy/io/product/sidd3_elements/Compression.py
""" Types implementing the SIDD 3.0 Compression Parameters """ __classification__ = 'UNCLASSIFIED' # SIDD 3.0 reuses the SIDD 2.0 types. Make those symbols available in this module. from sarpy.io.product.sidd2_elements.Compression import ( J2KSubtype, J2KType, CompressionType, ) __REUSED__ = ( # to avoid unused import lint errors J2KSubtype, J2KType, CompressionType, )
400
21.277778
83
py
sarpy
sarpy-master/sarpy/io/product/sidd3_elements/Measurement.py
""" Types implementing the SIDD 3.0 Measurement Parameters """ __classification__ = 'UNCLASSIFIED' # SIDD 3.0 reuses the SIDD 2.0 types. Make those symbols available in this module. from sarpy.io.product.sidd2_elements.Measurement import ( BaseProjectionType, MeasurableProjectionType, ProductPlaneType, PlaneProjectionType, GeographicProjectionType, CylindricalProjectionType, PolynomialProjectionType, MeasurementType, ) __REUSED__ = ( # to avoid unused import lint errors BaseProjectionType, MeasurableProjectionType, ProductPlaneType, PlaneProjectionType, GeographicProjectionType, CylindricalProjectionType, PolynomialProjectionType, MeasurementType, )
726
24.964286
83
py
sarpy
sarpy-master/sarpy/io/product/sidd3_elements/base.py
__classification__ = "UNCLASSIFIED" DEFAULT_STRICT = False FLOAT_FORMAT = '0.17G'
85
11.285714
35
py