pyMez.Code.DataHandlers.MUFModels module
A module that holds the models associated with the Microwave Uncertainty Framework. Most models are xml based. Has an interface for running .net as scripts
Examples
>>vna_uncert=MUFVNAUncert("MyUncertaintyMenu.VNAUncert") >>vna_uncert.get_results_directory()
MUFModels Example
Requirements
Help
#----------------------------------------------------------------------------- # Name: MUFModels # Purpose: A module that holds the models associated with the Microwave Uncertainty Framework # Author: Aric Sanders # Created: 3/31/2016 # License: MIT License #----------------------------------------------------------------------------- """ A module that holds the models associated with the Microwave Uncertainty Framework. Most models are xml based. Has an interface for running .net as scripts Examples -------- #!python >>vna_uncert=MUFVNAUncert("MyUncertaintyMenu.VNAUncert") >>vna_uncert.get_results_directory() <h3><a href="../../../Examples/Html/MUFModels_Example.html">MUFModels Example</a></h3> Requirements ------------ + [sys](https://docs.python.org/2/library/sys.html) + [os](https://docs.python.org/2/library/os.html?highlight=os#module-os) + [types](https://docs.python.org/2/library/types.html) + [pyMez](https://github.com/aricsanders/pyMez) + [pythonnet][https://github.com/pythonnet/pythonnet] Help --------------- <a href="./index.html">`pyMez.Code.DataHandlers`</a> <div> <a href="../../../pyMez_Documentation.html">Documentation Home</a> | <a href="../../index.html">API Documentation Home</a> | <a href="../../../Examples/html/Examples_Home.html">Examples Home</a> | <a href="../../../Reference_Index.html">Index</a> </div>""" #----------------------------------------------------------------------------- # Standard Imports import sys import os import datetime from types import * #----------------------------------------------------------------------------- # Third Party Imports sys.path.append(os.path.join(os.path.dirname( __file__ ), '..','..')) try: from Code.DataHandlers.XMLModels import * except: print("The module pyMez.Code.DataHandlers.XMLModels was not found," "please put it on the python path") raise ImportError try: from Code.DataHandlers.GeneralModels import * except: print("The module pyMez.Code.DataHandlers.XMLModels was not found," "please put it on the python path") raise ImportError try: import clr CLR=True except: print("The module clr had an error or was not found. Please check that it is on the path and " "working properly") CLR=False try: import matplotlib.pyplot as plt except: print("The module matplotlib had an error or was not found. Please check that it is on the path and " "working properly") raise ImportError #----------------------------------------------------------------------------- # Module Constants SCRIPTABLE_MUF_LOCATION=r"C:\Share\MUF-develop\VNAUncertainty\bin\Debug" """Location of the MUF executable with modifications to make it scriptable.""" MODEL_UNIT_LIST=["Unitless","cm","mm","um","GHz","pf","nH","ohm","mho","pf/cm","ns","ps","mV","mA"] MODEL_DISTRIBUTION_LIST=["Rectangular","Arc-sine","Bernoulli (binary)","Gaussain", "2-D Uniform-Distribution Radius","2-D Gaussian-Distribution Radius"] #----------------------------------------------------------------------------- # Module Functions def make_parameter_table(parameter_directory): """Creates a table from all the parameters in the parameter_directory, returns an AsciiDataTable""" file_names=os.listdir(parameter_directory) parameter_files=[] for file_name in file_names: extension = file_name.split(".")[-1] if re.search("parameter",extension,re.IGNORECASE) and extension not in ["parameterviewer"] : parameter_files.append(os.path.join(parameter_directory,file_name)) #print("{0} is {1}".format("parameter_files",parameter_files)) parameter_models=[MUFParameter(file_name) for file_name in parameter_files] column_names=["Parameter_Name","Value","Distribution_Type","Width","Standard_Uncertainty","Units"] data=[] for index,parameter in enumerate(parameter_models): print(("Parameter Number: {0}, Name:{1}".format(index,parameter.get_mechanism_name()) )) row=[os.path.split(parameter.get_mechanism_name())[-1].split(".")[0], parameter.get_value(),parameter.get_distribution_type(), parameter.get_distribution_width(),parameter.get_standard_uncertainty(), parameter.get_units()] data.append(row) data_table=AsciiDataTable(column_names=column_names,data=data) return data_table #----------------------------------------------------------------------------- # Module Classes class MUFParameter(XMLBase): def get_value(self): """Returns the value of the parameter""" mechanism_value=self.etree.findall(".//MechanismValue")[0] value=mechanism_value.attrib["ControlText"] return float(value) def set_value(self,value): """Sets the value (center of distribution)""" mechanism_value=self.etree.findall(".//MechanismValue")[0] mechanism_value.attrib["ControlText"]=str(value) self.update_document() def get_distribution_type(self): """Returns the type of Distribution. The choices are held in DistributionType/Item.""" distribution_type=self.etree.findall(".//DistributionType")[0] text=distribution_type.attrib["ControlText"] return text def set_distribution_type(self,distribution_type): """Sets the distribution type, accepts an integer or text value. See the constant MODEL_DISTRIBUTION_LIST for possibilities. Rectangular is 0, Gaussian is 3. """ if type(distribution_type) in [IntType,FloatType]: type_number=distribution_type type_name=MODEL_DISTRIBUTION_LIST[distribution_type] elif distribution_type in MODEL_DISTRIBUTION_LIST: type_number=MODEL_DISTRIBUTION_LIST.index(distribution_type) type_name=distribution_type else: print(("Could not set the type {0} please choose a" " type or index from {1}".format(distribution_type,MODEL_DISTRIBUTION_LIST))) return distribution_type_tag = self.etree.findall(".//DistributionType")[0] distribution_type_tag.attrib["ControlText"]=type_name distribution_type_tag.attrib["SelectedIndex"]=type_number self.update_document() def get_distribution_width(self): """Returns the wdith of the distribution.""" distribution_width=self.etree.findall(".//DistributionLimits")[0] text=distribution_width.attrib["ControlText"] return text def set_distribution_width(self,distribution_width): """Sets the distribution width""" distribution_width = self.etree.findall(".//DistributionLimits")[0] distribution_width.attrib["ControlText"]=str(distribution_width) self.update_document() def get_units(self): """Returns the units of the parameter""" units=self.etree.findall(".//Units")[0] text=units.attrib["ControlText"] return text def set_units(self,units): """Sets the units of the parameter can accept either an index or value. Look at MODEL_UNIT_LIST for complete set of possibilities""" if type(units) in [IntType,FloatType]: unit_number=units unit_name=MODEL_DISTRIBUTION_LIST[units] elif units in MODEL_DISTRIBUTION_LIST: unit_number=MODEL_DISTRIBUTION_LIST.index(units) unit_name=units else: print(("Could not set the units {0} please choose a" " type or index from {1}".format(units,MODEL_UNIT_LIST))) return unit_tag = self.etree.findall(".//Units")[0] unit_tag.attrib["ControlText"]=unit_name unit_tag.attrib["SelectedIndex"]=unit_number self.update_document() def get_mechanism_name(self): """Returns the mechanism name""" units=self.etree.findall(".//MechanismName")[0] text=units.attrib["ControlText"] return text def get_standard_uncertainty(self): """returns the standard uncertainty of the parameter""" uncertainty=self.etree.findall(".//StandardUncertainty")[0] text = uncertainty.attrib["ControlText"] number=float(text.split(":")[-1]) return number class MUFModel(XMLBase): pass class MUFVNAUncert(XMLBase): def get_results_directory(self): "Returns the results directory" results_directory=self.etree.findall(".//MenuStripTextBoxes/ResultsDirectory")[0].attrib["Text"] return results_directory def set_results_directory(self,directory=None): "Sets the results directory, default is the current working directory" if directory is None: directory=os.getcwd() results_directory = self.document.getElementsByTagName("ResultsDirectory")[0] results_directory.setAttribute(attname="Text", value=directory) check_box=self.document.getElementsByTagName("SelectResultsDirectoryToolStripMenuItem")[0] check_box.setAttribute(attname="Checked", value="True") self.update_etree() def get_number_standards(self): "Returns the number of calibration standards in the before calibration" sub_items = self.etree.findall(".//BeforeCalibration/Item") return len(sub_items) def get_standard_definition(self,standard_number=1): "Returns the xml definition of the standard in position standard_number" sub_items = self.etree.findall(".//BeforeCalibration/Item") return etree.tostring(sub_items[standard_number-1]) def get_standard_measurement_locations(self): """Returns the file locations for the measurement of the standards in a form of a list""" standards = self.etree.findall(".//BeforeCalibration/Item/SubItem[@Index='6']") locations=[standard.attrib["Text"] for standard in standards] return locations def set_standard_location(self,standard_location=None,standard_number=1): """Sets the location for the measurement of standard_number""" standards = self.etree.findall(".//BeforeCalibration/Item/SubItem[@Index='6']") standard=standards[standard_number-1] standard.attrib["Text"]=standard_location self.update_document() def get_number_montecarlo(self): "Returns the number of montecarlo simulations" montecarlo_text_box=self.etree.findall(".//MenuStripTextBoxes/NumberMonteCarloSimulations")[0] number_montecarlo=montecarlo_text_box.attrib["Text"] return number_montecarlo def set_number_montecarlo(self,number_montecarlo=100): """Sets the number of montecarlo trials for the menu""" montecarlo_text_box = self.etree.findall(".//MenuStripTextBoxes/NumberMonteCarloSimulations")[0] montecarlo_text_box.attrib["Text"]=str(number_montecarlo) self.update_document() def get_DUTs(self): "Returns the names and locations of DUTs" duts=[] names=[x.attrib["Text"] for x in self.etree.findall(".//DUTMeasurements/Item/SubItem[@Index='0']")] locations=[x.attrib["Text"] for x in self.etree.findall(".//DUTMeasurements/Item/SubItem[@Index='1']")] for index,name in enumerate(names): name_location_dictionary={"name":name,"location":locations[index]} duts.append(name_location_dictionary) return duts def add_DUT(self,location,name=None): """Adds a DUT to the DUTMeasurements element""" # get the name if name is None: name=os.path.basename(location).split(".")[0] # first get the DUTMeasurement element dut_measurement=self.etree.findall(".//DUTMeasurements")[0] # next add one to the count attribute number_standards=int(dut_measurement.attrib["Count"]) number_standards+=1 dut_measurement.attrib["Count"]=str(number_standards) # create a Item item=etree.SubElement(dut_measurement,"Item",attrib={"Count":"2","Index":str(number_standards),"Text":name}) etree.SubElement(item,"SubItem",attrib={"Index":"0","Text":name}) etree.SubElement(item,"SubItem",attrib={"Index":"1","Text":location}) self.update_document() def clear_DUTs(self): """Removes all DUTs""" dut_measurement = self.etree.findall(".//DUTMeasurements")[0] items= self.etree.findall(".//DUTMeasurements/Item") for item in items: dut_measurement.remove(item) self.update_document() class MUFMeasurement(XMLBase): def get_name_parameter_dictionary(self): """Returns a dictionary of 'name':'parameter_name' pairs to correlate covariance files with their mechanism names""" out_dictionary={} try: names=[x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='0']")] mechanisms=[x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='2']")] for index,name in enumerate(names): split_parameter_name=os.path.split(mechanisms[index])[-1] parameter_name=split_parameter_name.split(".")[0] out_dictionary[name]=parameter_name return out_dictionary except: print("Could not retrieve the name - parameter dictionary") pass def get_covariance_dictionary(self): """Returns a list of dictionaries that has the keys name, location, and parameter_location""" covariance_list=[] try: names=[x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='0']")] locations=[x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='1']")] mechanisms = [x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='2']")] for index,name in enumerate(names): name_location_dictionary={"name":name,"location":locations[index],"parameter_location":mechanisms[index]} covariance_list.append(name_location_dictionary) return covariance_list except: print("Could not retrieve the covariance dictionary") pass def get_montecarlo_dictionary(self): """Returns a list of dictionaries that has the keys name, location""" montecarlo_list=[] try: names=[x.attrib["Text"] for x in self.etree.findall(".//MonteCarloPerturbedSParams/Item/SubItem[@Index='0']")] locations=[x.attrib["Text"] for x in self.etree.findall(".//MonteCarloPerturbedSParams/Item/SubItem[@Index='1']")] for index,name in enumerate(names): name_location_dictionary={"name":name,"location":locations[index]} montecarlo_list.append(name_location_dictionary) return montecarlo_list except: print("Could not retrieve the montecarlo dictionary") pass def get_nominal_dictionary(self): "Returns a single dictionary with nominal name and location" nominal_dictionary={} try: location=map(lambda x: x.attrib["Text"], self.etree.findall(".//MeasSParams/Item/SubItem[@Index='1']"))[0] name=os.path.split(location)[-1].split(".")[0] nominal_dictionary["location"]=location nominal_dictionary["name"]=name return nominal_dictionary except: print("Could not get nominal path information") pass class MUFVNAUncertArchive(XMLBase): pass class MUFSolution(XMLBase): pass class MUFComplexModel(AsciiDataTable): """MUFComplexModel is built for the .complex files used in eps etc """ def __init__(self, file_path, **options): """Initializes the class MUFComplexModel""" defaults = {"data_delimiter": "\t", "column_names_delimiter": ",", "specific_descriptor": 'Complex', "general_descriptor": 'EPS', "extension": 'complex', "comment_begin": "!", "comment_end": "\n", "header": None, "column_names": ["Frequency", "re", "im"], "column_names_begin_token": "!", "column_names_end_token": "\n", "data": None, "row_formatter_string": None, "data_table_element_separator": None, "row_begin_token": None, "row_end_token": None, "escape_character": None, "data_begin_token": None, "data_end_token": None, "column_types": ['float' for i in range(len(["Frequency", "re", "im"]))] } self.options = {} for key, value in defaults.items(): self.options[key] = value for key, value in options.items(): self.options[key] = value if file_path is not None: self.path = file_path self.__read_and_fix__() AsciiDataTable.__init__(self, None, **self.options) if file_path is not None: self.path = file_path def __read_and_fix__(self): """Reads in the data and fixes any problems with delimiters, etc""" in_file = open(self.path, 'r') lines = [] for line in in_file: lines.append([float(x) for x in line.split("\t")]) in_file.close() self.options["data"] = lines self.complex_data = [] for row in self.options["data"]: frequency = [row[0]] complex_numbers = row[1:] # print np.array(complex_numbers[1::2]) complex_array = np.array(complex_numbers[0::2]) + 1.j * np.array(complex_numbers[1::2]) self.complex_data.append(frequency + complex_array.tolist()) def get_variation_parameter(self): try: re_data = self["re"][:] re_data_var = [re_data[i + 2] - 2.0 * re_data[i + 1] + re_data[i] for i in range(len(re_data) - 2)] self.variation_parameter = 100 * max([abs(x) for x in re_data_var]) except: raise self.variation_parameter = 0 return self.variation_parameter def get_re_std(self): return np.std(self["re"]) def get_re_mean(self): return np.mean(self["re"]) def get_re_max(self): return np.max(self["re"]) def show(self, **options): fig, ax1 = plt.subplots() ax1.plot(self["Frequency"], self["re"], 'b-') ax1.set_xlabel('Frequency (GHz)') # Make the y-axis label, ticks and tick labels match the line color. ax1.set_ylabel('Real', color='b') ax1.tick_params('y', colors='b') ax2 = ax1.twinx() ax2.plot(self["Frequency"], self["im"], 'r-') ax2.set_ylabel('Imaginary', color='r') ax2.tick_params('y', colors='r') fig.tight_layout() plt.show() #----------------------------------------------------------------------------- # Module Scripts if CLR: def run_muf_script(menu_location,timeit=True): """Opens a vnauncert or vnauncert_archive and runs it as is.""" start=datetime.datetime.utcnow() sys.path.append(SCRIPTABLE_MUF_LOCATION) clr.AddReference("VNAUncertainty") import VNAUncertainty from System import EventArgs, Object event=EventArgs() vna =VNAUncertainty.VNAUncertainty() vna.OnLoad(event) vna.myOpenMenu(menu_location) vna.OnLocationChanged(event) vna.RunCalibration(0) vna.Close() if timeit: stop=datetime.datetime.utcnow() runtime=stop-start print(("VNAUncertainty finished running at {0}".format(stop))) print(("The script took {0} seconds to run".format(runtime.seconds))) #----------------------------------------------------------------------------- # Module Runner if __name__ == '__main__': pass
Functions
def make_parameter_table(
parameter_directory)
Creates a table from all the parameters in the parameter_directory, returns an AsciiDataTable
def make_parameter_table(parameter_directory): """Creates a table from all the parameters in the parameter_directory, returns an AsciiDataTable""" file_names=os.listdir(parameter_directory) parameter_files=[] for file_name in file_names: extension = file_name.split(".")[-1] if re.search("parameter",extension,re.IGNORECASE) and extension not in ["parameterviewer"] : parameter_files.append(os.path.join(parameter_directory,file_name)) #print("{0} is {1}".format("parameter_files",parameter_files)) parameter_models=[MUFParameter(file_name) for file_name in parameter_files] column_names=["Parameter_Name","Value","Distribution_Type","Width","Standard_Uncertainty","Units"] data=[] for index,parameter in enumerate(parameter_models): print(("Parameter Number: {0}, Name:{1}".format(index,parameter.get_mechanism_name()) )) row=[os.path.split(parameter.get_mechanism_name())[-1].split(".")[0], parameter.get_value(),parameter.get_distribution_type(), parameter.get_distribution_width(),parameter.get_standard_uncertainty(), parameter.get_units()] data.append(row) data_table=AsciiDataTable(column_names=column_names,data=data) return data_table
def run_muf_script(
menu_location, timeit=True)
Opens a vnauncert or vnauncert_archive and runs it as is.
def run_muf_script(menu_location,timeit=True): """Opens a vnauncert or vnauncert_archive and runs it as is.""" start=datetime.datetime.utcnow() sys.path.append(SCRIPTABLE_MUF_LOCATION) clr.AddReference("VNAUncertainty") import VNAUncertainty from System import EventArgs, Object event=EventArgs() vna =VNAUncertainty.VNAUncertainty() vna.OnLoad(event) vna.myOpenMenu(menu_location) vna.OnLocationChanged(event) vna.RunCalibration(0) vna.Close() if timeit: stop=datetime.datetime.utcnow() runtime=stop-start print(("VNAUncertainty finished running at {0}".format(stop))) print(("The script took {0} seconds to run".format(runtime.seconds)))
Classes
class MUFComplexModel
MUFComplexModel is built for the .complex files used in eps etc
class MUFComplexModel(AsciiDataTable): """MUFComplexModel is built for the .complex files used in eps etc """ def __init__(self, file_path, **options): """Initializes the class MUFComplexModel""" defaults = {"data_delimiter": "\t", "column_names_delimiter": ",", "specific_descriptor": 'Complex', "general_descriptor": 'EPS', "extension": 'complex', "comment_begin": "!", "comment_end": "\n", "header": None, "column_names": ["Frequency", "re", "im"], "column_names_begin_token": "!", "column_names_end_token": "\n", "data": None, "row_formatter_string": None, "data_table_element_separator": None, "row_begin_token": None, "row_end_token": None, "escape_character": None, "data_begin_token": None, "data_end_token": None, "column_types": ['float' for i in range(len(["Frequency", "re", "im"]))] } self.options = {} for key, value in defaults.items(): self.options[key] = value for key, value in options.items(): self.options[key] = value if file_path is not None: self.path = file_path self.__read_and_fix__() AsciiDataTable.__init__(self, None, **self.options) if file_path is not None: self.path = file_path def __read_and_fix__(self): """Reads in the data and fixes any problems with delimiters, etc""" in_file = open(self.path, 'r') lines = [] for line in in_file: lines.append([float(x) for x in line.split("\t")]) in_file.close() self.options["data"] = lines self.complex_data = [] for row in self.options["data"]: frequency = [row[0]] complex_numbers = row[1:] # print np.array(complex_numbers[1::2]) complex_array = np.array(complex_numbers[0::2]) + 1.j * np.array(complex_numbers[1::2]) self.complex_data.append(frequency + complex_array.tolist()) def get_variation_parameter(self): try: re_data = self["re"][:] re_data_var = [re_data[i + 2] - 2.0 * re_data[i + 1] + re_data[i] for i in range(len(re_data) - 2)] self.variation_parameter = 100 * max([abs(x) for x in re_data_var]) except: raise self.variation_parameter = 0 return self.variation_parameter def get_re_std(self): return np.std(self["re"]) def get_re_mean(self): return np.mean(self["re"]) def get_re_max(self): return np.max(self["re"]) def show(self, **options): fig, ax1 = plt.subplots() ax1.plot(self["Frequency"], self["re"], 'b-') ax1.set_xlabel('Frequency (GHz)') # Make the y-axis label, ticks and tick labels match the line color. ax1.set_ylabel('Real', color='b') ax1.tick_params('y', colors='b') ax2 = ax1.twinx() ax2.plot(self["Frequency"], self["im"], 'r-') ax2.set_ylabel('Imaginary', color='r') ax2.tick_params('y', colors='r') fig.tight_layout() plt.show()
Ancestors (in MRO)
- MUFComplexModel
- Code.DataHandlers.GeneralModels.AsciiDataTable
- __builtin__.object
Instance variables
var options
Methods
def __init__(
self, file_path, **options)
Initializes the class MUFComplexModel
def __init__(self, file_path, **options): """Initializes the class MUFComplexModel""" defaults = {"data_delimiter": "\t", "column_names_delimiter": ",", "specific_descriptor": 'Complex', "general_descriptor": 'EPS', "extension": 'complex', "comment_begin": "!", "comment_end": "\n", "header": None, "column_names": ["Frequency", "re", "im"], "column_names_begin_token": "!", "column_names_end_token": "\n", "data": None, "row_formatter_string": None, "data_table_element_separator": None, "row_begin_token": None, "row_end_token": None, "escape_character": None, "data_begin_token": None, "data_end_token": None, "column_types": ['float' for i in range(len(["Frequency", "re", "im"]))] } self.options = {} for key, value in defaults.items(): self.options[key] = value for key, value in options.items(): self.options[key] = value if file_path is not None: self.path = file_path self.__read_and_fix__() AsciiDataTable.__init__(self, None, **self.options) if file_path is not None: self.path = file_path
def add_column(
self, column_name=None, column_type=None, column_data=None, format_string=None)
Adds a column with column_name, and column_type. If column data is supplied and it's length is the same as data(same number of rows) then it is added, else self.options['empty_character'] is added in each spot in the preceding rows
def add_column(self,column_name=None,column_type=None,column_data=None,format_string=None): """Adds a column with column_name, and column_type. If column data is supplied and it's length is the same as data(same number of rows) then it is added, else self.options['empty_character'] is added in each spot in the preceding rows""" original_column_names=self.column_names[:] try: self.column_names=original_column_names+[column_name] if self.options["column_types"]: old_column_types=self.options["column_types"][:] self.options["column_types"]=old_column_types+[column_type] if len(column_data) == len(self.data): for index,row in enumerate(self.data[:]): #print("{0} is {1}".format('self.data[index]',self.data[index])) #print("{0} is {1}".format('row',row)) new_row=row[:] new_row.append(column_data[index]) self.data[index]=new_row else: for index,row in enumerate(self.data[:]): self.data[index]=row.append(self.options['empty_value']) if column_data is not None: for item in column_data: empty_row=[self.options['empty_value'] for column in original_column_names] empty_row.append(item) self.add_row(empty_row) if self.options["row_formatter_string"] is None: pass else: if format_string is None: self.options["row_formatter_string"]=self.options["row_formatter_string"]+\ '{delimiter}'+"{"+str(len(self.column_names)-1)+"}" else: self.options["row_formatter_string"]=self.options["row_formatter_string"]+format_string #self.update_model() except: self.column_names=original_column_names print("Could not add columns") raise
def add_index(
self)
Adds a column with name index and values that are 0 referenced indices, does nothing if there is already a column with name index, always inserts it at the 0 position
def add_index(self): """Adds a column with name index and values that are 0 referenced indices, does nothing if there is already a column with name index, always inserts it at the 0 position""" if 'index' in self.column_names: print("Add Index passed") pass else: self.column_names.insert(0,'index') for index,row in enumerate(self.data): self.data[index].insert(0,index) if self.options['column_types']: self.options['column_types'].insert(0,'int') if self.options['row_formatter_string']: temp_formatter_list=self.options['row_formatter_string'].split("{delimiter}") iterated_row_formatter_list=[temp_formatter_list[i].replace(str(i),str(i+1)) for i in range(len(temp_formatter_list))] new_formatter=string_list_collapse(iterated_row_formatter_list,string_delimiter="{delimiter}") self.options['row_formatter_string']='{0}{delimiter}'+new_formatter
def add_inline_comment(
self, comment='', line_number=None, string_position=None)
Adds an inline in the specified location
def add_inline_comment(self,comment="",line_number=None,string_position=None): "Adds an inline in the specified location" try: self.inline_comments.append([comment,line_number,string_position]) except:pass
def add_row(
self, row_data)
Adds a single row given row_data which can be an ordered list/tuple or a dictionary with column names as keys
def add_row(self,row_data): """Adds a single row given row_data which can be an ordered list/tuple or a dictionary with column names as keys""" if self.data is None: self.data=[] if len(row_data) not in [len(self.column_names),len(self.column_names)]: print(" could not add the row, dimensions do not match") return if isinstance(row_data,(ListType,np.ndarray)): self.data.append(row_data) elif isinstance(row_data,DictionaryType): data_list=[row_data[column_name] for column_name in self.column_names] self.data.append(data_list)
def build_string(
self, **temp_options)
Builds a string representation of the data table based on self.options, or temp_options. Passing temp_options does not permanently change the model
def build_string(self,**temp_options): """Builds a string representation of the data table based on self.options, or temp_options. Passing temp_options does not permanently change the model""" # store the original options to be put back after the string is made original_options=self.options for key,value in temp_options.items(): self.options[key]=value section_end=0 next_section_begin=0 if self.options['data_table_element_separator'] is None: inner_element_spacing=0 else: # if header does not end in "\n" and inner_element_spacing=self.options['data_table_element_separator'].count('\n') string_out="" between_section="" if self.options['data_table_element_separator'] is not None: between_section=self.options['data_table_element_separator'] if not self.header: self.options['header_begin_line']=self.options['header_end_line']=None pass else: self.options["header_begin_line"]=0 if self.data is None and self.column_names is None and self.footer is None: string_out=self.get_header_string() self.options["header_end_line"]=None else: string_out=self.get_header_string()+between_section #print("{0} is {1}".format("self.get_header_string()",self.get_header_string())) header_end=self.get_header_string()[-1] #print("{0} is {1}".format("header_end",header_end)) if header_end in ["\n"]: adjust_header_lines=0 else: adjust_header_lines=1 # I think this is wrong If header string ends in an "\n" fixed for now inner_element_spacing=inner_element_spacing last_header_line=self.get_header_string().count('\n')+adjust_header_lines self.options["header_end_line"]=last_header_line next_section_begin=last_header_line+inner_element_spacing-adjust_header_lines if not self.column_names: self.options['column_names_begin_line']=self.options['column_names_end_line']=None pass else: self.options["column_names_begin_line"]=next_section_begin if self.data is None and self.footer is None: self.options["column_names_end_line"]=None string_out=string_out+self.get_column_names_string() else: string_out=string_out+self.get_column_names_string()+between_section column_names_end=self.get_column_names_string()[-1] #print("{0} is {1}".format("column_names_end",column_names_end)) if column_names_end in ["\n"]: adjust_column_names_lines=0 else: adjust_column_names_lines=1 last_column_names_line=self.get_column_names_string().count('\n')+\ self.options["column_names_begin_line"]+adjust_column_names_lines self.options["column_names_end_line"]=last_column_names_line next_section_begin=last_column_names_line+inner_element_spacing-adjust_column_names_lines if not self.data: self.options['data_begin_line']=self.options['data_end_line']=None pass else: self.options["data_begin_line"]=next_section_begin if self.footer is None: self.options["data_end_line"]=None string_out=string_out+self.get_data_string() else: string_out=string_out+self.get_data_string()+between_section data_end=self.get_data_string()[-1] #print("{0} is {1}".format("column_names_end",column_names_end)) if data_end in ["\n"]: adjust_data_lines=0 else: adjust_data_lines=1 last_data_line=self.get_data_string().count("\n")+\ self.options["data_begin_line"]+adjust_data_lines self.options["data_end_line"]=last_data_line next_section_begin=last_data_line+inner_element_spacing-adjust_data_lines if not self.footer: self.options['footer_begin_line']=self.options['footer_end_line']=None pass else: self.options["footer_begin_line"]=next_section_begin string_out=string_out+self.get_footer_string() self.options['footer_end_line']=None # set the options back after the string has been made if self.inline_comments is None: pass else: lines=string_out.splitlines() for comment in self.inline_comments: lines=insert_inline_comment(lines,comment=comment[0],line_number=comment[1], string_position=comment[2], begin_token=self.options['inline_comment_begin'], end_token=self.options['inline_comment_end']) string_out=string_list_collapse(lines,string_delimiter='\n') self.options=original_options return string_out
def change_unit_prefix(
self, column_selector=None, old_prefix=None, new_prefix=None, unit='Hz')
Changes the prefix of the units of the column specified by column_selector (column name or index) example usage is self.change_unit_prefix(column_selector='Frequency',old_prefix=None,new_prefix='G',unit='Hz') to change a column from Hz to GHz. It updates the data values, column_descriptions, and column_units if they exist, see http://www.nist.gov/pml/wmd/metric/prefixes.cfm for possible prefixes
def change_unit_prefix(self,column_selector=None,old_prefix=None,new_prefix=None,unit='Hz'): """Changes the prefix of the units of the column specified by column_selector (column name or index) example usage is self.change_unit_prefix(column_selector='Frequency',old_prefix=None,new_prefix='G',unit='Hz') to change a column from Hz to GHz. It updates the data values, column_descriptions, and column_units if they exist, see http://www.nist.gov/pml/wmd/metric/prefixes.cfm for possible prefixes""" multipliers={"yotta":10.**24,"Y":10.**24,"zetta":10.**21,"Z":10.**21,"exa":10.**18,"E":10.**18,"peta":10.**15, "P":10.**15,"tera":10.**12,"T":10.**12,"giga":10.**9,"G":10.**9,"mega":10.**6,"M":10.**6, "kilo":10.**3,"k":10.**3,"hecto":10.**2,"h":10.**2,"deka":10.,"da":10.,None:1.,"":1., "deci":10.**-1,"d":10.**-1,"centi":10.**-2,"c":10.**-2,"milli":10.**-3,"m":10.**-3, "micro":10.**-6,"mu":10.**-6,"\u00B5":10.**-6,"nano":10.**-9, "n":10.**-9,"pico":10.**-12,"p":10.**-12,"femto":10.**-15, "f":10.**-15,"atto":10.**-18,"a":10.**-18,"zepto":10.**-21,"z":10.**-21, "yocto":10.**-24,"y":10.**-24} # change column name into column index try: if old_prefix is None: old_prefix="" if new_prefix is None: new_prefix="" old_unit=old_prefix+unit new_unit=new_prefix+unit if column_selector in self.column_names: column_selector=self.column_names.index(column_selector) for index,row in enumerate(self.data): if isinstance(self.data[index][column_selector],FloatType): #print "{0:e}".format(multipliers[old_prefix]/multipliers[new_prefix]) self.data[index][column_selector]=\ (multipliers[old_prefix]/multipliers[new_prefix])*self.data[index][column_selector] elif isinstance(self.data[index][column_selector],(StringType,IntType)): self.data[index][column_selector]=\ str((multipliers[old_prefix]/multipliers[new_prefix])*float(self.data[index][column_selector])) else: print(type(self.data[index][column_selector])) raise if self.options["column_descriptions"] is not None: old=self.options["column_descriptions"][column_selector] self.options["column_descriptions"][column_selector]=old.replace(old_unit,new_unit) if self.options["column_units"] is not None: old=self.options["column_units"][column_selector] self.options["column_units"][column_selector]=old.replace(old_unit,new_unit) if re.search(old_unit,self.column_names[column_selector]): old=self.column_names[column_selector] self.column_names[column_selector]=old.replace(old_unit,new_unit) except: print(("Could not change the unit prefix of column {0}".format(column_selector))) raise
def copy(
self)
Creates a shallow copy of the data table
def copy(self): "Creates a shallow copy of the data table" return copy.copy(self)
def find_line(
self, begin_token)
Finds the first line that has begin token in it
def find_line(self,begin_token): """Finds the first line that has begin token in it""" for index,line in enumerate(self.lines): if re.search(begin_token,line,re.IGNORECASE): return index
def get_column(
self, column_name=None, column_index=None)
Returns a column as a list given a column name or column index
def get_column(self,column_name=None,column_index=None): """Returns a column as a list given a column name or column index""" if column_name is None: if column_index is None: return else: column_selector=column_index else: column_selector=self.column_names.index(column_name) out_list=[self.data[i][column_selector] for i in range(len(self.data))] return out_list
def get_column_names_string(
self)
Returns the column names as a string using options
def get_column_names_string(self): "Returns the column names as a string using options" string_out="" # This writes the column_names column_name_begin="" column_name_end="" if self.options["column_names_begin_token"] is None: column_name_begin="" else: column_name_begin=self.options["column_names_begin_token"] if self.options["column_names_end_token"] is None: column_name_end="" else: column_name_end=self.options["column_names_end_token"] if self.column_names is None: string_out="" else: if isinstance(self.column_names, StringType): string_out=self.column_names elif isinstance(self.column_names, ListType): string_out=list_to_string(self.column_names, data_delimiter=self.options["column_names_delimiter"],end="") #print("{0} is {1}".format('string_out',string_out)) else: string_out=ensure_string(self.column_names) #print column_name_begin,string_out,column_name_end return column_name_begin+string_out+column_name_end
def get_data_dictionary_list(
self, use_row_formatter_string=True)
Returns a python list with a row dictionary of form {column_name:data_column}
def get_data_dictionary_list(self,use_row_formatter_string=True): """Returns a python list with a row dictionary of form {column_name:data_column}""" try: if self.options["row_formatter_string"] is None: use_row_formatter_string=False if use_row_formatter_string: list_formatter=[item.replace("{"+str(index),"{0") for index,item in enumerate(self.options["row_formatter_string"].split("{delimiter}"))] else: list_formatter=["{0}" for i in self.column_names] #print self.column_names #print self.data #print list_formatter #print len(self.column_names)==len(self.data[0]) #print len(list_formatter)==len(self.data[0]) #print type(self.data[0]) out_list=[{self.column_names[i]:list_formatter[i].format(value) for i,value in enumerate(line)} for line in self.data] return out_list except: print("Could not form a data_dictionary_list, check that row_formatter_string is properly defined") #print(out_list) raise
def get_data_string(
self)
Returns the data as a string
def get_data_string(self): "Returns the data as a string" #Todo:refactor to cut out unused lines string_out="" if self.data is None: string_out= "" else: if isinstance(self.data, StringType): if self.options['data_begin_token'] is None: if self.options['data_end_token'] is None: string_out=self.data else: if re.search(self.options['data_end_token'],self.data): string_out=self.data else: string_out=self.data+self.options['data_end_token'] else: if self.options['data_end_token'] is None: if re.match(self.options['data_begin_token'],self.data): string_out=self.data else: string_out=self.options['data_begin_token']+self.data elif isinstance(self.data,(ListType,np.ndarray)): try: #If the first row is a string, we should strip all the tokens and add them back in if isinstance(self.data[0], StringType): if self.options['data_begin_token'] is None: string_out=string_list_collapse(self.data) else: if re.match(self.options['data_begin_token'],self.data[0]): if self.options['data_end_token'] is None: string_out=string_list_collapse(self.data) else: if re.search(self.options['data_end_token'],self.data[-1]): string_out=string_list_collapse(self.data) else: string_out=string_list_collapse(self.data)+self.options['data_end_token'] else: if self.options['data_end_token'] is None: string_out=self.options['data_begin_token']+string_list_collapse(self.data) else: if re.search(self.options['data_end_token'],self.data[-1]): string_out=self.options['data_begin_token']+string_list_collapse(self.data) else: string_out=self.options['data_begin_token']+\ string_list_collapse(self.data)+\ self.options['data_end_token'] elif isinstance(self.data[0],(ListType,np.ndarray)): prefix="" if self.options['data_begin_token'] is None: if self.options['data_end_token'] is None: string_out=list_list_to_string(self.data,data_delimiter=self.options['data_delimiter'], row_formatter_string=self.options['row_formatter_string'], line_begin=self.options["row_begin_token"], line_end=self.options["row_end_token"]) else: string_out=list_list_to_string(self.data,data_delimiter=self.options['data_delimiter'], row_formatter_string=self.options['row_formatter_string'], line_begin=self.options["row_begin_token"], line_end=self.options["row_end_token"])+\ self.options['data_end_token'] else: if self.options['data_end_token'] is None: string_out=self.options['data_begin_token']+\ list_list_to_string(self.data, data_delimiter=self.options['data_delimiter'], row_formatter_string=self.options['row_formatter_string'], line_begin=self.options["row_begin_token"], line_end=self.options["row_end_token"]) else: string_out=self.options['data_begin_token']+\ list_list_to_string(self.data, data_delimiter=self.options['data_delimiter'], row_formatter_string=\ self.options['row_formatter_string'], line_begin=self.options["row_begin_token"], line_end=self.options["row_end_token"])+\ self.options['data_end_token'] else: string_out=list_to_string(self.data, data_delimiter=self.options['data_delimiter'], row_formatter_string=self.options['row_formatter_string'], begin=self.options["row_begin_token"], end=self.options["row_end_token"]) except IndexError: pass else: string_out=ensure_string(self.data) if string_out[-1] not in ["\n"] and self.footer is not None and self.options["data_table_element_separator"] is None: string_out=string_out+"\n" return string_out
Returns the footer using options in self.options. If block comment is specified, and the footer is a list it will block comment out the footer. If comment_begin and comment_end are specified it will use those to represent each line of the footer. If footer_begin_token and/or footer_end_token are specified it will wrap the footer in those.
def get_header_string(
self)
Returns the header using options in self.options. If block comment is specified, and the header is a list it will block comment out the header. If comment_begin and comment_end are specified it will use those to represent each line of the header. If header_begin_token and/or header_end_token are specified it will wrap the header in those.
def get_header_string(self): """Returns the header using options in self.options. If block comment is specified, and the header is a list it will block comment out the header. If comment_begin and comment_end are specified it will use those to represent each line of the header. If header_begin_token and/or header_end_token are specified it will wrap the header in those. """ string_out="" header_begin="" header_end="" if self.options["header_begin_token"] is None: header_begin="" else: header_begin=self.options["header_begin_token"] if self.options["header_end_token"] is None: header_end="" else: header_end=self.options["header_end_token"] # This writes the header if self.header is None: string_out= "" elif self.options["header_line_types"] is not None: for index,line in enumerate(self.options["header_line_types"]): if index == len(self.options["header_line_types"])-1: end='' else: end='\n' if line in ['header','header_line','normal']: string_out=string_out+self.header[index]+end elif line in ['line_comment','comment']: #print("{0} is {1}".format("index",index)) string_out=string_out+line_comment_string(self.header[index], comment_begin=self.options["comment_begin"], comment_end=self.options["comment_end"])+end elif line in ['block_comment','block']: if index-1<0: block_comment_begin=index block_comment_end=index+2 continue elif self.options["header_line_types"][index-1] not in ['block_comment','block']: block_comment_begin=index block_comment_end=index+2 continue else: if index+1>len(self.options["header_line_types"])-1: string_out=string_out+line_list_comment_string(self.header[block_comment_begin:], comment_begin=self.options['block_comment_begin'], comment_end=self.options['block_comment_end'], block=True)+end elif self.options["header_line_types"][index+1] in ['block_comment','block']: block_comment_end+=1 else: string_out=string_out+\ line_list_comment_string(self.header[block_comment_begin:block_comment_end], comment_begin=self.options['block_comment_begin'], comment_end=self.options['block_comment_end'], block=True)+end else: string_out=string_out+line elif self.options['treat_header_as_comment'] in [None,True] and self.options["header_line_types"] in [None]: # Just happens if the user has set self.header manually if isinstance(self.header, StringType): string_out=line_comment_string(self.header, comment_begin=self.options["comment_begin"], comment_end=self.options["comment_end"]) #string_out=re.sub('\n','',string_out,count=1) elif isinstance(self.header, ListType): if self.options['block_comment_begin'] is None: if self.options['comment_begin'] is None: string_out=string_list_collapse(self.header) else: string_out=line_list_comment_string(self.header,comment_begin=self.options['comment_begin'], comment_end=self.options['comment_end']) lines_out=string_out.splitlines() # if re.search('\n',self.options['comment_end']): # string_out=re.sub('\n','',string_out,count=1) #self.options["header_line_types"]=["line_comment" for line in self.header] else: string_out=line_list_comment_string(self.header,comment_begin=self.options['block_comment_begin'], comment_end=self.options['block_comment_end'],block=True) #self.options["header_line_types"]=["block_comment" for line in self.header] else: string_out=ensure_string(self.header,list_delimiter="\n",end_if_list="") return header_begin+string_out+header_end
def get_options(
self)
Prints the option list
def get_options(self): "Prints the option list" for key,value in self.options.items(): print(("{0} = {1}".format(key,value)))
def get_options_by_element(
self, element_name)
returns a dictionary of all the options that have to do with element. Element must be header,column_names,data, or footer
def get_options_by_element(self,element_name): """ returns a dictionary of all the options that have to do with element. Element must be header,column_names,data, or footer""" keys_regarding_element=[x for x in list(self.options.keys()) if re.search(element_name,str(x),re.IGNORECASE)] out_dictionary={key:self.options[key] for key in keys_regarding_element} #print out_dictionary return out_dictionary
def get_re_max(
self)
def get_re_max(self): return np.max(self["re"])
def get_re_mean(
self)
def get_re_mean(self): return np.mean(self["re"])
def get_re_std(
self)
def get_re_std(self): return np.std(self["re"])
def get_row(
self, row_index=None)
Returns the row as a list specified by row_index
def get_row(self,row_index=None): """Returns the row as a list specified by row_index""" if row_index is None: return else: return self.data[row_index]
def get_unique_column_values(
self, column_name=None, column_index=None)
Returns the unique values in a column as a list given a column name or column index
def get_unique_column_values(self,column_name=None,column_index=None): """Returns the unique values in a column as a list given a column name or column index""" if column_name is None: if column_index is None: return else: column_selector=column_index else: column_selector=self.column_names.index(column_name) out_list=list(set([self.data[i][column_selector] for i in range(len(self.data))])) return out_list
def get_variation_parameter(
self)
def get_variation_parameter(self): try: re_data = self["re"][:] re_data_var = [re_data[i + 2] - 2.0 * re_data[i + 1] + re_data[i] for i in range(len(re_data) - 2)] self.variation_parameter = 100 * max([abs(x) for x in re_data_var]) except: raise self.variation_parameter = 0 return self.variation_parameter
def is_valid(
self)
Returns True if ascii table conforms to its specification given by its own options
def is_valid(self): """Returns True if ascii table conforms to its specification given by its own options""" options={} for key,value in self.options.items(): options[key]=value # print("self.options[{0}] is {1} ".format(key,value)) for element in self.elements: if self.__dict__[element] is None: options[element]=None else: options[element]=[] options["validate"]=True newtable=AsciiDataTable(None,**options) lines=self.build_string().splitlines() for index,line in enumerate(lines): lines[index]=line+"\n" newtable.lines=lines newtable.__parse__() # print newtable.data # print newtable.column_names # print newtable #print_comparison(newtable.footer,None) newtable.update_model() # The new table rows are not being coerced into the right format #print newtable #newtable.update_model() #print newtable.options #print self.options #print newtable.data # print newtable.options==self.options # for option_key,option_value in newtable.options.iteritems(): # print("New Table Option {0} is {1} ".format(option_key,option_value)) # print("self.options[{0}] is {1} ".format(option_key,self.options[option_key])) # print_comparison(option_value,self.options[option_key]) # #print self return self==newtable
def lines_defined(
self)
If begin_line and end_line for all elements that are None are defined returns True
def lines_defined(self): """If begin_line and end_line for all elements that are None are defined returns True""" truth_table=[] last_element="" output=False for index,element in enumerate(self.elements): if element not in ['inline_comments','metadata'] and self.__dict__[element] is not None: try: last_element=element if not None in [self.options['%s_begin_line'%element],self.options['%s_end_line'%element]]: truth_table.append(True) else: truth_table.append(False) except: return False #print truth_table # The last_line of the last element is fine to be none if truth_table[-1] is False: if self.options['%s_begin_line'%last_element] is not None: truth_table[-1]=True if False in truth_table: output=False else: output=True #print output return output
Moves the DataTable's footer to the header and updates the model
def remove_column(
self, column_name=None, column_index=None)
Removes the column specified by column_name or column_index and updates the model. The column is removed from column_names, data and if present column_types, column_descriptions and row formatter
def remove_column(self,column_name=None,column_index=None): """Removes the column specified by column_name or column_index and updates the model. The column is removed from column_names, data and if present column_types, column_descriptions and row formatter""" if self.column_names: number_of_columns=len(self.column_names[:]) elif self.data: number_of_columns=len(self.data[0]) else: raise if column_name: column_index=self.column_names.index(column_name) elif column_index: pass else: raise TypeError("To remove a column either the name or index must be specified") #print("{0} is {1}".format("column_index",column_index)) #print("{0} is {1}".format("type(column_index)",type(column_index))) self.column_names.pop(column_index) for row in self.data: row.pop(column_index) if self.options["row_formatter_string"]: format_string="{"+str(column_index)+"}"+"{delimiter}" self.options["row_formatter_string"]=\ self.options["row_formatter_string"].replace(format_string,"") for index in range(column_index+1,number_of_columns): old_format_string="{"+str(index) new_format_string="{"+str(index-1) self.options["row_formatter_string"]=\ self.options["row_formatter_string"].replace(old_format_string,new_format_string)
def remove_row(
self, row_index)
Removes the row specified by row_index and updates the model. Note index is relative to the data attribute so to remove the first row use row_index=0 and the last data row is row_index=-1
def remove_row(self,row_index): """Removes the row specified by row_index and updates the model. Note index is relative to the data attribute so to remove the first row use row_index=0 and the last data row is row_index=-1""" self.data.pop(row_index) self.update_model()
def save(
self, path=None, **temp_options)
" Saves the file, to save in another ascii format specify elements in temp_options, the options specified do not permanently change the object's options. If path is supplied it saves the file to that path otherwise uses the object's attribute path to define the saving location
def save(self,path=None,**temp_options): """" Saves the file, to save in another ascii format specify elements in temp_options, the options specified do not permanently change the object's options. If path is supplied it saves the file to that path otherwise uses the object's attribute path to define the saving location """ original_options=self.options for key,value in temp_options.items(): self.options[key]=value out_string=self.build_string(**temp_options) if path is None: path=self.path file_out=open(path,'w') file_out.write(out_string) file_out.close() if self.options["save_schema"]: self.save_schema(change_extension(path,new_extension="schema")) self.options=original_options
def save_schema(
self, path=None, format=None)
Saves the tables options as a text file or pickled dictionary (default). If no name is supplied, autonames it and saves
def save_schema(self,path=None,format=None): """Saves the tables options as a text file or pickled dictionary (default). If no name is supplied, autonames it and saves""" if path is None: path=auto_name(self.name.replace('.'+self.options["extension"],""),'Schema',self.options["directory"],'txt') if format in [None,'python','pickle']: pickle.dump(self.options,open(path,'wb')) elif format in ['txt','text','.txt']: file_out=open(path,'w') keys=sorted(list(self.options.keys())) for key in keys: out_key=str(key).replace("\n","\\n") out_value=str(self.options[key]).replace("\n","\\n") file_out.write("{0} : {1} \n".format(out_key,out_value)) file_out.close()
def show(
self, **options)
def show(self, **options): fig, ax1 = plt.subplots() ax1.plot(self["Frequency"], self["re"], 'b-') ax1.set_xlabel('Frequency (GHz)') # Make the y-axis label, ticks and tick labels match the line color. ax1.set_ylabel('Real', color='b') ax1.tick_params('y', colors='b') ax2 = ax1.twinx() ax2.plot(self["Frequency"], self["im"], 'r-') ax2.set_ylabel('Imaginary', color='r') ax2.tick_params('y', colors='r') fig.tight_layout() plt.show()
def structure_metadata(
self)
Function that should be overridden by whatever model the datatable has, it only responds with a self.metadata attribute in its base state derived from self.options["metadata]
def structure_metadata(self): """Function that should be overridden by whatever model the datatable has, it only responds with a self.metadata attribute in its base state derived from self.options["metadata]""" self.metadata=self.options["metadata"]
def update_column_names(
self)
Update column names adds the value x# for any column that exists in self.data that is not named
def update_column_names(self): """Update column names adds the value x# for any column that exists in self.data that is not named""" if self.data is None: return elif isinstance(self.column_names, StringType): self.column_names=split_row(self.column_names,self.options["column_names_delimiter"]) elif self.column_names is None: column_names=[] for index,column in enumerate(self.data[0]): column_names.append("x"+str(index)) self.column_names=column_names return elif len(self.column_names)==len(self.data[0]): return elif len(self.column_names) < len(self.data[0]): for index in range(len(self.column_names),len(self.data[0])): self.column_names.append("x"+str(index)) return
def update_import_options(
self, import_table, verbose=False)
Updates the options in the import table
def update_import_options(self,import_table,verbose=False): """Updates the options in the import table""" # discovered slight bug 2017-01-18 the variable index is not the right one to have here # it should be i from 0 to len(import_table) defined_element_index=0 for index,element in enumerate(['header','column_names','data','footer']): if self.__dict__[element] is not None: if verbose: print(("The {0} variable is {1}".format('index',index))) print(("The {0} variable is {1}".format('element',element))) print(("The {0} variable is {1}".format('import_table',import_table))) [self.options['%s_begin_line'%element], self.options['%s_end_line'%element], self.options['%s_begin_token'%element], self.options['%s_end_token'%element]]=import_table[defined_element_index][:] defined_element_index+=1
def update_index(
self)
Updates the index column if it exits, otherwise exits quietly
def update_index(self): """ Updates the index column if it exits, otherwise exits quietly """ if 'index' not in self.column_names: return else: try: #This should be 0 but just in case index_column_number=self.column_names.index('index') for i in range(len(self.data)): self.data[i][index_column_number]=i except: pass
def update_model(
self)
Updates the model after a change has been made. If you add anything to the attributes of the model, or change this updates the values. If the model has an index column it will make sure the numbers are correct. In addition, it will update the options dictionary to reflect added rows, changes in deliminators etc.
def update_model(self): """Updates the model after a change has been made. If you add anything to the attributes of the model, or change this updates the values. If the model has an index column it will make sure the numbers are correct. In addition, it will update the options dictionary to reflect added rows, changes in deliminators etc. """ if self.column_names is not None and 'index' in self.column_names: self.update_index() #make sure there are no "\n" characters in the element lists (if so replace them with "") for data this is # done on import list_types=["header","column_names","footer"] for element in list_types: if self.__dict__[element] is not None: for index,item in enumerate(self.__dict__[element]): if isinstance(self.__dict__[element][index], StringType): self.__dict__[element][index]=item.replace("\n","") self.update_column_names() if self.data is not None: self.data=convert_all_rows(self.data,self.options["column_types"]) self.string=self.build_string() self.lines=self.string.splitlines()
class MUFMeasurement
class MUFMeasurement(XMLBase): def get_name_parameter_dictionary(self): """Returns a dictionary of 'name':'parameter_name' pairs to correlate covariance files with their mechanism names""" out_dictionary={} try: names=[x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='0']")] mechanisms=[x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='2']")] for index,name in enumerate(names): split_parameter_name=os.path.split(mechanisms[index])[-1] parameter_name=split_parameter_name.split(".")[0] out_dictionary[name]=parameter_name return out_dictionary except: print("Could not retrieve the name - parameter dictionary") pass def get_covariance_dictionary(self): """Returns a list of dictionaries that has the keys name, location, and parameter_location""" covariance_list=[] try: names=[x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='0']")] locations=[x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='1']")] mechanisms = [x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='2']")] for index,name in enumerate(names): name_location_dictionary={"name":name,"location":locations[index],"parameter_location":mechanisms[index]} covariance_list.append(name_location_dictionary) return covariance_list except: print("Could not retrieve the covariance dictionary") pass def get_montecarlo_dictionary(self): """Returns a list of dictionaries that has the keys name, location""" montecarlo_list=[] try: names=[x.attrib["Text"] for x in self.etree.findall(".//MonteCarloPerturbedSParams/Item/SubItem[@Index='0']")] locations=[x.attrib["Text"] for x in self.etree.findall(".//MonteCarloPerturbedSParams/Item/SubItem[@Index='1']")] for index,name in enumerate(names): name_location_dictionary={"name":name,"location":locations[index]} montecarlo_list.append(name_location_dictionary) return montecarlo_list except: print("Could not retrieve the montecarlo dictionary") pass def get_nominal_dictionary(self): "Returns a single dictionary with nominal name and location" nominal_dictionary={} try: location=map(lambda x: x.attrib["Text"], self.etree.findall(".//MeasSParams/Item/SubItem[@Index='1']"))[0] name=os.path.split(location)[-1].split(".")[0] nominal_dictionary["location"]=location nominal_dictionary["name"]=name return nominal_dictionary except: print("Could not get nominal path information") pass
Ancestors (in MRO)
- MUFMeasurement
- Code.DataHandlers.XMLModels.XMLBase
Methods
def __init__(
self, file_path=None, **options)
Initializes the XML Base Class
def __init__(self,file_path=None,**options): "Initializes the XML Base Class " # This is a general pattern for adding a lot of options # The next more advanced thing to do is retrieve defaults from a settings file defaults={"root":"root", "style_sheet":os.path.join(XSLT_REPOSITORY,'DEFAULT_STYLE.xsl').replace('\\','/'), "specific_descriptor":'XML', "general_descriptor":'Document', "directory":None, "extension":'xml', "content":None } self.options={} for key,value in defaults.items(): self.options[key]=value for key,value in options.items(): self.options[key]=value # Define Method Aliases if they are available if METHOD_ALIASES: for command in alias(self): exec(command) #if the file path is not supplied create a new xml sheet if file_path is None: if self.options["content"]: self.document = xml.dom.minidom.parseString(self.options["content"]) self.options["content"]=None else: impl=getDOMImplementation() self.document=impl.createDocument(None,self.options['root'],None) # Should be a relative path for if self.options["style_sheet"] is not None: new_node=self.document.createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="{0}"'.format(self.options['style_sheet'])) self.document.insertBefore(new_node,self.document.documentElement) if DEFAULT_FILE_NAME is None: self.path=auto_name(self.options["specific_descriptor"], self.options["general_descriptor"], self.options["directory"], self.options["extension"]) else: # Just a backup plan if the python path is messed up self.path=DEFAULT_FILE_NAME else: try: try: file_in = open(file_path, 'r', encoding="utf-8") except: file_in = open(file_path, 'r') self.document = xml.dom.minidom.parse(file_in) file_in.close() self.path = file_path except: file_in = open(file_path, 'r', encoding="utf-8") content = str(file_in.read()) # print("File Content is {0}".format(content)) self.etree = etree.fromstring(content) self.document = xml.dom.minidom.parseString(etree.tostring(self.etree, encoding="unicode")) self.etree=etree.fromstring(self.document.toxml())
def get_covariance_dictionary(
self)
Returns a list of dictionaries that has the keys name, location, and parameter_location
def get_covariance_dictionary(self): """Returns a list of dictionaries that has the keys name, location, and parameter_location""" covariance_list=[] try: names=[x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='0']")] locations=[x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='1']")] mechanisms = [x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='2']")] for index,name in enumerate(names): name_location_dictionary={"name":name,"location":locations[index],"parameter_location":mechanisms[index]} covariance_list.append(name_location_dictionary) return covariance_list except: print("Could not retrieve the covariance dictionary") pass
def get_montecarlo_dictionary(
self)
Returns a list of dictionaries that has the keys name, location
def get_montecarlo_dictionary(self): """Returns a list of dictionaries that has the keys name, location""" montecarlo_list=[] try: names=[x.attrib["Text"] for x in self.etree.findall(".//MonteCarloPerturbedSParams/Item/SubItem[@Index='0']")] locations=[x.attrib["Text"] for x in self.etree.findall(".//MonteCarloPerturbedSParams/Item/SubItem[@Index='1']")] for index,name in enumerate(names): name_location_dictionary={"name":name,"location":locations[index]} montecarlo_list.append(name_location_dictionary) return montecarlo_list except: print("Could not retrieve the montecarlo dictionary") pass
def get_name_parameter_dictionary(
self)
Returns a dictionary of 'name':'parameter_name' pairs to correlate covariance files with their mechanism names
def get_name_parameter_dictionary(self): """Returns a dictionary of 'name':'parameter_name' pairs to correlate covariance files with their mechanism names""" out_dictionary={} try: names=[x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='0']")] mechanisms=[x.attrib["Text"] for x in self.etree.findall(".//PerturbedSParams/Item/SubItem[@Index='2']")] for index,name in enumerate(names): split_parameter_name=os.path.split(mechanisms[index])[-1] parameter_name=split_parameter_name.split(".")[0] out_dictionary[name]=parameter_name return out_dictionary except: print("Could not retrieve the name - parameter dictionary") pass
def get_nominal_dictionary(
self)
Returns a single dictionary with nominal name and location
def get_nominal_dictionary(self): "Returns a single dictionary with nominal name and location" nominal_dictionary={} try: location=map(lambda x: x.attrib["Text"], self.etree.findall(".//MeasSParams/Item/SubItem[@Index='1']"))[0] name=os.path.split(location)[-1].split(".")[0] nominal_dictionary["location"]=location nominal_dictionary["name"]=name return nominal_dictionary except: print("Could not get nominal path information") pass
def save(
self, path=None)
" Saves as an XML file
def save(self,path=None): """" Saves as an XML file""" if path is None: path=self.path file_out=open(path,'w') file_out.write(str(self)) file_out.close()
def save_HTML(
self, file_path=None, XSLT=None)
Saves a HTML transformation of the XML document using XLST at file_path. Defaults to an XLST in self.options["XSLT"] and file_path=self.path.replace('.xml','.html')
def save_HTML(self,file_path=None,XSLT=None): """Saves a HTML transformation of the XML document using XLST at file_path. Defaults to an XLST in self.options["XSLT"] and file_path=self.path.replace('.xml','.html')""" if XSLT is None: # For some reason an absolute path tends to break here, maybe a spaces in file names problem XSLT=self.options['style_sheet'] HTML=self.to_HTML(XSLT=XSLT) #print type(HTML) if file_path is None: file_path=self.path.replace('.xml','.html') out_file=open(file_path,'w') out_file.write(HTML) out_file.close()
def show(
self, mode='Window')
Displays a XML Document either as formatted text in the command line or in a window (using wx)
def show(self,mode='Window'): """ Displays a XML Document either as formatted text in the command line or in a window (using wx)""" def tag_to_tagName(tag): tagName=tag.replace('<','') tagName=tagName.replace('/','') tagName=tagName.replace('>','') return tagName if mode in ['text','txt','cmd line','cmd']: for node in self.document.getElementsByTagName('Entry'): print('Entry Index: %s \tDate: %s'%(node.getAttribute('Index'), node.getAttribute('Date'))) print(node.firstChild.nodeValue) elif re.search('xml',mode,re.IGNORECASE): for node in self.document.getElementsByTagName('Entry'): print(node.toprettyxml()) elif re.search('Window|wx',mode,re.IGNORECASE): try: import wx import wx.html2 except: print('Cannot locate wx, please add to sys.path') app = wx.App(False) frame=wx.Frame(None) html_window=wx.html2.WebView.New(frame) html_window.SetPage(str(self.to_HTML()),"") frame.Show() app.MainLoop()
def to_HTML(
self, XSLT=None)
Returns HTML string by applying a XSL to the XML document
def to_HTML(self,XSLT=None): """ Returns HTML string by applying a XSL to the XML document""" if XSLT is None: # For some reason an absolute path tends to break here, maybe a spaces in file names problem XSLT=self.options['style_sheet'] XSL_data=etree.parse(XSLT) XSL_transform=etree.XSLT(XSL_data) HTML=XSL_transform(etree.XML(self.document.toxml())) return str(HTML)
def update_document(
self)
Updates the attribute document from the self.etree.
def update_document(self): """Updates the attribute document from the self.etree. """ self.document=xml.dom.minidom.parseString(etree.tostring(self.etree))
def update_etree(
self)
Updates the attribute etree. Should be called anytime the xml content is changed
def update_etree(self): "Updates the attribute etree. Should be called anytime the xml content is changed" self.etree = etree.fromstring(self.document.toxml())
class MUFModel
class MUFModel(XMLBase): pass
Ancestors (in MRO)
- MUFModel
- Code.DataHandlers.XMLModels.XMLBase
Methods
def __init__(
self, file_path=None, **options)
Initializes the XML Base Class
def __init__(self,file_path=None,**options): "Initializes the XML Base Class " # This is a general pattern for adding a lot of options # The next more advanced thing to do is retrieve defaults from a settings file defaults={"root":"root", "style_sheet":os.path.join(XSLT_REPOSITORY,'DEFAULT_STYLE.xsl').replace('\\','/'), "specific_descriptor":'XML', "general_descriptor":'Document', "directory":None, "extension":'xml', "content":None } self.options={} for key,value in defaults.items(): self.options[key]=value for key,value in options.items(): self.options[key]=value # Define Method Aliases if they are available if METHOD_ALIASES: for command in alias(self): exec(command) #if the file path is not supplied create a new xml sheet if file_path is None: if self.options["content"]: self.document = xml.dom.minidom.parseString(self.options["content"]) self.options["content"]=None else: impl=getDOMImplementation() self.document=impl.createDocument(None,self.options['root'],None) # Should be a relative path for if self.options["style_sheet"] is not None: new_node=self.document.createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="{0}"'.format(self.options['style_sheet'])) self.document.insertBefore(new_node,self.document.documentElement) if DEFAULT_FILE_NAME is None: self.path=auto_name(self.options["specific_descriptor"], self.options["general_descriptor"], self.options["directory"], self.options["extension"]) else: # Just a backup plan if the python path is messed up self.path=DEFAULT_FILE_NAME else: try: try: file_in = open(file_path, 'r', encoding="utf-8") except: file_in = open(file_path, 'r') self.document = xml.dom.minidom.parse(file_in) file_in.close() self.path = file_path except: file_in = open(file_path, 'r', encoding="utf-8") content = str(file_in.read()) # print("File Content is {0}".format(content)) self.etree = etree.fromstring(content) self.document = xml.dom.minidom.parseString(etree.tostring(self.etree, encoding="unicode")) self.etree=etree.fromstring(self.document.toxml())
def save(
self, path=None)
" Saves as an XML file
def save(self,path=None): """" Saves as an XML file""" if path is None: path=self.path file_out=open(path,'w') file_out.write(str(self)) file_out.close()
def save_HTML(
self, file_path=None, XSLT=None)
Saves a HTML transformation of the XML document using XLST at file_path. Defaults to an XLST in self.options["XSLT"] and file_path=self.path.replace('.xml','.html')
def save_HTML(self,file_path=None,XSLT=None): """Saves a HTML transformation of the XML document using XLST at file_path. Defaults to an XLST in self.options["XSLT"] and file_path=self.path.replace('.xml','.html')""" if XSLT is None: # For some reason an absolute path tends to break here, maybe a spaces in file names problem XSLT=self.options['style_sheet'] HTML=self.to_HTML(XSLT=XSLT) #print type(HTML) if file_path is None: file_path=self.path.replace('.xml','.html') out_file=open(file_path,'w') out_file.write(HTML) out_file.close()
def show(
self, mode='Window')
Displays a XML Document either as formatted text in the command line or in a window (using wx)
def show(self,mode='Window'): """ Displays a XML Document either as formatted text in the command line or in a window (using wx)""" def tag_to_tagName(tag): tagName=tag.replace('<','') tagName=tagName.replace('/','') tagName=tagName.replace('>','') return tagName if mode in ['text','txt','cmd line','cmd']: for node in self.document.getElementsByTagName('Entry'): print('Entry Index: %s \tDate: %s'%(node.getAttribute('Index'), node.getAttribute('Date'))) print(node.firstChild.nodeValue) elif re.search('xml',mode,re.IGNORECASE): for node in self.document.getElementsByTagName('Entry'): print(node.toprettyxml()) elif re.search('Window|wx',mode,re.IGNORECASE): try: import wx import wx.html2 except: print('Cannot locate wx, please add to sys.path') app = wx.App(False) frame=wx.Frame(None) html_window=wx.html2.WebView.New(frame) html_window.SetPage(str(self.to_HTML()),"") frame.Show() app.MainLoop()
def to_HTML(
self, XSLT=None)
Returns HTML string by applying a XSL to the XML document
def to_HTML(self,XSLT=None): """ Returns HTML string by applying a XSL to the XML document""" if XSLT is None: # For some reason an absolute path tends to break here, maybe a spaces in file names problem XSLT=self.options['style_sheet'] XSL_data=etree.parse(XSLT) XSL_transform=etree.XSLT(XSL_data) HTML=XSL_transform(etree.XML(self.document.toxml())) return str(HTML)
def update_document(
self)
Updates the attribute document from the self.etree.
def update_document(self): """Updates the attribute document from the self.etree. """ self.document=xml.dom.minidom.parseString(etree.tostring(self.etree))
def update_etree(
self)
Updates the attribute etree. Should be called anytime the xml content is changed
def update_etree(self): "Updates the attribute etree. Should be called anytime the xml content is changed" self.etree = etree.fromstring(self.document.toxml())
class MUFParameter
class MUFParameter(XMLBase): def get_value(self): """Returns the value of the parameter""" mechanism_value=self.etree.findall(".//MechanismValue")[0] value=mechanism_value.attrib["ControlText"] return float(value) def set_value(self,value): """Sets the value (center of distribution)""" mechanism_value=self.etree.findall(".//MechanismValue")[0] mechanism_value.attrib["ControlText"]=str(value) self.update_document() def get_distribution_type(self): """Returns the type of Distribution. The choices are held in DistributionType/Item.""" distribution_type=self.etree.findall(".//DistributionType")[0] text=distribution_type.attrib["ControlText"] return text def set_distribution_type(self,distribution_type): """Sets the distribution type, accepts an integer or text value. See the constant MODEL_DISTRIBUTION_LIST for possibilities. Rectangular is 0, Gaussian is 3. """ if type(distribution_type) in [IntType,FloatType]: type_number=distribution_type type_name=MODEL_DISTRIBUTION_LIST[distribution_type] elif distribution_type in MODEL_DISTRIBUTION_LIST: type_number=MODEL_DISTRIBUTION_LIST.index(distribution_type) type_name=distribution_type else: print(("Could not set the type {0} please choose a" " type or index from {1}".format(distribution_type,MODEL_DISTRIBUTION_LIST))) return distribution_type_tag = self.etree.findall(".//DistributionType")[0] distribution_type_tag.attrib["ControlText"]=type_name distribution_type_tag.attrib["SelectedIndex"]=type_number self.update_document() def get_distribution_width(self): """Returns the wdith of the distribution.""" distribution_width=self.etree.findall(".//DistributionLimits")[0] text=distribution_width.attrib["ControlText"] return text def set_distribution_width(self,distribution_width): """Sets the distribution width""" distribution_width = self.etree.findall(".//DistributionLimits")[0] distribution_width.attrib["ControlText"]=str(distribution_width) self.update_document() def get_units(self): """Returns the units of the parameter""" units=self.etree.findall(".//Units")[0] text=units.attrib["ControlText"] return text def set_units(self,units): """Sets the units of the parameter can accept either an index or value. Look at MODEL_UNIT_LIST for complete set of possibilities""" if type(units) in [IntType,FloatType]: unit_number=units unit_name=MODEL_DISTRIBUTION_LIST[units] elif units in MODEL_DISTRIBUTION_LIST: unit_number=MODEL_DISTRIBUTION_LIST.index(units) unit_name=units else: print(("Could not set the units {0} please choose a" " type or index from {1}".format(units,MODEL_UNIT_LIST))) return unit_tag = self.etree.findall(".//Units")[0] unit_tag.attrib["ControlText"]=unit_name unit_tag.attrib["SelectedIndex"]=unit_number self.update_document() def get_mechanism_name(self): """Returns the mechanism name""" units=self.etree.findall(".//MechanismName")[0] text=units.attrib["ControlText"] return text def get_standard_uncertainty(self): """returns the standard uncertainty of the parameter""" uncertainty=self.etree.findall(".//StandardUncertainty")[0] text = uncertainty.attrib["ControlText"] number=float(text.split(":")[-1]) return number
Ancestors (in MRO)
- MUFParameter
- Code.DataHandlers.XMLModels.XMLBase
Methods
def __init__(
self, file_path=None, **options)
Initializes the XML Base Class
def __init__(self,file_path=None,**options): "Initializes the XML Base Class " # This is a general pattern for adding a lot of options # The next more advanced thing to do is retrieve defaults from a settings file defaults={"root":"root", "style_sheet":os.path.join(XSLT_REPOSITORY,'DEFAULT_STYLE.xsl').replace('\\','/'), "specific_descriptor":'XML', "general_descriptor":'Document', "directory":None, "extension":'xml', "content":None } self.options={} for key,value in defaults.items(): self.options[key]=value for key,value in options.items(): self.options[key]=value # Define Method Aliases if they are available if METHOD_ALIASES: for command in alias(self): exec(command) #if the file path is not supplied create a new xml sheet if file_path is None: if self.options["content"]: self.document = xml.dom.minidom.parseString(self.options["content"]) self.options["content"]=None else: impl=getDOMImplementation() self.document=impl.createDocument(None,self.options['root'],None) # Should be a relative path for if self.options["style_sheet"] is not None: new_node=self.document.createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="{0}"'.format(self.options['style_sheet'])) self.document.insertBefore(new_node,self.document.documentElement) if DEFAULT_FILE_NAME is None: self.path=auto_name(self.options["specific_descriptor"], self.options["general_descriptor"], self.options["directory"], self.options["extension"]) else: # Just a backup plan if the python path is messed up self.path=DEFAULT_FILE_NAME else: try: try: file_in = open(file_path, 'r', encoding="utf-8") except: file_in = open(file_path, 'r') self.document = xml.dom.minidom.parse(file_in) file_in.close() self.path = file_path except: file_in = open(file_path, 'r', encoding="utf-8") content = str(file_in.read()) # print("File Content is {0}".format(content)) self.etree = etree.fromstring(content) self.document = xml.dom.minidom.parseString(etree.tostring(self.etree, encoding="unicode")) self.etree=etree.fromstring(self.document.toxml())
def get_distribution_type(
self)
Returns the type of Distribution. The choices are held in DistributionType/Item.
def get_distribution_type(self): """Returns the type of Distribution. The choices are held in DistributionType/Item.""" distribution_type=self.etree.findall(".//DistributionType")[0] text=distribution_type.attrib["ControlText"] return text
def get_distribution_width(
self)
Returns the wdith of the distribution.
def get_distribution_width(self): """Returns the wdith of the distribution.""" distribution_width=self.etree.findall(".//DistributionLimits")[0] text=distribution_width.attrib["ControlText"] return text
def get_mechanism_name(
self)
Returns the mechanism name
def get_mechanism_name(self): """Returns the mechanism name""" units=self.etree.findall(".//MechanismName")[0] text=units.attrib["ControlText"] return text
def get_standard_uncertainty(
self)
returns the standard uncertainty of the parameter
def get_standard_uncertainty(self): """returns the standard uncertainty of the parameter""" uncertainty=self.etree.findall(".//StandardUncertainty")[0] text = uncertainty.attrib["ControlText"] number=float(text.split(":")[-1]) return number
def get_units(
self)
Returns the units of the parameter
def get_units(self): """Returns the units of the parameter""" units=self.etree.findall(".//Units")[0] text=units.attrib["ControlText"] return text
def get_value(
self)
Returns the value of the parameter
def get_value(self): """Returns the value of the parameter""" mechanism_value=self.etree.findall(".//MechanismValue")[0] value=mechanism_value.attrib["ControlText"] return float(value)
def save(
self, path=None)
" Saves as an XML file
def save(self,path=None): """" Saves as an XML file""" if path is None: path=self.path file_out=open(path,'w') file_out.write(str(self)) file_out.close()
def save_HTML(
self, file_path=None, XSLT=None)
Saves a HTML transformation of the XML document using XLST at file_path. Defaults to an XLST in self.options["XSLT"] and file_path=self.path.replace('.xml','.html')
def save_HTML(self,file_path=None,XSLT=None): """Saves a HTML transformation of the XML document using XLST at file_path. Defaults to an XLST in self.options["XSLT"] and file_path=self.path.replace('.xml','.html')""" if XSLT is None: # For some reason an absolute path tends to break here, maybe a spaces in file names problem XSLT=self.options['style_sheet'] HTML=self.to_HTML(XSLT=XSLT) #print type(HTML) if file_path is None: file_path=self.path.replace('.xml','.html') out_file=open(file_path,'w') out_file.write(HTML) out_file.close()
def set_distribution_type(
self, distribution_type)
Sets the distribution type, accepts an integer or text value. See the constant MODEL_DISTRIBUTION_LIST for possibilities. Rectangular is 0, Gaussian is 3.
def set_distribution_type(self,distribution_type): """Sets the distribution type, accepts an integer or text value. See the constant MODEL_DISTRIBUTION_LIST for possibilities. Rectangular is 0, Gaussian is 3. """ if type(distribution_type) in [IntType,FloatType]: type_number=distribution_type type_name=MODEL_DISTRIBUTION_LIST[distribution_type] elif distribution_type in MODEL_DISTRIBUTION_LIST: type_number=MODEL_DISTRIBUTION_LIST.index(distribution_type) type_name=distribution_type else: print(("Could not set the type {0} please choose a" " type or index from {1}".format(distribution_type,MODEL_DISTRIBUTION_LIST))) return distribution_type_tag = self.etree.findall(".//DistributionType")[0] distribution_type_tag.attrib["ControlText"]=type_name distribution_type_tag.attrib["SelectedIndex"]=type_number self.update_document()
def set_distribution_width(
self, distribution_width)
Sets the distribution width
def set_distribution_width(self,distribution_width): """Sets the distribution width""" distribution_width = self.etree.findall(".//DistributionLimits")[0] distribution_width.attrib["ControlText"]=str(distribution_width) self.update_document()
def set_units(
self, units)
Sets the units of the parameter can accept either an index or value. Look at MODEL_UNIT_LIST for complete set of possibilities
def set_units(self,units): """Sets the units of the parameter can accept either an index or value. Look at MODEL_UNIT_LIST for complete set of possibilities""" if type(units) in [IntType,FloatType]: unit_number=units unit_name=MODEL_DISTRIBUTION_LIST[units] elif units in MODEL_DISTRIBUTION_LIST: unit_number=MODEL_DISTRIBUTION_LIST.index(units) unit_name=units else: print(("Could not set the units {0} please choose a" " type or index from {1}".format(units,MODEL_UNIT_LIST))) return unit_tag = self.etree.findall(".//Units")[0] unit_tag.attrib["ControlText"]=unit_name unit_tag.attrib["SelectedIndex"]=unit_number self.update_document()
def set_value(
self, value)
Sets the value (center of distribution)
def set_value(self,value): """Sets the value (center of distribution)""" mechanism_value=self.etree.findall(".//MechanismValue")[0] mechanism_value.attrib["ControlText"]=str(value) self.update_document()
def show(
self, mode='Window')
Displays a XML Document either as formatted text in the command line or in a window (using wx)
def show(self,mode='Window'): """ Displays a XML Document either as formatted text in the command line or in a window (using wx)""" def tag_to_tagName(tag): tagName=tag.replace('<','') tagName=tagName.replace('/','') tagName=tagName.replace('>','') return tagName if mode in ['text','txt','cmd line','cmd']: for node in self.document.getElementsByTagName('Entry'): print('Entry Index: %s \tDate: %s'%(node.getAttribute('Index'), node.getAttribute('Date'))) print(node.firstChild.nodeValue) elif re.search('xml',mode,re.IGNORECASE): for node in self.document.getElementsByTagName('Entry'): print(node.toprettyxml()) elif re.search('Window|wx',mode,re.IGNORECASE): try: import wx import wx.html2 except: print('Cannot locate wx, please add to sys.path') app = wx.App(False) frame=wx.Frame(None) html_window=wx.html2.WebView.New(frame) html_window.SetPage(str(self.to_HTML()),"") frame.Show() app.MainLoop()
def to_HTML(
self, XSLT=None)
Returns HTML string by applying a XSL to the XML document
def to_HTML(self,XSLT=None): """ Returns HTML string by applying a XSL to the XML document""" if XSLT is None: # For some reason an absolute path tends to break here, maybe a spaces in file names problem XSLT=self.options['style_sheet'] XSL_data=etree.parse(XSLT) XSL_transform=etree.XSLT(XSL_data) HTML=XSL_transform(etree.XML(self.document.toxml())) return str(HTML)
def update_document(
self)
Updates the attribute document from the self.etree.
def update_document(self): """Updates the attribute document from the self.etree. """ self.document=xml.dom.minidom.parseString(etree.tostring(self.etree))
def update_etree(
self)
Updates the attribute etree. Should be called anytime the xml content is changed
def update_etree(self): "Updates the attribute etree. Should be called anytime the xml content is changed" self.etree = etree.fromstring(self.document.toxml())
class MUFSolution
class MUFSolution(XMLBase): pass
Ancestors (in MRO)
- MUFSolution
- Code.DataHandlers.XMLModels.XMLBase
Methods
def __init__(
self, file_path=None, **options)
Initializes the XML Base Class
def __init__(self,file_path=None,**options): "Initializes the XML Base Class " # This is a general pattern for adding a lot of options # The next more advanced thing to do is retrieve defaults from a settings file defaults={"root":"root", "style_sheet":os.path.join(XSLT_REPOSITORY,'DEFAULT_STYLE.xsl').replace('\\','/'), "specific_descriptor":'XML', "general_descriptor":'Document', "directory":None, "extension":'xml', "content":None } self.options={} for key,value in defaults.items(): self.options[key]=value for key,value in options.items(): self.options[key]=value # Define Method Aliases if they are available if METHOD_ALIASES: for command in alias(self): exec(command) #if the file path is not supplied create a new xml sheet if file_path is None: if self.options["content"]: self.document = xml.dom.minidom.parseString(self.options["content"]) self.options["content"]=None else: impl=getDOMImplementation() self.document=impl.createDocument(None,self.options['root'],None) # Should be a relative path for if self.options["style_sheet"] is not None: new_node=self.document.createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="{0}"'.format(self.options['style_sheet'])) self.document.insertBefore(new_node,self.document.documentElement) if DEFAULT_FILE_NAME is None: self.path=auto_name(self.options["specific_descriptor"], self.options["general_descriptor"], self.options["directory"], self.options["extension"]) else: # Just a backup plan if the python path is messed up self.path=DEFAULT_FILE_NAME else: try: try: file_in = open(file_path, 'r', encoding="utf-8") except: file_in = open(file_path, 'r') self.document = xml.dom.minidom.parse(file_in) file_in.close() self.path = file_path except: file_in = open(file_path, 'r', encoding="utf-8") content = str(file_in.read()) # print("File Content is {0}".format(content)) self.etree = etree.fromstring(content) self.document = xml.dom.minidom.parseString(etree.tostring(self.etree, encoding="unicode")) self.etree=etree.fromstring(self.document.toxml())
def save(
self, path=None)
" Saves as an XML file
def save(self,path=None): """" Saves as an XML file""" if path is None: path=self.path file_out=open(path,'w') file_out.write(str(self)) file_out.close()
def save_HTML(
self, file_path=None, XSLT=None)
Saves a HTML transformation of the XML document using XLST at file_path. Defaults to an XLST in self.options["XSLT"] and file_path=self.path.replace('.xml','.html')
def save_HTML(self,file_path=None,XSLT=None): """Saves a HTML transformation of the XML document using XLST at file_path. Defaults to an XLST in self.options["XSLT"] and file_path=self.path.replace('.xml','.html')""" if XSLT is None: # For some reason an absolute path tends to break here, maybe a spaces in file names problem XSLT=self.options['style_sheet'] HTML=self.to_HTML(XSLT=XSLT) #print type(HTML) if file_path is None: file_path=self.path.replace('.xml','.html') out_file=open(file_path,'w') out_file.write(HTML) out_file.close()
def show(
self, mode='Window')
Displays a XML Document either as formatted text in the command line or in a window (using wx)
def show(self,mode='Window'): """ Displays a XML Document either as formatted text in the command line or in a window (using wx)""" def tag_to_tagName(tag): tagName=tag.replace('<','') tagName=tagName.replace('/','') tagName=tagName.replace('>','') return tagName if mode in ['text','txt','cmd line','cmd']: for node in self.document.getElementsByTagName('Entry'): print('Entry Index: %s \tDate: %s'%(node.getAttribute('Index'), node.getAttribute('Date'))) print(node.firstChild.nodeValue) elif re.search('xml',mode,re.IGNORECASE): for node in self.document.getElementsByTagName('Entry'): print(node.toprettyxml()) elif re.search('Window|wx',mode,re.IGNORECASE): try: import wx import wx.html2 except: print('Cannot locate wx, please add to sys.path') app = wx.App(False) frame=wx.Frame(None) html_window=wx.html2.WebView.New(frame) html_window.SetPage(str(self.to_HTML()),"") frame.Show() app.MainLoop()
def to_HTML(
self, XSLT=None)
Returns HTML string by applying a XSL to the XML document
def to_HTML(self,XSLT=None): """ Returns HTML string by applying a XSL to the XML document""" if XSLT is None: # For some reason an absolute path tends to break here, maybe a spaces in file names problem XSLT=self.options['style_sheet'] XSL_data=etree.parse(XSLT) XSL_transform=etree.XSLT(XSL_data) HTML=XSL_transform(etree.XML(self.document.toxml())) return str(HTML)
def update_document(
self)
Updates the attribute document from the self.etree.
def update_document(self): """Updates the attribute document from the self.etree. """ self.document=xml.dom.minidom.parseString(etree.tostring(self.etree))
def update_etree(
self)
Updates the attribute etree. Should be called anytime the xml content is changed
def update_etree(self): "Updates the attribute etree. Should be called anytime the xml content is changed" self.etree = etree.fromstring(self.document.toxml())
class MUFVNAUncert
class MUFVNAUncert(XMLBase): def get_results_directory(self): "Returns the results directory" results_directory=self.etree.findall(".//MenuStripTextBoxes/ResultsDirectory")[0].attrib["Text"] return results_directory def set_results_directory(self,directory=None): "Sets the results directory, default is the current working directory" if directory is None: directory=os.getcwd() results_directory = self.document.getElementsByTagName("ResultsDirectory")[0] results_directory.setAttribute(attname="Text", value=directory) check_box=self.document.getElementsByTagName("SelectResultsDirectoryToolStripMenuItem")[0] check_box.setAttribute(attname="Checked", value="True") self.update_etree() def get_number_standards(self): "Returns the number of calibration standards in the before calibration" sub_items = self.etree.findall(".//BeforeCalibration/Item") return len(sub_items) def get_standard_definition(self,standard_number=1): "Returns the xml definition of the standard in position standard_number" sub_items = self.etree.findall(".//BeforeCalibration/Item") return etree.tostring(sub_items[standard_number-1]) def get_standard_measurement_locations(self): """Returns the file locations for the measurement of the standards in a form of a list""" standards = self.etree.findall(".//BeforeCalibration/Item/SubItem[@Index='6']") locations=[standard.attrib["Text"] for standard in standards] return locations def set_standard_location(self,standard_location=None,standard_number=1): """Sets the location for the measurement of standard_number""" standards = self.etree.findall(".//BeforeCalibration/Item/SubItem[@Index='6']") standard=standards[standard_number-1] standard.attrib["Text"]=standard_location self.update_document() def get_number_montecarlo(self): "Returns the number of montecarlo simulations" montecarlo_text_box=self.etree.findall(".//MenuStripTextBoxes/NumberMonteCarloSimulations")[0] number_montecarlo=montecarlo_text_box.attrib["Text"] return number_montecarlo def set_number_montecarlo(self,number_montecarlo=100): """Sets the number of montecarlo trials for the menu""" montecarlo_text_box = self.etree.findall(".//MenuStripTextBoxes/NumberMonteCarloSimulations")[0] montecarlo_text_box.attrib["Text"]=str(number_montecarlo) self.update_document() def get_DUTs(self): "Returns the names and locations of DUTs" duts=[] names=[x.attrib["Text"] for x in self.etree.findall(".//DUTMeasurements/Item/SubItem[@Index='0']")] locations=[x.attrib["Text"] for x in self.etree.findall(".//DUTMeasurements/Item/SubItem[@Index='1']")] for index,name in enumerate(names): name_location_dictionary={"name":name,"location":locations[index]} duts.append(name_location_dictionary) return duts def add_DUT(self,location,name=None): """Adds a DUT to the DUTMeasurements element""" # get the name if name is None: name=os.path.basename(location).split(".")[0] # first get the DUTMeasurement element dut_measurement=self.etree.findall(".//DUTMeasurements")[0] # next add one to the count attribute number_standards=int(dut_measurement.attrib["Count"]) number_standards+=1 dut_measurement.attrib["Count"]=str(number_standards) # create a Item item=etree.SubElement(dut_measurement,"Item",attrib={"Count":"2","Index":str(number_standards),"Text":name}) etree.SubElement(item,"SubItem",attrib={"Index":"0","Text":name}) etree.SubElement(item,"SubItem",attrib={"Index":"1","Text":location}) self.update_document() def clear_DUTs(self): """Removes all DUTs""" dut_measurement = self.etree.findall(".//DUTMeasurements")[0] items= self.etree.findall(".//DUTMeasurements/Item") for item in items: dut_measurement.remove(item) self.update_document()
Ancestors (in MRO)
- MUFVNAUncert
- Code.DataHandlers.XMLModels.XMLBase
Methods
def __init__(
self, file_path=None, **options)
Initializes the XML Base Class
def __init__(self,file_path=None,**options): "Initializes the XML Base Class " # This is a general pattern for adding a lot of options # The next more advanced thing to do is retrieve defaults from a settings file defaults={"root":"root", "style_sheet":os.path.join(XSLT_REPOSITORY,'DEFAULT_STYLE.xsl').replace('\\','/'), "specific_descriptor":'XML', "general_descriptor":'Document', "directory":None, "extension":'xml', "content":None } self.options={} for key,value in defaults.items(): self.options[key]=value for key,value in options.items(): self.options[key]=value # Define Method Aliases if they are available if METHOD_ALIASES: for command in alias(self): exec(command) #if the file path is not supplied create a new xml sheet if file_path is None: if self.options["content"]: self.document = xml.dom.minidom.parseString(self.options["content"]) self.options["content"]=None else: impl=getDOMImplementation() self.document=impl.createDocument(None,self.options['root'],None) # Should be a relative path for if self.options["style_sheet"] is not None: new_node=self.document.createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="{0}"'.format(self.options['style_sheet'])) self.document.insertBefore(new_node,self.document.documentElement) if DEFAULT_FILE_NAME is None: self.path=auto_name(self.options["specific_descriptor"], self.options["general_descriptor"], self.options["directory"], self.options["extension"]) else: # Just a backup plan if the python path is messed up self.path=DEFAULT_FILE_NAME else: try: try: file_in = open(file_path, 'r', encoding="utf-8") except: file_in = open(file_path, 'r') self.document = xml.dom.minidom.parse(file_in) file_in.close() self.path = file_path except: file_in = open(file_path, 'r', encoding="utf-8") content = str(file_in.read()) # print("File Content is {0}".format(content)) self.etree = etree.fromstring(content) self.document = xml.dom.minidom.parseString(etree.tostring(self.etree, encoding="unicode")) self.etree=etree.fromstring(self.document.toxml())
def add_DUT(
self, location, name=None)
Adds a DUT to the DUTMeasurements element
def add_DUT(self,location,name=None): """Adds a DUT to the DUTMeasurements element""" # get the name if name is None: name=os.path.basename(location).split(".")[0] # first get the DUTMeasurement element dut_measurement=self.etree.findall(".//DUTMeasurements")[0] # next add one to the count attribute number_standards=int(dut_measurement.attrib["Count"]) number_standards+=1 dut_measurement.attrib["Count"]=str(number_standards) # create a Item item=etree.SubElement(dut_measurement,"Item",attrib={"Count":"2","Index":str(number_standards),"Text":name}) etree.SubElement(item,"SubItem",attrib={"Index":"0","Text":name}) etree.SubElement(item,"SubItem",attrib={"Index":"1","Text":location}) self.update_document()
def clear_DUTs(
self)
Removes all DUTs
def clear_DUTs(self): """Removes all DUTs""" dut_measurement = self.etree.findall(".//DUTMeasurements")[0] items= self.etree.findall(".//DUTMeasurements/Item") for item in items: dut_measurement.remove(item) self.update_document()
def get_DUTs(
self)
Returns the names and locations of DUTs
def get_DUTs(self): "Returns the names and locations of DUTs" duts=[] names=[x.attrib["Text"] for x in self.etree.findall(".//DUTMeasurements/Item/SubItem[@Index='0']")] locations=[x.attrib["Text"] for x in self.etree.findall(".//DUTMeasurements/Item/SubItem[@Index='1']")] for index,name in enumerate(names): name_location_dictionary={"name":name,"location":locations[index]} duts.append(name_location_dictionary) return duts
def get_number_montecarlo(
self)
Returns the number of montecarlo simulations
def get_number_montecarlo(self): "Returns the number of montecarlo simulations" montecarlo_text_box=self.etree.findall(".//MenuStripTextBoxes/NumberMonteCarloSimulations")[0] number_montecarlo=montecarlo_text_box.attrib["Text"] return number_montecarlo
def get_number_standards(
self)
Returns the number of calibration standards in the before calibration
def get_number_standards(self): "Returns the number of calibration standards in the before calibration" sub_items = self.etree.findall(".//BeforeCalibration/Item") return len(sub_items)
def get_results_directory(
self)
Returns the results directory
def get_results_directory(self): "Returns the results directory" results_directory=self.etree.findall(".//MenuStripTextBoxes/ResultsDirectory")[0].attrib["Text"] return results_directory
def get_standard_definition(
self, standard_number=1)
Returns the xml definition of the standard in position standard_number
def get_standard_definition(self,standard_number=1): "Returns the xml definition of the standard in position standard_number" sub_items = self.etree.findall(".//BeforeCalibration/Item") return etree.tostring(sub_items[standard_number-1])
def get_standard_measurement_locations(
self)
Returns the file locations for the measurement of the standards in a form of a list
def get_standard_measurement_locations(self): """Returns the file locations for the measurement of the standards in a form of a list""" standards = self.etree.findall(".//BeforeCalibration/Item/SubItem[@Index='6']") locations=[standard.attrib["Text"] for standard in standards] return locations
def save(
self, path=None)
" Saves as an XML file
def save(self,path=None): """" Saves as an XML file""" if path is None: path=self.path file_out=open(path,'w') file_out.write(str(self)) file_out.close()
def save_HTML(
self, file_path=None, XSLT=None)
Saves a HTML transformation of the XML document using XLST at file_path. Defaults to an XLST in self.options["XSLT"] and file_path=self.path.replace('.xml','.html')
def save_HTML(self,file_path=None,XSLT=None): """Saves a HTML transformation of the XML document using XLST at file_path. Defaults to an XLST in self.options["XSLT"] and file_path=self.path.replace('.xml','.html')""" if XSLT is None: # For some reason an absolute path tends to break here, maybe a spaces in file names problem XSLT=self.options['style_sheet'] HTML=self.to_HTML(XSLT=XSLT) #print type(HTML) if file_path is None: file_path=self.path.replace('.xml','.html') out_file=open(file_path,'w') out_file.write(HTML) out_file.close()
def set_number_montecarlo(
self, number_montecarlo=100)
Sets the number of montecarlo trials for the menu
def set_number_montecarlo(self,number_montecarlo=100): """Sets the number of montecarlo trials for the menu""" montecarlo_text_box = self.etree.findall(".//MenuStripTextBoxes/NumberMonteCarloSimulations")[0] montecarlo_text_box.attrib["Text"]=str(number_montecarlo) self.update_document()
def set_results_directory(
self, directory=None)
Sets the results directory, default is the current working directory
def set_results_directory(self,directory=None): "Sets the results directory, default is the current working directory" if directory is None: directory=os.getcwd() results_directory = self.document.getElementsByTagName("ResultsDirectory")[0] results_directory.setAttribute(attname="Text", value=directory) check_box=self.document.getElementsByTagName("SelectResultsDirectoryToolStripMenuItem")[0] check_box.setAttribute(attname="Checked", value="True") self.update_etree()
def set_standard_location(
self, standard_location=None, standard_number=1)
Sets the location for the measurement of standard_number
def set_standard_location(self,standard_location=None,standard_number=1): """Sets the location for the measurement of standard_number""" standards = self.etree.findall(".//BeforeCalibration/Item/SubItem[@Index='6']") standard=standards[standard_number-1] standard.attrib["Text"]=standard_location self.update_document()
def show(
self, mode='Window')
Displays a XML Document either as formatted text in the command line or in a window (using wx)
def show(self,mode='Window'): """ Displays a XML Document either as formatted text in the command line or in a window (using wx)""" def tag_to_tagName(tag): tagName=tag.replace('<','') tagName=tagName.replace('/','') tagName=tagName.replace('>','') return tagName if mode in ['text','txt','cmd line','cmd']: for node in self.document.getElementsByTagName('Entry'): print('Entry Index: %s \tDate: %s'%(node.getAttribute('Index'), node.getAttribute('Date'))) print(node.firstChild.nodeValue) elif re.search('xml',mode,re.IGNORECASE): for node in self.document.getElementsByTagName('Entry'): print(node.toprettyxml()) elif re.search('Window|wx',mode,re.IGNORECASE): try: import wx import wx.html2 except: print('Cannot locate wx, please add to sys.path') app = wx.App(False) frame=wx.Frame(None) html_window=wx.html2.WebView.New(frame) html_window.SetPage(str(self.to_HTML()),"") frame.Show() app.MainLoop()
def to_HTML(
self, XSLT=None)
Returns HTML string by applying a XSL to the XML document
def to_HTML(self,XSLT=None): """ Returns HTML string by applying a XSL to the XML document""" if XSLT is None: # For some reason an absolute path tends to break here, maybe a spaces in file names problem XSLT=self.options['style_sheet'] XSL_data=etree.parse(XSLT) XSL_transform=etree.XSLT(XSL_data) HTML=XSL_transform(etree.XML(self.document.toxml())) return str(HTML)
def update_document(
self)
Updates the attribute document from the self.etree.
def update_document(self): """Updates the attribute document from the self.etree. """ self.document=xml.dom.minidom.parseString(etree.tostring(self.etree))
def update_etree(
self)
Updates the attribute etree. Should be called anytime the xml content is changed
def update_etree(self): "Updates the attribute etree. Should be called anytime the xml content is changed" self.etree = etree.fromstring(self.document.toxml())
class MUFVNAUncertArchive
class MUFVNAUncertArchive(XMLBase): pass
Ancestors (in MRO)
- MUFVNAUncertArchive
- Code.DataHandlers.XMLModels.XMLBase
Methods
def __init__(
self, file_path=None, **options)
Initializes the XML Base Class
def __init__(self,file_path=None,**options): "Initializes the XML Base Class " # This is a general pattern for adding a lot of options # The next more advanced thing to do is retrieve defaults from a settings file defaults={"root":"root", "style_sheet":os.path.join(XSLT_REPOSITORY,'DEFAULT_STYLE.xsl').replace('\\','/'), "specific_descriptor":'XML', "general_descriptor":'Document', "directory":None, "extension":'xml', "content":None } self.options={} for key,value in defaults.items(): self.options[key]=value for key,value in options.items(): self.options[key]=value # Define Method Aliases if they are available if METHOD_ALIASES: for command in alias(self): exec(command) #if the file path is not supplied create a new xml sheet if file_path is None: if self.options["content"]: self.document = xml.dom.minidom.parseString(self.options["content"]) self.options["content"]=None else: impl=getDOMImplementation() self.document=impl.createDocument(None,self.options['root'],None) # Should be a relative path for if self.options["style_sheet"] is not None: new_node=self.document.createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="{0}"'.format(self.options['style_sheet'])) self.document.insertBefore(new_node,self.document.documentElement) if DEFAULT_FILE_NAME is None: self.path=auto_name(self.options["specific_descriptor"], self.options["general_descriptor"], self.options["directory"], self.options["extension"]) else: # Just a backup plan if the python path is messed up self.path=DEFAULT_FILE_NAME else: try: try: file_in = open(file_path, 'r', encoding="utf-8") except: file_in = open(file_path, 'r') self.document = xml.dom.minidom.parse(file_in) file_in.close() self.path = file_path except: file_in = open(file_path, 'r', encoding="utf-8") content = str(file_in.read()) # print("File Content is {0}".format(content)) self.etree = etree.fromstring(content) self.document = xml.dom.minidom.parseString(etree.tostring(self.etree, encoding="unicode")) self.etree=etree.fromstring(self.document.toxml())
def save(
self, path=None)
" Saves as an XML file
def save(self,path=None): """" Saves as an XML file""" if path is None: path=self.path file_out=open(path,'w') file_out.write(str(self)) file_out.close()
def save_HTML(
self, file_path=None, XSLT=None)
Saves a HTML transformation of the XML document using XLST at file_path. Defaults to an XLST in self.options["XSLT"] and file_path=self.path.replace('.xml','.html')
def save_HTML(self,file_path=None,XSLT=None): """Saves a HTML transformation of the XML document using XLST at file_path. Defaults to an XLST in self.options["XSLT"] and file_path=self.path.replace('.xml','.html')""" if XSLT is None: # For some reason an absolute path tends to break here, maybe a spaces in file names problem XSLT=self.options['style_sheet'] HTML=self.to_HTML(XSLT=XSLT) #print type(HTML) if file_path is None: file_path=self.path.replace('.xml','.html') out_file=open(file_path,'w') out_file.write(HTML) out_file.close()
def show(
self, mode='Window')
Displays a XML Document either as formatted text in the command line or in a window (using wx)
def show(self,mode='Window'): """ Displays a XML Document either as formatted text in the command line or in a window (using wx)""" def tag_to_tagName(tag): tagName=tag.replace('<','') tagName=tagName.replace('/','') tagName=tagName.replace('>','') return tagName if mode in ['text','txt','cmd line','cmd']: for node in self.document.getElementsByTagName('Entry'): print('Entry Index: %s \tDate: %s'%(node.getAttribute('Index'), node.getAttribute('Date'))) print(node.firstChild.nodeValue) elif re.search('xml',mode,re.IGNORECASE): for node in self.document.getElementsByTagName('Entry'): print(node.toprettyxml()) elif re.search('Window|wx',mode,re.IGNORECASE): try: import wx import wx.html2 except: print('Cannot locate wx, please add to sys.path') app = wx.App(False) frame=wx.Frame(None) html_window=wx.html2.WebView.New(frame) html_window.SetPage(str(self.to_HTML()),"") frame.Show() app.MainLoop()
def to_HTML(
self, XSLT=None)
Returns HTML string by applying a XSL to the XML document
def to_HTML(self,XSLT=None): """ Returns HTML string by applying a XSL to the XML document""" if XSLT is None: # For some reason an absolute path tends to break here, maybe a spaces in file names problem XSLT=self.options['style_sheet'] XSL_data=etree.parse(XSLT) XSL_transform=etree.XSLT(XSL_data) HTML=XSL_transform(etree.XML(self.document.toxml())) return str(HTML)
def update_document(
self)
Updates the attribute document from the self.etree.
def update_document(self): """Updates the attribute document from the self.etree. """ self.document=xml.dom.minidom.parseString(etree.tostring(self.etree))
def update_etree(
self)
Updates the attribute etree. Should be called anytime the xml content is changed
def update_etree(self): "Updates the attribute etree. Should be called anytime the xml content is changed" self.etree = etree.fromstring(self.document.toxml())
Module variables
var CLR
var DEFAULT_FILE_NAME
var DEFAULT_INSTRUMENT_SHEET_STYLE
var DEFAULT_INSTRUMENT_STATE_STYLE
var DEFAULT_LOG_STYLE
var DEFAULT_MEASUREMENT_STYLE
var DEFAULT_METADATA_STYLE
var DEFAULT_REGISTER_STYLE
var DEFAULT_STYLE
var DRIVER_FILE_EXTENSIONS
var EXIF_AVAILABLE
var GENERAL_DESCRIPTORS
var GET_STATS_FIELDS
var IMAGE_FILE_EXTENSIONS
var INSTRUMENT_SHEETS
var METHOD_ALIASES
var MODEL_DISTRIBUTION_LIST
var MODEL_UNIT_LIST
var NODE_TYPE_DICTIONARY
var NUMBER_MATCH_STRING
var OS_STAT_FIELDS
var PIL_AVAILABLE
var PYMEASURE_ROOT
var SCRIPTABLE_MUF_LOCATION
Location of the MUF executable with modifications to make it scriptable.
var StringTypes
var TESTS_DIRECTORY
var XSLT_CAPABLE
var XSLT_REPOSITORY
var type_names