<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">import xml.etree.ElementTree as ET
from lxml import etree
import XMLparser
import tkFileDialog
import os
import zipfile

def prettyPrintXml(xmlFilePathToPrettyPrint):
    """Pretty print the xml file after all frames have been analyzed"""
    assert xmlFilePathToPrettyPrint is not None
    parser = etree.XMLParser(resolve_entities=False, remove_blank_text=True)
    document = etree.parse(xmlFilePathToPrettyPrint, parser)
    document.write(xmlFilePathToPrettyPrint, pretty_print=True, encoding='ISO-8859-1', xml_declaration=True)

def newCluster(subj, tdms_path, root_incl, xml_inclusion, thick_file):
    cluster_new = ET.SubElement(subj, 'Cluster')
    # src_tdms = ET.SubElement(cluster_new, 'TDMSSource', attrib={"Filename": tdms_path[-30:]})
    # src_TA = ET.SubElement(cluster_new, 'ThicknessSource', attrib={"Filename":thick_file})
    # tree = ET.ElementTree(root_incl)
    # tree.write(xml_inclusion, xml_declaration=True)

def TAxmlFormat(subj, xml_inclusion):
    root = ET.Element("Thicknesses")
    root.set("subject", subj)
    SegLocations(ET.SubElement(root, "UpperArm"))
    SegLocations(ET.SubElement(root, "LowerArm"))
    SegLocations(ET.SubElement(root, "UpperLeg"))
    SegLocations(ET.SubElement(root, "LowerLeg"))

    return root
    # tree = ET.ElementTree(root)
    # tree.write(xml_inclusion, xml_declaration=True)

def SegLocations(seg):
    ET.SubElement(seg, "ProximalLateral").set('Anatomical', 'None')
    ET.SubElement(seg, "ProximalAnterior").set('Anatomical', 'None')
    ET.SubElement(seg, "ProximalMedial").set('Anatomical', 'None')
    ET.SubElement(seg, "ProximalPosterior").set('Anatomical', 'None')
    ET.SubElement(seg, "CentralLateral").set('Anatomical', 'None')
    CA = ET.SubElement(seg, "CentralAnterior")
    CA.set('Anatomical', 'None')
    CA.set('Indentation', 'None')
    ET.SubElement(seg, "CentralMedial").set('Anatomical', 'None')
    CP = ET.SubElement(seg, "CentralPosterior")
    CP.set('Anatomical', 'None')
    CP.set('Indentation', 'None')
    ET.SubElement(seg, "DistalLateral").set('Anatomical', 'None')
    ET.SubElement(seg, "DistalAnterior").set('Anatomical', 'None')
    ET.SubElement(seg, "DistalMedial").set('Anatomical', 'None')
    ET.SubElement(seg, "DistalPosterior").set('Anatomical', 'None')

def edit_attrib(thickfile, root):

    if thickfile[-34:-32] == 'UA':
        seg = "UpperArm"
    elif thickfile[-34:-32] == 'LA':
        seg = "LowerArm"
    elif thickfile[-34:-32] == 'UL':
        seg = "UpperLeg"
    elif thickfile[-34:-32] == 'LL':
        seg = "LowerLeg"

    if thickfile[-30:-29] == 'P':
        loc = 'Proximal'
    elif thickfile[-30:-29] == 'C':
        loc = 'Central'
    elif thickfile[-30:-29] == 'D':
        loc = 'Distal'

    if thickfile[-31:-30] == 'L':
        loc = loc + 'Lateral'
    elif thickfile[-31:-30] == 'M':
        loc = loc + 'Medial'
    elif thickfile[-31:-30] == 'A':
        loc = loc + 'Anterior'
    elif thickfile[-31:-30] == 'P':
        loc = loc + 'Posterior'

    if thickfile[-28:-27] == 'A':
        a = 'Anatomical'
    elif thickfile[-28:-27] == 'I':
        a = 'Indentation'

    root.find(seg).find(loc).set(a, thickfile)

def create_zip(path, ziph):
    path = os.path.join(path, "TissueThickness")
    for root, dirs, files in os.walk(path):
        for file in files:
            if analysis_type in root:
                ziph.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), start=os.path.split(path)[0]))

def create_xml(subj_path, analysis_type):
    """Create xml file with forces, moments, and thicknesses"""

    sub_xml = os.path.join(subj_path, "Configuration", os.path.split(subj_path)[1]+'.xml')
    i = 0
    # Check if an xml file exists for this image. If TRUE, create a thickness analysis inclusion file.
    if os.path.exists(sub_xml):

        XML = ET.parse(sub_xml)
        root = XML.getroot()
        us_file_array = root.find('Subject_Data').find('Ultrasound_File_Path_Array')

        # Create inclusion xml
        xml_inclusion = os.path.join(os.path.join(os.path.join(subj_path, "TissueThickness"), analysis_type), os.path.split(subj_path)[1]+'_TA_inclusion.xml')
        subj = os.path.split(subj_path)[1]
        root_incl = TAxmlFormat(subj, xml_inclusion)

        for file in us_file_array.findall('Ultrasound_File_Path_Cluster'):
            clusters = file.find('TDMS_File_Path_Array').findall('Cluster')
            cluster = clusters[-1] #Take the last accepted trial
            thick_file = 'None'

            if cluster.find('Accepted').text == 'TRUE':
                tdms_path = cluster.find('Data_File_Path').text
                for dirName, subdirList, fileList in os.walk(os.path.join(os.path.join(subj_path, "TissueThickness"), analysis_type)):
                    if subj[0:1] == 'M':
                        for file in fileList:
                            if file.endswith('.xml') and file[0:34] == str(tdms_path[-30:-5]+ '_manThick'):
                                # thick_file = os.path.join("TissueThickness", os.path.join(analysis_type, file))
                                thick_file = file
                    elif subj[0:1] == 'C':
                        for file in fileList:
                            if file.endswith('.xml') and file[0:35] == str(tdms_path[-31:-5] + '_manThick'):
                                # thick_file = os.path.join("TissueThickness", os.path.join(analysis_type, file))
                                thick_file = file
                if thick_file != 'None':
                    edit_attrib(thick_file, root_incl)
                else:
                    print(subj, tdms_path)

                i+=1

        tree = ET.ElementTree(root_incl)
        tree.write(xml_inclusion, xml_declaration=True)
        prettyPrintXml(os.path.join(subj_path, xml_inclusion))

    os.chdir(os.path.split(subj_path)[0])
    zipf = zipfile.ZipFile(os.path.split(subj_path)[1]+'_TA.zip', 'w', zipfile.ZIP_DEFLATED)
    create_zip(subj_path, zipf)
    zipf.close()

    return (i)


# Define path for subject

# subj_path = tkFileDialog.askdirectory()
# dir_multis = '/home/morrile2/Documents/MULTIS Data/MULTIS_test'
# subj_path = 'MULTIS067-1'
dir_multis = '/home/morrile2/Documents/MULTIS Data/MULTIS_invitro'
subj_path = 'CMULTIS002-2'
analysis_type = 'CTManual_zProbe'
# dir_list = os.listdir('/home/morrile2/Documents/MULTIS Data/MULTIS_test')
dir_list = [subj_path]
for subj in dir_list:
    print subj
    if "MULTIS" in subj:
        subj_path = os.path.join(dir_multis, subj)
        ii = create_xml(subj_path, analysis_type)
        print("Total xmls in Inclusion file = %i" % (ii))

</pre></body></html>