<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">"""

Description:
This script was written to create and display figures comparing locations of two different patients. This is used to
check the analysis points quickly to make sure they make sense and also to confirm that we are seeing similar
landmarks in the ultrasound images across patients.


Getting started:
    A dialog box will appear, type in the desired location (for example UA_L for upper arm lateral images). A
    checkbox list will appear with all of the available locations and patients that were analyzed using TA_sfm
    software. Select the six trials you would like to include. At this point, the code can only produce images for
    anatomical trials (proximal, central, and distal) for each limb anatomical location.

    Original Author:
        Erica Morrill
        Department of Biomedical Engineering
        Lerner Research Institute
        Cleveland Clinic
        Cleveland, OH
        morrile2@ccf.org

"""

import xml.etree.ElementTree as ET
import os
import Tkinter as tk
import pandas
import tkFileDialog
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import numpy as np
import tkSimpleDialog
from scipy.misc import imread, imshow

class FileSelectionApp(tk.Tk):
    """Application to display all of the trials in a list"""

    def __init__(self):
        tk.Tk.__init__(self)

        home = os.path.expanduser('~')
        for dirname, subdirList, fileList in os.walk(home):
            for dir in subdirList:
                if "MULTIS_test" in dir and "studies" not in dirname:
                    multis_dir = dirname + '/' + dir

        print multis_dir
        try:
            multis_dir
        except NameError:
            multis_dir = tkFileDialog.askdirectory(title="Open MULTIS trials directory")

        self.directory = multis_dir
        self.getSubjects()
        self.title('Select Files')

        self.columnconfigure(0, weight=1)

        self.var = []
        self.i = 0
        for item in self.subFiles:
            self.var.append(tk.IntVar())
            c = tk.Checkbutton(self, text=item, variable=self.var[self.i])
            c.grid(column = 0, row=self.i, sticky='w')
            self.i +=1

        # self.minsize(200, 100/(self.i))

        tk.Button(self, text="Okay", command=self.checkBoxes).grid(row=2, column =1, sticky='ens')
        tk.Button(self, text="Select All", command=self.SelectAll).grid(row=0, column=1, sticky='ens')
        tk.Button(self, text="Clear Selection", command=self.ClearSelection).grid(row=1, column=1, sticky = 'ens')


    def yview(self, *args):
        apply(self.yview, args)

    def checkBoxes(self):

        locations = ['LA_A', 'LA_L', 'LA_P', 'LA_M', 'UA_A', 'UA_L', 'UA_P', 'UA_M', 'LL_A', 'LL_L', 'LL_P', 'LL_M',
                     'UL_A', 'UL_L', 'UL_P', 'UL_M']
        # locations = ['LA_A'] #Used for testing

        for l1 in locations:
            for l2 in ['C', 'C', 'D']:
                loc = l1 + l2
                count = 0
                self.text = loc
                self.images = []
                self.num = []
                for bb in self.var:
                    if bb.get() == 1:
                        # print(self.subFiles)
                        files, nums = self.getImages(loc, self.dir[count])
                        self.images = self.images + files
                        self.num = self.num + nums
                    count += 1

                zipped = zip(self.images, self.num)
                zipped.sort(key=lambda t:t[1])
                self.images, self.num = zip(*zipped)
                # self.destroy()
                self.plot_data()
        self.quit()

    def plot_data(self):

        fig_idx = len(self.images)/25+1
        for i in range(fig_idx):
            images = self.images[i*25:(i+1)*25]
            num = self.num[i*25:(i+1)*25]
            fig, ax = plt.subplots(5, 5, figsize = (16,13))

            if self.text[0] == 'U':
                title = 'Upper'
            elif self.text[0] == 'L':
                title = 'Lower'

            if self.text[1] == 'A':
                title += ' Arm'
            elif self.text[1] == 'L':
                title += ' Leg'

            if self.text[3] == 'A':
                title += ' Anterior'
            elif self.text[3] == 'L':
                title += ' Lateral'
            elif self.text[3] == 'P':
                title += ' Posterior'
            elif self.text[3] == 'M':
                title += ' Medial'

            if self.text[4] == 'P':
                title += ' Proximal'
            elif self.text[4] == 'C':
                title += ' Central'
            elif self.text[4] == 'D':
                title += ' Distal'

            for p, img in enumerate(images):
                ax[p//5,p%5].imshow(imread(img))
                ax[p // 5, p % 5].set_xlim([165, 1170])
                ax[p // 5, p % 5].set_ylim([875, 125])
                ax[p // 5, p % 5].axis("off")
                ax[p//5,p%5].set_title("MULTIS"+num[p])

            for p in range(len(images), 25):
                ax[p//5, p%5].axis("off")

            fig.suptitle(title, fontsize=20, x = 0.525)
            fig.tight_layout()
            fig.subplots_adjust(top = 0.92, left = 0.05, right = 0.95)


            if not os.path.isdir(self.directory+'/SummaryFigures/'):
                os.makedirs(self.directory+'/SummaryFigures/')

            plt.savefig(self.directory + '/SummaryFigures/' + self.text+'_' + str(i) +'.png')
            fig.close()
            # plt.show()

    def SelectAll(self):
        for bb in self.var:
            bb.set(1)

    def ClearSelection(self):
        for bb in self.var:
            bb.set(0)

    def getSubjects(self):
        self.subFiles = []
        self.dir = []
        for dirname,subdirList,fileList in os.walk(self.directory):
            for file in fileList:
                if "TA_inclusion.xml" in file:
                    self.dir.append(os.path.split(os.path.split(dirname)[0])[0])
                    self.subFiles.append(os.path.split(os.path.split(os.path.split(dirname)[0])[0])[1])
        sortedTrials = sorted(zip(self.subFiles, self.dir))
        self.subFiles, self.dir = zip(*sortedTrials)


    def getImages(self, location, directory):
        loc_files = []
        nums = []

        thick_xml_list = self.parseXMLinclusion(location, os.path.join(os.path.join(os.path.join(directory,'TissueThickness'), 'UltrasoundManual'), os.path.split(directory)[1]+"_TA_inclusion.xml"))

        # print thick_xml_list
        for th_xml in thick_xml_list:
            loc_files.append(os.path.join(os.path.join(os.path.join(directory, os.path.split(th_xml)[0]), 'ThicknessPNG'), os.path.split(th_xml)[1][0:-4]+'.png'))
            nums.append(os.path.split(th_xml)[1][10:13])

        # print loc_files, nums
        return loc_files, nums

    def parseXMLinclusion(self, location, inclusion):
        doc = ET.parse(inclusion)
        root = doc.getroot()
        thickness_xmls = []

        for child in root:
            for subChild in child:
                XML = subChild.attrib["Anatomical"]
                if XML != "None" and XML[-28:-27] == "A" and XML[-34:-29] == location:
                    thickness_xmls.append(XML)

        return thickness_xmls

if __name__ == "__main__":

    app = FileSelectionApp()
    app.mainloop()</pre></body></html>