Esempio n. 1
0
def test_gettables():
    """py.test for gettables"""
    thedata = (
        (
            [
                ("Site and Source Energy", [["a", "2"], ["3", "4"]]),
                ("Site to Source Energy Conversion Factors", [["b", "6"], ["7", "8"]]),
                ("Custom Monthly Report", [["c", "16"], ["17", "18"]]),
                ("Custom Monthly Report", [["d", "26"], ["27", "28"]]),
            ],
            False,
        ),  # titlerows, tofloat
        (
            [
                ("Site and Source Energy", [["a", 2], [3, 4]]),
                ("Site to Source Energy Conversion Factors", [["b", 6], [7, 8]]),
                ("Custom Monthly Report", [["c", 16], [17, 18]]),
                ("Custom Monthly Report", [["d", 26], [27, 28]]),
            ],
            True,
        ),  # titlerows, tofloat
    )
    for titlerows, tofloat in thedata:
        result = readhtml.titletable(SAMPLE_HTML, tofloat=tofloat)
        for (title1, rows1), (title2, rows2) in zip(result, titlerows):
            assert title1 == title2
            assert rows1 == rows2
        assert result == titlerows
Esempio n. 2
0
def tablebyindex(filehandle, index):
    """fast extraction of the table using the index to identify the table

    This function reads only one table from the HTML file. This is in contrast to `results.readhtml.titletable` that will read all the tables into memory and allows you to interactively look thru them. The function `results.readhtml.titletable` can be very slow on large HTML files.

    This function is useful when you know which file you are looking for. It does not work with negative indices, like you can in a list. If you know a way to make negative indices work, do a pull request :-)

    Parameters
    ----------
    fhandle : file like object
        A file handle to the E+ HTML table file
    index: int
        This is the index of the table you are looking for

    Returns
    -------
    titleandtable : (str, list)
        - (title, table)
            - title = previous item with a <b> tag
            - table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..]
    """
    with filehandle:
        tableindex = 0
        for i in range(index + 1):
            thetable = get_upto_nexttable(filehandle)
    filehandle = StringIO(thetable)
    htables = readhtml.titletable(filehandle)
    try:
        return htables[0]
    except IndexError as e:
        None
Esempio n. 3
0
def test_gettables():
    """py.test for gettables"""
    thedata = (
        ([('Site and Source Energy', [['a', '2'], ['3', '4']]),
          ('Site to Source Energy Conversion Factors', [['b', '6'], ['7',
                                                                     '8']]),
          ('Custom Monthly Report', [['c', '16'], ['17', '18']]),
          ('Custom Monthly Report', [['d', '26'],
                                     ['27',
                                      '28']])], False),  # titlerows, tofloat
        ([('Site and Source Energy', [['a', 2], [3, 4]]),
          ('Site to Source Energy Conversion Factors', [['b', 6], [7, 8]]),
          ('Custom Monthly Report', [['c', 16], [17, 18]]),
          ('Custom Monthly Report', [['d', 26],
                                     [27, 28]])], True),  # titlerows, tofloat
    )
    for titlerows, tofloat in thedata:
        # print titlerows
        result = readhtml.titletable(SAMPLE_HTML, tofloat=tofloat)
        for (title1, rows1), (title2, rows2) in zip(result, titlerows):
            # print title1, title2
            assert title1 == title2
            # print rows1, rows2
            assert rows1 == rows2
        assert result == titlerows
    def __init__(self):
        #Change EplusPath Here
        eplusPath="D:/EnergyPlusV8-6-0/energyplus.exe"

        #Automate Setting
        self.path=os.path.abspath('.')
        sys.path.append(self.path)
        self.idfName = "test6.idf"
        self.eplusPath=eplusPath
        self.iddFile = "Energy+.idd"
        IDF.setiddname(self.iddFile)
        self.outputPath="."
        self.idf1 = IDF(self.idfName)
        self.epwFile = "SGP_Singapore.486980_IWEC.epw"
        esoPath="5ZoneAirCooled.eso"

        #Call Eplus Here
        # subprocess.call([self.eplusPath,'-i',self.iddFile,'-w',self.epwFile,'-d',self.outputPath,self.idfName])

        self.htmFile = "eplustbl.htm"
        fileHandle = open(self.htmFile, 'r').read() # get a file handle to the html file
        self.eplusOutputTables = readhtml.titletable(fileHandle) # reads the tables with their titles
        
        self.ETTV=Class_ETTV.ETTV()
        self.ETTV.ETTVCalculator(self.eplusOutputTables)
        self.RTTV=Class_RTTV.RTTV()
        self.RTTV.RTTVCalculator(self.eplusOutputTables,self.idf1)
        self.Trop=Class_Trop.Trop()
        self.Trop.TropCalculator(self.eplusOutputTables,self.RTTV.RTTV)
        self.TDSE=Class_TDSE.TDSE()
        self.TDSE.TDSECalculator(self.eplusOutputTables,esoPath)

        #Output
        self.get()
Esempio n. 5
0
 def setfolder(self):
     """
     set folder and set html file
     :return:
     """
     files = os.listdir(self.folder)
     for file in files:
         print(file)
         if file.endswith('Table.html'):
             html = open((str(self.folder) + '/' + file), 'r').read()
             self.htables = readhtml.titletable(html)
             name = file[0:-10] + '.csv'
Esempio n. 6
0
def test_gettables():
    """py.test for gettables"""
    thedata = (
        (
            [
                (
                    'Site and Source Energy',
                    [['a', '2'], ['3', '4']]
                ),
                (
                    'Site to Source Energy Conversion Factors',
                    [['b', '6'], ['7', '8']]
                ),
                (
                    'Custom Monthly Report',
                    [['c', '16'], ['17', '18']]
                ),
                (
                    'Custom Monthly Report',
                    [['d', '26'], ['27', '28']]
                )
            ], False), # titlerows, tofloat
        (
            [
                (
                    'Site and Source Energy',
                    [['a', 2], [3, 4]]
                ),
                (
                    'Site to Source Energy Conversion Factors',
                    [['b', 6], [7, 8]]
                ),
                (
                    'Custom Monthly Report',
                    [['c', 16], [17, 18]]
                ),
                (
                    'Custom Monthly Report',
                    [['d', 26], [27, 28]]
                )
            ], True), # titlerows, tofloat
    )
    for titlerows, tofloat in thedata:
        # print titlerows
        result = readhtml.titletable(SAMPLE_HTML, tofloat=tofloat)
        for (title1, rows1), (title2, rows2) in zip(result, titlerows):
            # print title1, title2
            assert title1 == title2
            # print rows1, rows2
            assert rows1 == rows2
        assert result == titlerows
Esempio n. 7
0
    def run_models(self, processors):
        if self.idf is None:
            raise TypeError('idf not set')
        util = EppyUtilIdf()
        idf_lst = []
        file_dir = os.path.dirname(__file__)
        output_folder = os.path.join(file_dir, 'sensitivity_results')
        try:
            shutil.rmtree(output_folder)
        except FileNotFoundError as e:
            print(e)
        os.mkdir(output_folder)

        for i, values in enumerate(self.X):
            idf_temp = util.copy(self.idf)
            for j, value in enumerate(values):
                for obj in self.objects[j]:
                    obj_id, obj_name, field = obj.split(',')
                    util.mod(idf_temp, obj_id, obj_name, field, value)
            idf_temp.idfname = os.path.join(output_folder,
                                            'run-{}.idf'.format(i))
            idf_temp.save()

            sim_settings = {
                'ep_version': '8-7-0',
                'verbose': 'q',
                'output_directory': output_folder,
                'readvars': True,
                'output_prefix': "run-{}-".format(i)
            }
            idf_lst.append([idf_temp, sim_settings])

        run_functions.runIDFs(idf_lst, processors=processors)
        # retrieve E+ outputs after simulations are run
        num_samples = self.X.shape[0]
        self.y = np.zeros(num_samples)

        for k in range(num_samples):
            result_file = os.path.join(output_folder,
                                       'run-{}-tbl.htm'.format(k))
            with open(result_file, "r", encoding="ISO-8859-1") as f:
                results_table = readhtml.titletable(f.read())

            total_site_energy = util.get_output(
                results_table, ['Site and Source Energy', 'Total Site Energy'])
            total_site_energy_per_area = total_site_energy[1]
            self.y[k] = total_site_energy_per_area
Esempio n. 8
0
def results():
    t_id = []
    cooling = []
    heating = []
    files = glob('sim_result/*.htm')
    i = 1
    for file1 in files:
        filehandle = open(file1, 'r').read()
        htables = readhtml.titletable(filehandle)
        t_id.append(
            re.search('sim_result/([a-z]*)([0-9]*).idf(.*).htm',
                      file1).group(2))
        cooling.append(htables[3][1][-1][4])
        heating.append(htables[3][1][-1][5])
        print(str(i) + "/" + str(total))
        i = i + 1
    data_raw = {'id': t_id, 'cooling': cooling, 'heating': heating}
    df = pd.DataFrame(data_raw)
    df.to_csv("model_outputs.csv", index=False)
Esempio n. 9
0
def getfromhtm(fhandle, htm_options):
    """getdata from htm"""
    returndict = dict(htm_options)
    if htm_options.setdefault("as_tables", None):
        htables = readhtml.titletable(fhandle)
        returndict["result"] = [list(table) for table in htables]
        # made into a list for json conversion
        # json conversion makes it a list
        # so now testing is easier
    elif isinstance(htm_options.setdefault("tableindex", None), int):
        header, table = fasthtml.tablebyindex(fhandle, htm_options["tableindex"])
    elif htm_options.setdefault("tablename", None):
        header, table = fasthtml.tablebyname(fhandle, htm_options["tablename"])
    if htm_options.setdefault("table"):
        returndict["result"] = [header, table]
    elif htm_options.setdefault("rows"):
        irows = htm_options["rows"]
        parttable = list()
        for i in irows:
            parttable.append(table[i])
        returndict["result"] = [header, parttable]
    elif htm_options.setdefault("cols"):
        icols = htm_options["cols"]
        parttable = list()
        for row in table:
            partrow = list()
            for i in icols:
                partrow.append(row[i])
            parttable.append(partrow)
        returndict["result"] = [header, parttable]
    elif htm_options.setdefault("cells"):
        cells = htm_options["cells"]
        somecells = list()
        for cell in cells:
            somecells.append(table[cell[0]][cell[1]])
        returndict["result"] = [header, somecells]
    return returndict
Esempio n. 10
0
def tablebyname(filehandle, header):
    """fast extraction of the table using the header to identify the table

    This function reads only one table from the HTML file. This is in contrast to `results.readhtml.titletable` that will read all the tables into memory and allows you to interactively look thru them. The function `results.readhtml.titletable` can be very slow on large HTML files.

    This function is useful when you know which file you are looking for. It looks for the title line that is in bold just before the table. Some tables don't have such a title in bold. This function will not work for tables that don't have a title in bold

    Parameters
    ----------
    fhandle : file like object
        A file handle to the E+ HTML table file
    header: str
        This is the title of the table you are looking for

    Returns
    -------
    titleandtable : (str, list)
        - (title, table)
            - title = previous item with a <b> tag
            - table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..]
    """
    htmlheader = f"<b>{header}</b><br><br>"

    with filehandle:
        for line in filehandle:
            line = _decodeline(line)
            if line.strip() == htmlheader:
                justtable = getnexttable(filehandle)
                thetable = f"{htmlheader}\n{justtable}"
                break

    filehandle = StringIO(thetable)
    htables = readhtml.titletable(filehandle)
    try:
        return list(htables[0])
    except IndexError as e:
        None
Esempio n. 11
0
	idf_run.run(output_directory=saida,expandobjects=True)

for idf in lista_idfs_AC:
	nome = idf.replace('.idf','')
	saida = os.getcwd() + "\%s" % nome
	idf_run = IDF(idf, epw)
	idf_run.run(output_directory=saida,expandobjects=True)
'''


# RESULTADOS AC
for i in range(len(lista_idfs_AC)):
	fname = "C%d AC/eplustbl.htm"%i
	filehandle = open(fname,'r').read()

	htables = readhtml.titletable(filehandle)
	firstitem = htables[0]
	firstitem_table = firstitem[1]
	secondrow = firstitem_table[2]
	consumo_total = secondrow[1]
	result_AC.write("C%d AC " %i + str(consumo_total) + '\n')

# RESULTADOS VN
for i in range(len(lista_idfs_VN)):
	sum_serie = 0
	path = "C%d VN/eplusout.eso"%i
	dd, data = esoreader.read(path)
	frequency, key, variable = dd.find_variable('Zone Thermal Comfort ASHRAE 55 Adaptive Model 80% Acceptability Status')[0]
	idx = dd.index[frequency, key, variable]
	time_series = data[idx]
	num_hours =8760
Esempio n. 12
0
import sys
import os
from eppy.results import readhtml

lista_de_valores = []
archivoIDF = sys.argv[1]
carpeta = os.path.join(os.path.dirname(archivoIDF),
                       "optimizacion_" + os.path.splitext(os.path.basename(archivoIDF))[0])
fname = os.path.join(carpeta, "eplustbl.htm")  # archivo html valor
filehandle = open(fname, 'r').read()  # get a file handle to the html file
htables = readhtml.titletable(filehandle)  # reads the tables with their titles

valores = []
valores.append(htables[0][1][1][1])
valores.append(htables[0][1][3][1])
valores.append(htables[17][1][2][5])
valores.append(htables[17][1][3][4])
valores.append(htables[11][1][1][1])
valores.append(htables[6][1][2][5])

lista_de_valores.append(valores)

header = []
# TITLE Total Energy (kWh) / Total Site Energy
attrib = ('[' + str(htables[0][1][0][1]) +
          '/' + str(htables[0][1][1][0]) + ']')
header.append(attrib)
# TITLE Total Energy (kWh) / Total Source Energy
attrib1 = ('[' + str(htables[0][1][0][1]) +
           '/' + str(htables[0][1][3][0]) + ']')
header.append(attrib1)