def get_config(self): config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) try: self.base_year = config.get('Base', 'year') except: self.base_year = '2012' parents = [] try: parents = getParents(config.items('Parents')) except: pass try: self.bom_file = config.get('Files', 'bom') for key, value in parents: self.bom_file = self.bom_file.replace(key, value) self.bom_file = self.bom_file.replace('$USER$', getUser()) self.bom_file = self.bom_file.replace('$YEAR$', self.base_year) except: self.bom_file = '' try: self.town_file = config.get('Files', 'towns') for key, value in parents: self.town_file = self.town_file.replace(key, value) self.town_file = self.town_file.replace('$USER$', getUser()) self.town_file = self.town_file.replace('$YEAR$', self.base_year) except: self.town_file = ''
def __init__(self, latitude, longitude, year=None, adjust_wind=None): config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) if year is None: try: self.base_year = config.get('Base', 'year') self.base_year = str(self.base_year) except: self.base_year = '2012' else: self.base_year = year parents = [] try: parents = getParents(config.items('Parents')) except: pass try: self.rain_files = config.get('Files', 'rain_files') for key, value in parents: self.rain_files = self.rain_files.replace(key, value) self.rain_files = self.rain_files.replace('$USER$', getUser()) self.rain_files = self.rain_files.replace('$YEAR$', str(self.base_year)) except: self.rain_files = '' try: self.solar_files = config.get('Files', 'solar_files') for key, value in parents: self.solar_files = self.solar_files.replace(key, value) self.solar_files = self.solar_files.replace('$USER$', getUser()) self.solar_files = self.solar_files.replace('$YEAR$', str(self.base_year)) except: self.solar_files = '' try: self.solar_index = config.get('Files', 'solar_index') for key, value in parents: self.solar_index = self.solar_index.replace(key, value) self.solar_index = self.solar_index.replace('$USER$', getUser()) self.solar_index = self.solar_index.replace('$YEAR$', str(self.base_year)) except: self.solar_index = '' try: self.wind_files = config.get('Files', 'wind_files') for key, value in parents: self.wind_files = self.wind_files.replace(key, value) self.wind_files = self.wind_files.replace('$USER$', getUser()) self.wind_files = self.wind_files.replace('$YEAR$', str(self.base_year)) except: self.wind_files = '' try: self.wind_index = config.get('Files', 'wind_index') for key, value in parents: self.wind_index = self.wind_index.replace(key, value) self.wind_index = self.wind_index.replace('$USER$', getUser()) self.wind_index = self.wind_index.replace('$YEAR$', str(self.base_year)) except: self.wind_index = '' rain = False try: variable = config.get('View', 'resource_rainfall') if variable.lower() in ['true', 'yes', 'on']: rain = True except: pass self.windy = adjust_wind # find closest solar file self.solar_file, dist, lat, lon = self.find_closest(latitude, longitude) if os.path.exists(self.solar_files + '/' + self.solar_file): comment = 'Solar: %s\n at %s, %s (%s Km away)' % (self.solar_file, lat, lon, '{:0,.0f}'.format(dist)) self.wind_file, dist, lat, lon = self.find_closest(latitude, longitude, wind=True) if os.path.exists(self.wind_files + '/' + self.wind_file): if comment != '': comment += '\n' comment += 'Wind: %s\n at %s, %s (%s Km away)' % (self.wind_file, lat, lon, '{:0,.0f}'.format(dist)) plot_order = ['show_menu', 'dhi', 'dni', 'ghi', 'temp', 'wind'] if rain: plot_order.append('rain') plot_order2 = ['hour', 'total', 'month', 'season', 'period', 'mthavg', 'block'] #, 'pdf'] for plt in plot_order2: plot_order.append(plt) if rain: plot_order.append('monthly') plot_order.append('save_plot') self.hdrs = {'show_menu': 'Check / Uncheck all', 'dhi': 'Solar - DHI (Diffuse)', 'dni': 'Solar - DNI (Beam)', 'ghi': 'Solar - GHI (Global)', 'temp': 'Solar - Temperature', 'wind': 'Wind - Speed', 'hour': 'Hourly weather', 'total': 'Daily average', 'month': 'Daily average by month', 'season': 'Daily average by season', 'period': 'Daily average by period', 'mthavg': 'Monthly average', 'block': 'Show plots one at a time', 'pdf': 'Probability Density Function', 'save_plot': 'Save plot data to a file'} if rain: self.hdrs['rain'] = 'Rainfall - mm' self.hdrs['monthly'] = 'Monthly totals' spacers = {'dhi': 'Weather values', 'hour': 'Choose plots (all use a full year of data)', 'save_plot': 'Save plot data'} weathers = ['dhi', 'dni', 'ghi', 'rain', 'temp', 'wind'] self.plots = {} for i in range(len(plot_order)): self.plots[plot_order[i]] = False self.plots['total'] = True what_plots = whatPlots(self.plots, plot_order, self.hdrs, spacers, self.base_year, comment) what_plots.exec_() self.plots = what_plots.getValues() if self.plots is None: return if 'rain' not in list(self.plots.keys()): self.plots['monthly'] = False self.plots['rain'] = False self.x = [] self.ly = {} self.text = '' rain_col = -1 if self.plots['dhi'] or self.plots['dni'] or self.plots['ghi'] or self.plots['temp'] or self.plots['rain']: if os.path.exists(self.solar_files + '/' + self.solar_file): tf = open(self.solar_files + '/' + self.solar_file, 'r') lines = tf.readlines() tf.close() fst_row = len(lines) - 8760 if self.plots['dhi']: self.ly['dhi'] = [] if self.plots['dni']: self.ly['dni'] = [] if self.plots['ghi']: self.ly['ghi'] = [] if self.plots['temp']: self.ly['temp'] = [] if self.plots['wind']: # on the off chance there's no wind file we'll use what we can from solar self.ly['wind'] = [] wind_col = -1 if self.plots['rain']: self.ly['rain'] = [] if self.solar_file[-4:] == '.smw': dhi_col = 9 dni_col = 8 ghi_col = 7 temp_col = 0 elif self.solar_file[-10:] == '(TMY2).csv' or self.solar_file[-10:] == '(TMY3).csv' \ or self.solar_file[-10:] == '(INTL).csv' or self.solar_file[-4:] == '.csv': ghi_col = -1 if fst_row < 3: bits = lines[0].split(',') src_lat = float(bits[4]) src_lon = float(bits[5]) src_zne = float(bits[6]) else: cols = lines[fst_row - 3].split(',') bits = lines[fst_row - 2].split(',') for i in range(len(cols)): if cols[i].lower() in ['latitude', 'lat']: src_lat = float(bits[i]) elif cols[i].lower() in ['longitude', 'lon', 'long', 'lng']: src_lon = float(bits[i]) elif cols[i].lower() in ['tz', 'timezone', 'time zone']: src_zne = float(bits[i]) cols = lines[fst_row - 1].strip().split(',') for i in range(len(cols)): if cols[i].lower() in ['df', 'dhi', 'diffuse', 'diffuse horizontal', 'diffuse horizontal irradiance']: dhi_col = i elif cols[i].lower() in ['dn', 'dni', 'beam', 'direct normal', 'direct normal irradiance']: dni_col = i elif cols[i].lower() in ['gh', 'ghi', 'global', 'global horizontal', 'global horizontal irradiance']: ghi_col = i elif cols[i].lower() in ['temp', 'tdry']: temp_col = i elif cols[i].lower() in ['wspd', 'wind speed']: wind_col = i elif cols[i].lower() in ['rain', 'rainfall', 'rainfall (mm)']: rain_col = i for i in range(fst_row, len(lines)): bits = lines[i].split(',') if self.plots['dhi']: self.ly['dhi'].append(float(bits[dhi_col])) if self.plots['dni']: self.ly['dni'].append(float(bits[dni_col])) if self.plots['ghi']: if ghi_col < 0: zenith = getZenith(i - fst_row + 1, src_lat, src_lon, src_zne) ghi_val = int(self.ly['dni'][-1] * cos(radians(zenith)) + self.ly['dhi'][-1]) self.ly['ghi'].append(ghi_val) else: self.ly['ghi'].append(float(bits[ghi_col])) if self.plots['temp']: self.ly['temp'].append(float(bits[temp_col])) if self.plots['wind'] and wind_col >= 0: self.ly['wind'].append(float(bits[wind_col])) if self.plots['rain'] and rain_col >= 0: self.ly['rain'].append(float(bits[rain_col])) for key in weathers: try: if len(self.ly[key]) == 0: self.ly.pop(key) except: pass if len(self.ly) == 0: return else: return if self.plots['wind']: if self.wind_file != '': if os.path.exists(self.wind_files + '/' + self.wind_file): tf = open(self.wind_files + '/' + self.wind_file, 'r') lines = tf.readlines() tf.close() fst_row = len(lines) - 8760 self.ly['wind'] = [] # we'll override and wind from the solar file if self.windy is None: pass else: self.ly['wind2'] = [] if self.wind_file[-4:] == '.srw': units = lines[3].strip().split(',') heights = lines[4].strip().split(',') col = -1 for j in range(len(units)): if units[j] == 'm/s': if heights[j] == '50': col = j break for i in range(fst_row, len(lines)): bits = lines[i].split(',') self.ly['wind'].append(float(bits[col])) if self.windy is None: pass else: self.ly['wind2'].append(float(bits[col]) * (self.windy[1] / self.windy[0]) ** 0.143) else: return if self.plots['rain'] and rain_col < 0: if self.rain_files != '': self.rain_file, dist, lat, lon = self.find_closest(latitude, longitude, wind=True) if os.path.exists(self.rain_files + '/' + self.rain_file): if comment != '': comment += '\n' comment += 'Rain: %s\n at %s, %s (%s Km away)' % (self.rain_file, lat, lon, '{:0,.0f}'.format(dist)) tf = open(self.rain_files + '/' + self.rain_file, 'r') lines = tf.readlines() tf.close() fst_row = len(lines) - 8760 self.ly['rain'] = [] # we'll override and wind from the solar file cols = lines[fst_row - 1].strip().split(',') for i in range(len(cols)): if cols[i].lower() in ['rain', 'rainfall', 'rainfall (mm)']: rain_col = i break for i in range(fst_row, len(lines)): bits = lines[i].split(',') self.ly['rain'].append(float(bits[rain_col])) len_x = 8760 for i in range(len_x): self.x.append(i) self.colours = {'dhi': 'r', 'dni': 'y', 'ghi': 'orange', 'rain': 'c', 'temp': 'g', 'wind': 'b', 'wind2': 'black'} self.two_axes = False self.ylabel = ['Irradiance (W/m2)', 'Irrad (W/m2)'] if (self.plots['dhi'] or self.plots['dni'] or self.plots['ghi']): if self.plots['temp']: self.two_axes = True self.ylabel2 = [['temp'], 'Temperature. (oC)', 'Temp. (oC)'] if self.plots['wind']: if self.two_axes: self.ylabel2 = [['temp', 'wind'], 'Wind (m/s) & Temp. (oC)', 'Wind & Temp.'] else: self.two_axes = True self.ylabel2 = [['wind'], 'Wind Speed (m/s)', 'Wind (m/s)'] elif self.plots['temp']: self.ylabel = ['Temperature. (oC)', 'Temp. (oC)'] if self.plots['wind']: self.two_axes = True self.ylabel2 = [['wind'], 'Wind Speed (m/s)', 'Wind (m/s)'] elif self.plots['wind']: self.ylabel = ['Wind Speed (m/s)', 'Wind (m/s)'] elif self.plots['rain']: self.ylabel = ['Rainfall (mm)', 'Rain (mm)'] self.showGraphs(self.ly, self.x, ' for location %s, %s - %s' % (latitude, longitude, self.base_year))
def showGraphs(self, ly, x, locn): def dayPlot(self, period, data, locn, per_labels=None, x_labels=None): plt.figure(period) plt.suptitle(self.hdrs[period] + locn, fontsize=16) maxy = 0 maxw = 0 if len(data[0]) > 9: p_y = 3 p_x = 4 xl = 8 yl = [0, 4, 8] yl2 = [3, 7, 11] elif len(data[0]) > 6: p_y = 3 p_x = 3 xl = 6 yl = [0, 3] yl2 = [2, 5] elif len(data[0]) > 4: p_y = 2 p_x = 3 xl = 3 yl = [0, 3] yl2 = [2, 5] elif len(data[0]) > 2: p_y = 2 p_x = 2 xl = 2 yl = [0, 2] yl2 = [1, 3] else: p_y = 1 p_x = 2 xl = 0 yl = [0, 1] yl2 = [0, 1] wi = -1 ra = -1 te = -1 i = -1 for key, value in iter(sorted(self.ly.items())): i += 1 if key == 'wind': wi = i elif key == 'temp': te = i elif key == 'rain': ra = i for p in range(len(data[0])): for i in range(len(ly)): maxy = max(maxy, max(data[i][p])) if i == wi or i == te or i == ra: maxw = max(maxw, max(data[i][p])) for p in range(len(data[0])): px = plt.subplot(p_y, p_x, p + 1) i = -1 if self.two_axes: px2 = px.twinx() for key, value in iter(sorted(self.ly.items())): i += 1 lw = 2.0 if self.two_axes and key in self.ylabel2[0]: px2.plot(x24, data[i][p], linewidth=lw, label=key, color=self.colours[key]) else: px.plot(x24, data[i][p], linewidth=lw, label=key, color=self.colours[key]) plt.title(per_labels[p]) plt.xlim([1, 24]) plt.xticks(list(range(4, 25, 4))) # px.set_xticklabels(labels]) # plt.xticks(range(0, 25, 4)) # plt.grid(axis='x') px.set_xticklabels(x_labels[1:]) px.set_ylim([0, maxy]) if self.two_axes: px2.set_ylim(0, maxw) if p in yl2: px2.set_ylabel(self.ylabel2[2]) if p >= xl: px.set_xlabel('Hour of the Day') if p in yl: px.set_ylabel(self.ylabel[1]) if self.two_axes: lines = [] for key in self.ly: lines.append(mlines.Line2D([], [], color=self.colours[key], label=key)) px.legend(handles=lines, loc='best') else: px.legend(loc='best') if self.maximise: mng = plt.get_current_fig_manager() if sys.platform == 'win32' or sys.platform == 'cygwin': if plt.get_backend() == 'TkAgg': mng.window.state('zoomed') elif plt.get_backend() == 'Qt4Agg': mng.window.showMaximized() else: mng.resize(*mng.window.maxsize()) if self.plots['block']: plt.show(block=True) else: plt.draw() papersizes = {'a0': '33.1,46.8', 'a1': '23.4,33.1', 'a2': '16.5,23.4', 'a3': '11.7,16.5', 'a4': '8.3,11.7', 'a5': '5.8,8.3', 'a6': '4.1,5.8', 'a7': '2.9,4.1', 'a8': '2,2.9', 'a9': '1.5,2', 'a10': '1,1.5', 'b0': '39.4,55.7', 'b1': '27.8,39.4', 'b2': '19.7,27.8', 'b3': '13.9,19.7', 'b4': '9.8,13.9', 'b5': '6.9,9.8', 'b6': '4.9,6.9', 'b7': '3.5,4.9', 'b8': '2.4,3.5', 'b9': '1.7,2.4', 'b10': '1.2,1.7', 'foolscap': '8.0,13.0', 'ledger': '8.5,14.0', 'legal': '8.5,14.09', 'letter': '8.5,11.0'} landscape = False papersize = '' config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) self.maximise = False seasons = [] periods = [] parents = [] try: parents = getParents(config.items('Parents')) except: pass try: self.scenarios = config.get('Files', 'scenarios') for key, value in parents: self.scenarios = self.scenarios.replace(key, value) self.scenarios = self.scenarios.replace('$USER$', getUser()) self.scenarios = self.scenarios.replace('$YEAR$', str(self.base_year)) i = self.scenarios.rfind('/') self.scenarios = self.scenarios[:i + 1] except: self.scenarios = '' try: items = config.items('Power') for item, values in items: if item[:6] == 'season': if item == 'season': continue i = int(item[6:]) - 1 if i >= len(seasons): seasons.append([]) seasons[i] = values.split(',') for j in range(1, len(seasons[i])): seasons[i][j] = int(seasons[i][j]) - 1 elif item[:6] == 'period': if item == 'period': continue i = int(item[6:]) - 1 if i >= len(periods): periods.append([]) periods[i] = values.split(',') for j in range(1, len(periods[i])): periods[i][j] = int(periods[i][j]) - 1 elif item == 'maximise': if values.lower() in ['true', 'on', 'yes']: self.maximise = True elif item == 'save_format': plt.rcParams['savefig.format'] = values elif item == 'figsize': try: papersize = papersizes[values] except: papersize = values elif item == 'orientation': if values.lower()[0] == 'l': landscape = True except: pass if papersize != '': if landscape: bit = papersize.split(',') plt.rcParams['figure.figsize'] = bit[1] + ',' + bit[0] else: plt.rcParams['figure.figsize'] = papersize if len(seasons) == 0: seasons = [['Summer', 11, 0, 1], ['Autumn', 2, 3, 4], ['Winter', 5, 6, 7], ['Spring', 8, 9, 10]] if len(periods) == 0: periods = [['Winter', 4, 5, 6, 7, 8, 9], ['Summer', 10, 11, 0, 1, 2, 3]] for i in range(len(periods)): for j in range(len(seasons)): if periods[i][0] == seasons[j][0]: periods[i][0] += '2' break mth_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] ssn_labels = [] for i in range(len(seasons)): ssn_labels.append('%s (%s-%s)' % (seasons[i][0], mth_labels[seasons[i][1]], mth_labels[seasons[i][-1]])) # ssn_labels = ['Summer (Dec, Jan-Feb)', 'Autumn (Mar-May)', 'Winter (Jun-Aug)', 'Spring(Sep-Nov)'] smp_labels = [] for i in range(len(periods)): smp_labels.append('%s (%s-%s)' % (periods[i][0], mth_labels[periods[i][1]], mth_labels[periods[i][-1]])) # smp_labels = ['Winter (May-Oct)', 'Summer (Nov-Apr)'] labels = ['0:00', '4:00', '8:00', '12:00', '16:00', '20:00', '24:00'] mth_xlabels = ['0:', '4:', '8:', '12:', '16:', '20:', '24:'] m = 0 d = 1 day_labels = [] while m < len(the_days): day_labels.append('%s %s' % (str(d), mth_labels[m])) d += 7 if d > the_days[m]: d = d - the_days[m] m += 1 lbl_font = FontProperties() lbl_font.set_size('small') x24 = [] l24 = [] m24 = [] q24 = [] s24 = [] t12 = [] for i in range(24): x24.append(i + 1) for i in range(len(self.ly)): if self.plots['total']: l24.append([]) for j in range(24): l24[i].append(0.) if self.plots['month']: m24.append([]) for m in range(12): m24[i].append([]) for j in range(24): m24[i][m].append(0.) if self.plots['season']: q24.append([]) for q in range(len(seasons)): q24[i].append([]) for j in range(24): q24[i][q].append(0.) if self.plots['period']: s24.append([]) for s in range(len(periods)): s24[i].append([]) for j in range(24): s24[i][s].append(0.) if self.plots['monthly'] or self.plots['mthavg']: t12.append([]) for m in range(14): t12[i].append(0.) the_qtrs = [] for i in range(len(seasons)): d = 0 for j in range(1, len(seasons[i])): d += the_days[seasons[i][j]] the_qtrs.append(d) the_ssns = [] for i in range(len(periods)): d = 0 for j in range(1, len(periods[i])): d += the_days[periods[i][j]] the_ssns.append(d) the_hours = [0] i = 0 for m in range(len(the_days)): i = i + the_days[m] * 24 the_hours.append(i) d = -1 for i in range(0, len(x), 24): m = 11 d += 1 while i < the_hours[m] and m > 0: m -= 1 for k in range(24): j = -1 for key, value in iter(sorted(self.ly.items())): if len(value) == 0: continue j += 1 if self.plots['total']: l24[j][k] += value[i + k] if self.plots['month']: m24[j][m][k] = m24[j][m][k] + value[i + k] if self.plots['season']: for q in range(len(seasons)): if m in seasons[q]: break q24[j][q][k] = q24[j][q][k] + value[i + k] if self.plots['period']: for s in range(len(periods)): if m in periods[s]: break s24[j][s][k] = s24[j][s][k] + value[i + k] if self.plots['monthly'] or self.plots['mthavg']: t12[j][m + 1] = t12[j][m + 1] + value[i + k] for i in range(len(ly)): for k in range(24): if self.plots['total']: l24[i][k] = l24[i][k] / 365 if self.plots['month']: for m in range(12): m24[i][m][k] = m24[i][m][k] / the_days[m] if self.plots['season']: for q in range(len(seasons)): q24[i][q][k] = q24[i][q][k] / the_qtrs[q] if self.plots['period']: for s in range(len(periods)): s24[i][s][k] = s24[i][s][k] / the_ssns[s] if self.plots['hour']: if self.plots['save_plot']: vals = ['hour'] data = [] data.append(x) fig = plt.figure('hour') plt.grid(True) hx = fig.add_subplot(111) plt.title(self.hdrs['hour'] + ' - ' + locn) maxy = 0 if self.two_axes: hx2 = hx.twinx() for key, value in iter(sorted(self.ly.items())): lw = 2.0 if self.two_axes and key in self.ylabel2[0]: hx2.plot(x, value, linewidth=lw, label=key, color=self.colours[key]) else: hx.plot(x, value, linewidth=lw, label=key, color=self.colours[key]) maxy = max(maxy, max(value)) if self.plots['save_plot']: vals.append(key) data.append(value) if self.plots['save_plot']: titl = 'hour' dialog = displaytable.Table(list(map(list, list(zip(*data)))), title=titl, fields=vals, save_folder=self.scenarios) dialog.exec_() del dialog, data, vals hx.set_ylim([0, maxy]) plt.xlim([0, len(x)]) plt.xticks(list(range(12, len(x), 168))) hx.set_xticklabels(day_labels, rotation='vertical') hx.set_xlabel('Month of the year') hx.set_ylabel(self.ylabel[0]) hx.legend(loc='best') if self.two_axes: ylim = hx2.get_ylim() hx2.set_ylim(0, ylim[1]) lines = [] for key in self.ly: lines.append(mlines.Line2D([], [], color=self.colours[key], label=key)) hx.legend(handles=lines, loc='best') hx2.set_ylabel(self.ylabel2[1]) if self.maximise: mng = plt.get_current_fig_manager() if sys.platform == 'win32' or sys.platform == 'cygwin': if plt.get_backend() == 'TkAgg': mng.window.state('zoomed') elif plt.get_backend() == 'Qt4Agg': mng.window.showMaximized() else: mng.resize(*mng.window.maxsize()) zp = ZoomPanX() if self.two_axes: f = zp.zoom_pan(hx2, base_scale=1.2) # enable scrollable zoom else: f = zp.zoom_pan(hx, base_scale=1.2) # enable scrollable zoom if self.plots['block']: plt.show(block=True) else: plt.draw() del zp if self.plots['total']: if self.plots['save_plot']: vals = ['hour of the day'] decpts = [0] data = [] data.append(x24) figt = plt.figure('total') plt.grid(True) tx = figt.add_subplot(111) plt.title(self.hdrs['total'] + ' - ' + locn) maxy = 0 i = -1 lw = 2.0 if self.two_axes: tx2 = tx.twinx() for key, value in iter(sorted(self.ly.items())): i += 1 if self.two_axes and key in self.ylabel2[0]: tx2.plot(x24, l24[i], linewidth=lw, label=key, color=self.colours[key]) else: tx.plot(x24, l24[i], linewidth=lw, label=key, color=self.colours[key]) maxy = max(maxy, max(l24[i])) if self.plots['save_plot']: vals.append(key) data.append(l24[i]) if key == 'wind': decpts.append(2) else: decpts.append(1) if self.plots['save_plot']: titl = 'total' dialog = displaytable.Table(list(map(list, list(zip(*data)))), title=titl, fields=vals, save_folder=self.scenarios, decpts=decpts) dialog.exec_() del dialog, data, vals tx.set_ylim([0, maxy]) plt.xlim([1, 24]) plt.xticks(list(range(4, 25, 4))) tx.set_xticklabels(labels[1:]) tx.set_xlabel('Hour of the Day') tx.set_ylabel(self.ylabel[0]) tx.legend(loc='best') if self.two_axes: ylim = tx2.get_ylim() tx2.set_ylim(0, ylim[1]) lines = [] for key in self.ly: lines.append(mlines.Line2D([], [], color=self.colours[key], label=key)) tx.legend(handles=lines, loc='best') tx2.set_ylabel(self.ylabel2[1]) if self.maximise: mng = plt.get_current_fig_manager() if sys.platform == 'win32' or sys.platform == 'cygwin': if plt.get_backend() == 'TkAgg': mng.window.state('zoomed') elif plt.get_backend() == 'Qt4Agg': mng.window.showMaximized() else: mng.resize(*mng.window.maxsize()) if self.plots['block']: plt.show(block=True) else: plt.draw() if self.plots['month']: dayPlot(self, 'month', m24, locn, mth_labels, mth_xlabels) if self.plots['season']: dayPlot(self, 'season', q24, locn, ssn_labels, labels) if self.plots['period']: dayPlot(self, 'period', s24, locn, smp_labels, labels) if 'pdf' in list(self.plots.keys()): if self.plots['pdf'] and self.plots['wind']: j = int(ceil(max(self.ly['wind']))) figp = plt.figure('pdf') plt.grid(True) px = figp.add_subplot(111) plt.title(self.hdrs['pdf'] + ' - ' + locn) px.hist(self.ly['wind'], j) px.set_ylabel('Number of occurences') px.set_xlabel('Wind Speed (m/s)') if self.plots['block']: plt.show(block=True) else: plt.draw() if self.plots['monthly']: if self.plots['save_plot']: vals = ['monthly'] data = [] data.append(x24[:12]) decpts = [0] figt = plt.figure('monthly') plt.grid(True) tx = figt.add_subplot(111) plt.title(self.hdrs['monthly'] + ' - ' + locn) maxy = 0 i = -1 if self.two_axes: tx2 = tx.twinx() for key, value in iter(sorted(self.ly.items())): i += 1 lw = 2.0 if self.two_axes and key in self.ylabel2[0]: tx2.step(x24[:14], t12[i], linewidth=lw, label=key, color=self.colours[key]) else: tx.step(x24[:14], t12[i], linewidth=lw, label=key, color=self.colours[key]) maxy = max(maxy, max(t12[i]) + 1) if self.plots['save_plot']: vals.append(key) data.append(t12[i][1:-1]) if key == 'wind': decpts.append(2) else: decpts.append(1) if self.plots['save_plot']: titl = 'monthly' dialog = displaytable.Table(list(map(list, list(zip(*data)))), title=titl, fields=vals, save_folder=self.scenarios, decpts=decpts) dialog.exec_() del dialog, data, vals tx.set_ylim([0, maxy]) tick_spot = [] for i in range(12): tick_spot.append(i + 1.5) tx.set_xticks(tick_spot) tx.set_xticklabels(mth_labels) plt.xlim([1, 13.0]) tx.set_xlabel('Month') tx.set_ylabel(self.ylabel[0]) tx.legend(loc='best') if self.two_axes: ylim = tx2.get_ylim() tx2.set_ylim(0, ylim[1]) lines = [] for key in self.ly: lines.append(mlines.Line2D([], [], color=self.colours[key], label=key)) tx.legend(handles=lines, loc='best') tx2.set_ylabel(self.ylabel2[1]) if self.maximise: mng = plt.get_current_fig_manager() if sys.platform == 'win32' or sys.platform == 'cygwin': if plt.get_backend() == 'TkAgg': mng.window.state('zoomed') elif plt.get_backend() == 'Qt4Agg': mng.window.showMaximized() else: mng.resize(*mng.window.maxsize()) if self.plots['block']: plt.show(block=True) else: plt.draw() if self.plots['mthavg']: if self.plots['save_plot']: vals = ['monthly_average'] data = [] data.append(x24[:12]) decpts = [0] figt = plt.figure('monthly_average') plt.grid(True) tx = figt.add_subplot(111) plt.title(self.hdrs['mthavg'] + ' - ' + locn) maxy = 0 if self.two_axes: tx2 = tx.twinx() m12 = [] for i in range(len(t12)): m12.append([]) for m in range(1, 13): m12[-1].append(t12[i][m] / the_days[m - 1] / 24.) i = -1 lw = 2.0 for key, value in iter(sorted(self.ly.items())): i += 1 if self.two_axes and key in self.ylabel2[0]: tx2.plot(x24[:12], m12[i], linewidth=lw, label=key, color=self.colours[key]) else: tx.plot(x24[:12], m12[i], linewidth=lw, label=key, color=self.colours[key]) maxy = max(maxy, max(m12[i]) + 1) if self.plots['save_plot']: vals.append(key) data.append(m12[i]) if key == 'wind': decpts.append(2) else: decpts.append(1) if self.plots['save_plot']: titl = 'mthavg' dialog = displaytable.Table(list(map(list, list(zip(*data)))), title=titl, fields=vals, save_folder=self.scenarios, decpts=decpts) dialog.exec_() del dialog, data, vals tx.set_ylim([0, maxy]) plt.xlim([1, 12]) plt.xticks(list(range(1, 13, 1))) tx.set_xticklabels(mth_labels) tx.set_xlabel('Month') tx.set_ylabel(self.ylabel[0]) tx.legend(loc='best') if self.two_axes: ylim = tx2.get_ylim() tx2.set_ylim(0, ylim[1]) lines = [] for key in self.ly: lines.append(mlines.Line2D([], [], color=self.colours[key], label=key)) tx.legend(handles=lines, loc='best') tx2.set_ylabel(self.ylabel2[1]) if self.maximise: mng = plt.get_current_fig_manager() if sys.platform == 'win32' or sys.platform == 'cygwin': if plt.get_backend() == 'TkAgg': mng.window.state('zoomed') elif plt.get_backend() == 'Qt4Agg': mng.window.showMaximized() else: mng.resize(*mng.window.maxsize()) if self.plots['block']: plt.show(block=True) else: plt.draw() if not self.plots['block']: plt.show()
def get_config(self): config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) try: self.base_year = config.get('Base', 'year') except: self.base_year = '2012' parents = [] try: parents = getParents(config.items('Parents')) except: pass try: self.sam_file = config.get('Files', 'sam_turbines') for key, value in parents: self.sam_file = self.sam_file.replace(key, value) self.sam_file = self.sam_file.replace('$USER$', getUser()) self.sam_file = self.sam_file.replace('$YEAR$', self.base_year) except: self.sam_file = '' try: self.pow_dir = config.get('Files', 'pow_files') for key, value in parents: self.pow_dir = self.pow_dir.replace(key, value) self.pow_dir = self.pow_dir.replace('$USER$', getUser()) self.pow_dir = self.pow_dir.replace('$YEAR$', self.base_year) except: self.pow_dir = '' try: self.map = config.get('Map', 'map_choice') except: self.map = '' self.upper_left = [0., 0.] self.lower_right = [-90., 180.] try: upper_left = config.get('Map', 'upper_left' + self.map).split(',') self.upper_left[0] = float(upper_left[0].strip()) self.upper_left[1] = float(upper_left[1].strip()) lower_right = config.get('Map', 'lower_right' + self.map).split(',') self.lower_right[0] = float(lower_right[0].strip()) self.lower_right[1] = float(lower_right[1].strip()) except: try: lower_left = config.get('Map', 'lower_left' + self.map).split(',') upper_right = config.get('Map', 'upper_right' + self.map).split(',') self.upper_left[0] = float(upper_right[0].strip()) self.upper_left[1] = float(lower_left[1].strip()) self.lower_right[0] = float(lower_left[0].strip()) self.lower_right[1] = float(upper_right[1].strip()) except: pass self.technologies = [''] self.areas = {} try: technologies = config.get('Power', 'technologies') for item in technologies.split(): itm = techClean(item) self.technologies.append(itm) try: self.areas[itm] = float(config.get(itm, 'area')) except: self.areas[itm] = 0. except: pass self.cst_tshours = 0 try: self.cst_tshours = float(config.get('CST', 'tshours')) except: pass self.st_tshours = 0 try: self.st_tshours = float(config.get('Solar Thermal', 'tshours')) except: pass
def get_config(self): config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) try: self.base_year = config.get('Base', 'year') except: self.base_year = '2012' parents = [] try: parents = getParents(config.items('Parents')) except: pass try: self.kml_file = config.get('Files', 'grid_zones') for key, value in parents: self.kml_file = self.kml_file.replace(key, value) self.kml_file = self.kml_file.replace('$USER$', getUser()) self.kml_file = self.kml_file.replace('$YEAR$', self.base_year) except: self.kml_file = '' self.colour = '#00FF00' try: mapc = config.get('Map', 'map_choice') except: mapc = '' try: self.colour = config.get('Colors', 'grid_zones') except: pass if mapc != '': try: self.colour = config.get('Colors' + mapc, 'grid_zones') except: pass upper_left = [0., 0.] lower_right = [-90., 180.] try: upper_left = config.get('Map', 'upper_left' + mapc).split(',') upper_left[0] = float(upper_left[0].strip()) upper_left[1] = float(upper_left[1].strip()) lower_right = config.get('Map', 'lower_right' + mapc).split(',') lower_right[0] = float(lower_right[0].strip()) lower_right[1] = float(lower_right[1].strip()) except: try: lower_left = config.get('Map', 'lower_left' + mapc).split(',') upper_right = config.get('Map', 'upper_right' + mapc).split(',') upper_left[0] = float(upper_right[0].strip()) upper_left[1] = float(lower_left[1].strip()) lower_right[0] = float(lower_left[0].strip()) lower_right[1] = float(upper_right[1].strip()) except: pass self.map_polygon = [ upper_left, [upper_left[0], lower_right[1]], lower_right, [lower_right[0], upper_left[1]], upper_left ]
def get_config(self): config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) try: self.base_year = config.get('Base', 'year') except: self.base_year = '2012' parents = [] try: parents = getParents(aparents=config.items('Parents')) except: pass try: self.kml_file = config.get('Files', 'grid_network') for key, value in parents: self.kml_file = self.kml_file.replace(key, value) self.kml_file = self.kml_file.replace('$USER$', getUser()) self.kml_file = self.kml_file.replace('$YEAR$', self.base_year) except: self.kml_file = '' try: self.kml_file2 = config.get('Files', 'grid_network2') for key, value in parents: self.kml_file2 = self.kml_file2.replace(key, value) self.kml_file2 = self.kml_file2.replace('$USER$', getUser()) self.kml_file2 = self.kml_file2.replace('$YEAR$', self.base_year) except: self.kml_file2 = '' try: mapc = config.get('Map', 'map_choice') except: mapc = '' self.colors = {} self.colors['grid_boundary'] = 'blue' self.grid2_colors = { '500': '#%02x%02x%02x' % (255, 237, 0), '400': '#%02x%02x%02x' % (242, 170, 45), '330': '#%02x%02x%02x' % (242, 170, 45), '275': '#%02x%02x%02x' % (249, 13, 227), '220': '#%02x%02x%02x' % (0, 0, 255), '132': '#%02x%02x%02x' % (228, 2, 45), '110': '#%02x%02x%02x' % (228, 2, 45), '88': '#%02x%02x%02x' % (119, 65, 16), '66': '#%02x%02x%02x' % (119, 65, 16), 'dc': '#%02x%02x%02x' % (86, 154, 105) } try: colours = config.items('Colors') for item, colour in colours: if item in ['grid_boundary', 'grid_trace']: self.colors[item] = colour elif item[:5] == 'grid_': self.colors[item[5:]] = colour elif item[:6] == 'grid2_': self.grid2_colors[item[6:]] = colour except: pass if mapc != '': try: colours = config.items('Colors' + mapc) for item, colour in colours: if item in ['grid_boundary', 'grid_trace']: self.colors[item] = colour elif item[:5] == 'grid_': self.colors[item[5:]] = colour elif item[:6] == 'grid2_': self.grid2_colors[item[6:]] = colour except: pass upper_left = [0., 0.] lower_right = [-90., 180.] try: upper_left = config.get('Map', 'upper_left' + mapc).split(',') upper_left[0] = float(upper_left[0].strip()) upper_left[1] = float(upper_left[1].strip()) lower_right = config.get('Map', 'lower_right' + mapc).split(',') lower_right[0] = float(lower_right[0].strip()) lower_right[1] = float(lower_right[1].strip()) except: try: lower_left = config.get('Map', 'lower_left' + mapc).split(',') upper_right = config.get('Map', 'upper_right' + mapc).split(',') upper_left[0] = float(upper_right[0].strip()) upper_left[1] = float(lower_left[1].strip()) lower_right[0] = float(lower_left[0].strip()) lower_right[1] = float(upper_right[1].strip()) except: pass self.map_polygon = [ upper_left, [upper_left[0], lower_right[1]], lower_right, [lower_right[0], upper_left[1]], upper_left ] self.default_length = -1 try: trace_existing = config.get('View', 'trace_existing') if trace_existing.lower() in ['true', 'yes', 'on']: self.default_length = 0 except: try: trace_existing = config.get('Grid', 'trace_existing') if trace_existing.lower() in ['true', 'yes', 'on']: self.default_length = 0 except: pass self.line_costs = {} try: line_costs = config.get('Grid', 'line_costs') line_costs = line_costs.replace('(', '') line_costs = line_costs.replace(')', '') line_costs = line_costs.split(',') for i in range(len(line_costs)): line = line_costs[i].split('=') if line[1].strip()[-1] == 'K': self.line_costs[line[0].strip()] = float( line[1].strip()[:-1]) * pow(10, 3) elif line[1].strip()[-1] == 'M': self.line_costs[line[0].strip()] = float( line[1].strip()[:-1]) * pow(10, 6) else: self.line_costs[line[0].strip()] = float( line[1].strip()[:-1]) except: pass self.substation_costs = {} try: substation_costs = config.get('Grid', 'substation_costs') substation_costs = substation_costs.replace('(', '') substation_costs = substation_costs.replace(')', '') substation_costs = substation_costs.split(',') for i in range(len(substation_costs)): line = substation_costs[i].split('=') if line[1].strip()[-1] == 'K': self.substation_costs[line[0].strip()] = float( line[1].strip()[:-1]) * pow(10, 3) elif line[1].strip()[-1] == 'M': self.substation_costs[line[0].strip()] = float( line[1].strip()[:-1]) * pow(10, 6) else: self.substation_costs[line[0].strip()] = float( line[1].strip()[:-1]) except: pass try: s_lines = config.get('Grid', 's_lines') s_lines = s_lines.strip() self.s_line_table = self.decode(s_lines) except: self.s_line_table = [] try: d_lines = config.get('Grid', 'd_lines') d_lines = d_lines.strip() self.d_line_table = self.decode(d_lines) except: self.d_line_table = [] self.dummy_fix = False try: dummy_fix = config.get('Grid', 'dummy_fix') if dummy_fix.lower() in ['true', 'yes', 'on']: self.dummy_fix = True except: pass
class SSCAPI: global c_number config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) try: base_year = config.get('Base', 'year') except: base_year = '2014' parents = [] try: parents = getParents(config.items('Parents')) except: pass try: sam_sdk = config.get('Files', 'sam_sdk') for key, value in parents: sam_sdk = sam_sdk.replace(key, value) sam_sdk = sam_sdk.replace('$USER$', getUser()) sam_sdk = sam_sdk.replace('$YEAR$', base_year) except: sam_sdk = '' if sys.platform == 'win32' or sys.platform == 'cygwin': sam_sdk = sys.argv[0][:sys.argv[0].rfind('\\') + 1] + sam_sdk + '\\win' if 8 * struct.calcsize("P") == 64: sam_sdk += '64' else: sam_sdk += '32' os.environ["PATH"] += os.pathsep + sam_sdk _dll = CDLL(sam_sdk + "\\ssc.dll") # return _dll elif sys.platform == 'darwin': _dll = CDLL(sam_sdk + "/osx64/ssc.dylib") # return _dll elif sys.platform == 'linux2' or sys.platform == 'linux': # _dll = CDLL("../../linux64/ssc.so") _dll = CDLL(sam_sdk + "/linux64/ssc.so") # return _dll else: print("Platform not supported ", sys.platform) if _dll.ssc_version( ) <= 209: # need to check SAM version and if ealier than 210 use c_float c_number = c_float @staticmethod def ssc_version(): SSCAPI._dll.ssc_version.restype = c_int return SSCAPI._dll.ssc_version() @staticmethod def ssc_build_info(): SSCAPI._dll.ssc_build_info.restype = c_char_p return SSCAPI._dll.ssc_build_info() @staticmethod def ssc_data_create(): SSCAPI._dll.ssc_data_create.restype = c_void_p return SSCAPI._dll.ssc_data_create() @staticmethod def ssc_data_free(p_data): SSCAPI._dll.ssc_data_free(c_void_p(p_data)) @staticmethod def ssc_data_clear(p_data): SSCAPI._dll.ssc_data_clear(c_void_p(p_data)) @staticmethod def ssc_data_unassign(p_data, name): SSCAPI._dll.ssc_data_unassign(c_void_p(p_data), c_char_p(name)) @staticmethod def ssc_data_query(p_data, name): SSCAPI._dll.ssc_data_query.restype = c_int return SSCAPI._dll.ssc_data_query(c_void_p(p_data), c_char_p(name)) @staticmethod def ssc_data_first(p_data): SSCAPI._dll.ssc_data_first.restype = c_char_p return SSCAPI._dll.ssc_data_first(c_void_p(p_data)) @staticmethod def ssc_data_next(p_data): SSCAPI._dll.ssc_data_next.restype = c_char_p return SSCAPI._dll.ssc_data_next(c_void_p(p_data)) @staticmethod def ssc_data_set_string(p_data, name, value): SSCAPI._dll.ssc_data_set_string(c_void_p(p_data), c_char_p(name), c_char_p(value)) @staticmethod def ssc_data_set_number(p_data, name, value): SSCAPI._dll.ssc_data_set_number(c_void_p(p_data), c_char_p(name), c_number(value)) @staticmethod def ssc_data_set_array(p_data, name, parr): count = len(parr) arr = (c_number * count)() for i in range(count): arr[i] = c_number(parr[i]) return SSCAPI._dll.ssc_data_set_array(c_void_p(p_data), c_char_p(name), pointer(arr), c_int(count)) @staticmethod def ssc_data_set_matrix(p_data, name, mat): nrows = len(mat) ncols = len(mat[0]) size = nrows * ncols arr = (c_number * size)() idx = 0 for r in range(nrows): for c in range(ncols): arr[idx] = c_number(mat[r][c]) idx = idx + 1 return SSCAPI._dll.ssc_data_set_matrix(c_void_p(p_data), c_char_p(name), pointer(arr), c_int(nrows), c_int(ncols)) @staticmethod def ssc_data_set_table(p_data, name, table): SSCAPI._dll.ssc_data_set_table(c_void_p(p_data), c_char_p(name), c_void_p(table)) @staticmethod def ssc_data_get_string(p_data, name): SSCAPI._dll.ssc_data_get_string.restype = c_char_p return SSCAPI._dll.ssc_data_get_string(c_void_p(p_data), c_char_p(name)) @staticmethod def ssc_data_get_number(p_data, name): val = c_number(0) SSCAPI._dll.ssc_data_get_number(c_void_p(p_data), c_char_p(name), byref(val)) return val.value @staticmethod def ssc_data_get_array(p_data, name): count = c_int() SSCAPI._dll.ssc_data_get_array.restype = POINTER(c_number) parr = SSCAPI._dll.ssc_data_get_array(c_void_p(p_data), c_char_p(name), byref(count)) arr = [] for i in range(count.value): arr.append(float(parr[i])) return arr @staticmethod def ssc_data_get_matrix(p_data, name): nrows = c_int() ncols = c_int() SSCAPI._dll.ssc_data_get_matrix.restype = POINTER(c_number) parr = SSCAPI._dll.ssc_data_get_matrix(c_void_p(p_data), c_char_p(name), byref(nrows), byref(ncols)) idx = 0 mat = [] for r in range(nrows.value): row = [] for c in range(ncols.value): row.append(float(parr[idx])) idx = idx + 1 mat.append(row) return mat @staticmethod def ssc_data_get_table(p_data, name): SSCAPI._dll.ssc_data_get_table.restype = c_void_p return SSCAPI._dll.ssc_data_get_table(c_void_p(p_data), c_char_p(name)) @staticmethod def ssc_module_entry(index): SSCAPI._dll.ssc_module_entry.restype = c_void_p return SSCAPI._dll.ssc_module_entry(c_int(index)) @staticmethod def ssc_entry_name(p_entry): SSCAPI._dll.ssc_entry_name.restype = c_char_p return SSCAPI._dll.ssc_entry_name(c_void_p(p_entry)) @staticmethod def ssc_entry_description(p_entry): SSCAPI._dll.ssc_entry_description.restype = c_char_p return SSCAPI._dll.ssc_entry_description(c_void_p(p_entry)) @staticmethod def ssc_entry_version(p_entry): SSCAPI._dll.ssc_entry_version.restype = c_int return SSCAPI._dll.ssc_entry_version(c_void_p(p_entry)) @staticmethod def ssc_module_create(name): SSCAPI._dll.ssc_module_create.restype = c_void_p return SSCAPI._dll.ssc_module_create(c_char_p(name)) @staticmethod def ssc_module_free(p_mod): SSCAPI._dll.ssc_module_free(c_void_p(p_mod)) @staticmethod def ssc_module_var_info(p_mod, index): SSCAPI._dll.ssc_module_var_info.restype = c_void_p return SSCAPI._dll.ssc_module_var_info(c_void_p(p_mod), c_int(index)) @staticmethod def ssc_info_var_type(p_inf): return SSCAPI._dll.ssc_info_var_type(c_void_p(p_inf)) @staticmethod def ssc_info_data_type(p_inf): return SSCAPI._dll.ssc_info_data_type(c_void_p(p_inf)) @staticmethod def ssc_info_name(p_inf): SSCAPI._dll.ssc_info_name.restype = c_char_p return SSCAPI._dll.ssc_info_name(c_void_p(p_inf)) @staticmethod def ssc_info_label(p_inf): SSCAPI._dll.ssc_info_label.restype = c_char_p return SSCAPI._dll.ssc_info_label(c_void_p(p_inf)) @staticmethod def ssc_info_units(p_inf): SSCAPI._dll.ssc_info_units.restype = c_char_p return SSCAPI._dll.ssc_info_units(c_void_p(p_inf)) @staticmethod def ssc_info_meta(p_inf): SSCAPI._dll.ssc_info_meta.restype = c_char_p return SSCAPI._dll.ssc_info_meta(c_void_p(p_inf)) @staticmethod def ssc_info_group(p_inf): SSCAPI._dll.ssc_info_group.restype = c_char_p return SSCAPI._dll.ssc_info_group(c_void_p(p_inf)) @staticmethod def ssc_info_uihint(p_inf): SSCAPI._dll.ssc_info_uihint.restype = c_char_p return SSCAPI._dll.ssc_info_uihint(c_void_p(p_inf)) # start of added by AK 2015-07-01 @staticmethod def ssc_info_required(p_inf): SSCAPI._dll.ssc_info_required.restype = c_char_p return SSCAPI._dll.ssc_info_required(c_void_p(p_inf)) @staticmethod def ssc_info_constraints(p_inf): SSCAPI._dll.ssc_info_constraints.restype = c_char_p return SSCAPI._dll.ssc_info_constraints(c_void_p(p_inf)) # end of added by AK 2015-07-01 @staticmethod def ssc_module_exec(p_mod, p_data): SSCAPI._dll.ssc_module_exec.restype = c_int return SSCAPI._dll.ssc_module_exec(c_void_p(p_mod), c_void_p(p_data)) @staticmethod def ssc_module_exec_set_print(set_print): return SSCAPI._dll.ssc_module_exec_set_print(c_int(set_print)) @staticmethod def ssc_module_log(p_mod, index): type = c_int() time = c_float() SSCAPI._dll.ssc_module_log.restype = c_char_p return SSCAPI._dll.ssc_module_log(c_void_p(p_mod), c_int(index), byref(type), byref(time))
def get_config(self): config = configparser.RawConfigParser() if __name__ == '__main__': for i in range(1, len(sys.argv)): if sys.argv[i][-4:] == '.ini': config_file = sys.argv[i] break else: if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) try: self.base_year = config.get('Base', 'year') except: self.base_year = '2012' parents = [] try: parents = getParents(config.items('Parents')) except: pass try: self.sam_file = config.get('Files', 'sam_turbines') for key, value in parents: self.sam_file = self.sam_file.replace(key, value) self.sam_file = self.sam_file.replace('$USER$', getUser()) self.sam_file = self.sam_file.replace('$YEAR$', self.base_year) except: self.sam_file = '' try: self.pow_dir = config.get('Files', 'pow_files') for key, value in parents: self.pow_dir = self.pow_dir.replace(key, value) self.pow_dir = self.pow_dir.replace('$USER$', getUser()) self.pow_dir = self.pow_dir.replace('$YEAR$', self.base_year) except: self.pow_dir = '' self.fac_files = [] try: fac_file = config.get('Files', 'grid_stations') for key, value in parents: fac_file = fac_file.replace(key, value) fac_file = fac_file.replace('$USER$', getUser()) fac_file = fac_file.replace('$YEAR$', self.base_year) self.fac_files.append(fac_file) except: pass if self.stations2: try: fac_file = config.get('Files', 'grid_stations2') for key, value in parents: fac_file = fac_file.replace(key, value) fac_file = fac_file.replace('$USER$', getUser()) fac_file = fac_file.replace('$YEAR$', self.base_year) self.fac_files.append(fac_file) except: pass self.ignore_deleted = True try: if config.get('Grid', 'ignore_deleted_existing').lower() in [ 'false', 'off', 'no' ]: self.ignore_deleted = False except: pass self.technologies = [''] self.areas = {} try: technologies = config.get('Power', 'technologies') for item in technologies.split(): itm = techClean(item) self.technologies.append(itm) try: self.areas[itm] = float(config.get(itm, 'area')) except: self.areas[itm] = 0. except: pass try: technologies = config.get('Power', 'fossil_technologies') technologies = technologies.split() for item in technologies: itm = techClean(item) try: self.areas[itm] = float(config.get(itm, 'area')) except: self.areas[itm] = 0. except: pass try: mapc = config.get('Map', 'map_choice') except: mapc = '' upper_left = [0., 0.] lower_right = [-90., 180.] try: upper_left = config.get('Map', 'upper_left' + mapc).split(',') upper_left[0] = float(upper_left[0].strip()) upper_left[1] = float(upper_left[1].strip()) lower_right = config.get('Map', 'lower_right' + mapc).split(',') lower_right[0] = float(lower_right[0].strip()) lower_right[1] = float(lower_right[1].strip()) except: try: lower_left = config.get('Map', 'lower_left' + mapc).split(',') upper_right = config.get('Map', 'upper_right' + mapc).split(',') upper_left[0] = float(upper_right[0].strip()) upper_left[1] = float(lower_left[1].strip()) lower_right[0] = float(lower_left[0].strip()) lower_right[1] = float(upper_right[1].strip()) except: pass self.map_polygon = [ upper_left, [upper_left[0], lower_right[1]], lower_right, [lower_right[0], upper_left[1]], upper_left ]
def __init__(self, help='help.html'): super(FlexiPlot, self).__init__() self.help = help config = configparser.RawConfigParser() if len(sys.argv) > 1: self.config_file = sys.argv[1] else: self.config_file = getModelFile('flexiplot.ini') config.read(self.config_file) if not config.has_section('Flexiplot'): # new file set windows section self.restorewindows = True else: self.restorewindows = False try: rw = config.get('Windows', 'restorewindows') if rw.lower() in ['true', 'yes', 'on']: self.restorewindows = True except: pass parents = [] self.colours = {} try: parents = getParents(config.items('Parents')) except: pass try: base_year = config.get('Base', 'year') except: base_year = '2012' try: scenario_prefix = config.get('Files', 'scenario_prefix') except: scenario_prefix = '' try: self.scenarios = config.get('Files', 'scenarios') if scenario_prefix != '': self.scenarios += '/' + scenario_prefix for key, value in parents: self.scenarios = self.scenarios.replace(key, value) self.scenarios = self.scenarios.replace('$USER$', getUser()) self.scenarios = self.scenarios.replace('$YEAR$', base_year) self.scenarios = self.scenarios[:self.scenarios.rfind('/') + 1] if self.scenarios[:3] == '../': ups = self.scenarios.split('../') me = os.getcwd().split(os.sep) me = me[:-(len(ups) - 1)] me.append(ups[-1]) self.scenarios = '/'.join(me) except: self.scenarios = '' try: colours = config.items('Plot Colors') for item, colour in colours: itm = item.replace('_', ' ') self.colours[itm] = colour except: pass ifile = '' isheet = '' columns = [] self.setup = [False, False] self.details = True self.book = None self.rows = None self.leapyear = False iper = '<none>' imax = 0 self.alpha = 0.25 self.title_font = 'size=x-large' #'size=15' self.label_font = '' #'size=x-large' self.legend_font = '' #'size=x-large' self.ticks_font = '' #'size=large' self.constrained_layout = False self.series = [] self.xvalues = [] self.palette = True self.history = None self.max_files = 10 ifiles = self.get_flex_config() if len(ifiles) > 0: if self.history is None: self.history = sorted(ifiles.keys(), reverse=True) while ifile == '' and len(self.history) > 0: try: ifile = ifiles[self.history[0]] except: self.history.pop(0) matplotlib.rcParams['savefig.directory'] = os.getcwd() self.grid = QtWidgets.QGridLayout() self.updated = False self.colours_updated = False self.log = QtWidgets.QLabel('') rw = 0 self.grid.addWidget(QtWidgets.QLabel('Recent Files:'), rw, 0) self.files = QtWidgets.QComboBox() if ifile != '': self.popfileslist(ifile, ifiles) self.grid.addWidget(self.files, rw, 1, 1, 5) rw += 1 self.grid.addWidget(QtWidgets.QLabel('File:'), rw, 0) self.file = ClickableQLabel() self.file.setStyleSheet( "background-color: white; border: 1px inset grey; min-height: 22px; border-radius: 4px;" ) self.file.setText('') self.grid.addWidget(self.file, rw, 1, 1, 5) rw += 1 self.grid.addWidget(QtWidgets.QLabel('Sheet:'), rw, 0) self.sheet = QtWidgets.QComboBox() self.grid.addWidget(self.sheet, rw, 1, 1, 2) rw += 1 self.grid.addWidget(QtWidgets.QLabel('Title:'), rw, 0) self.title = QtWidgets.QLineEdit('') self.grid.addWidget(self.title, rw, 1, 1, 2) rw += 1 self.grid.addWidget(QtWidgets.QLabel('Series:'), rw, 0) self.seriesi = CustomCombo() for series in self.series: self.seriesi.addItem(series) self.seriesi.setEditable(True) self.grid.addWidget(self.seriesi, rw, 1, 1, 2) self.grid.addWidget( QtWidgets.QLabel( '(Cells for Series Categories; A1:B2 or r1,c1,r2,c2 format)'), rw, 3, 1, 2) rw += 1 self.grid.addWidget(QtWidgets.QLabel('Series Label:'), rw, 0) self.ylabel = QtWidgets.QLineEdit('') self.grid.addWidget(self.ylabel, rw, 1, 1, 2) rw += 1 self.grid.addWidget(QtWidgets.QLabel('X Values:'), rw, 0) self.xvaluesi = CustomCombo() for xvalues in self.xvalues: self.xvaluesi.addItem(xvalues) self.xvaluesi.setEditable(True) self.grid.addWidget(self.xvaluesi, rw, 1, 1, 2) self.grid.addWidget( QtWidgets.QLabel( '(Cells for X values; A1:B2 or r1,c1,r2,c2 format)'), rw, 3, 1, 2) rw += 1 self.grid.addWidget(QtWidgets.QLabel('X Label:'), rw, 0) self.xlabel = QtWidgets.QLineEdit('') self.grid.addWidget(self.xlabel, rw, 1, 1, 2) rw += 1 self.grid.addWidget(QtWidgets.QLabel('Maximum:'), rw, 0) self.maxSpin = QtWidgets.QSpinBox() self.maxSpin.setRange(0, 100000) self.maxSpin.setSingleStep(500) self.grid.addWidget(self.maxSpin, rw, 1) self.grid.addWidget( QtWidgets.QLabel( '(Handy if you want to produce a series of plots)'), rw, 3, 1, 3) rw += 1 self.grid.addWidget(QtWidgets.QLabel('Type of Plot:'), rw, 0) plots = ['Bar Chart', 'Cumulative', 'Linegraph', 'Step Plot'] self.plottype = QtWidgets.QComboBox() for plot in plots: self.plottype.addItem(plot) self.grid.addWidget(self.plottype, rw, 1) #, 1, 2) self.grid.addWidget( QtWidgets.QLabel('(Type of plot - stacked except for Linegraph)'), rw, 3, 1, 3) rw += 1 self.grid.addWidget(QtWidgets.QLabel('Percentage:'), rw, 0) self.percentage = QtWidgets.QCheckBox() self.percentage.setCheckState(QtCore.Qt.Unchecked) self.grid.addWidget(self.percentage, rw, 1) #, 1, 2) self.grid.addWidget( QtWidgets.QLabel('(Check for percentage distribution)'), rw, 3, 1, 3) rw += 1 self.grid.addWidget(QtWidgets.QLabel('Show Grid:'), rw, 0) grids = ['Both', 'Horizontal', 'Vertical', 'None'] self.gridtype = QtWidgets.QComboBox() for grid in grids: self.gridtype.addItem(grid) self.grid.addWidget(self.gridtype, rw, 1) #, 1, 2) self.grid.addWidget(QtWidgets.QLabel('(Choose gridlines)'), rw, 3, 1, 3) rw += 1 self.grid.addWidget( QtWidgets.QLabel('Column Order:\n(move to right\nto exclude)'), rw, 0) self.order = ListWidget(self) self.grid.addWidget(self.order, rw, 1, 1, 2) self.ignore = ListWidget(self) self.grid.addWidget(self.ignore, rw, 3, 1, 2) self.grid.addWidget(QtWidgets.QLabel(' '), rw, 5) if ifile != '': self.get_file_config(self.history[0]) self.files.currentIndexChanged.connect(self.filesChanged) self.file.clicked.connect(self.fileChanged) # self.seriesi.textChanged.connect(self.seriesChanged) self.seriesi.activated[str].connect(self.seriesChanged) self.seriesi.currentIndexChanged.connect(self.seriesChanged) self.xvaluesi.activated[str].connect(self.xvaluesChanged) self.xvaluesi.currentIndexChanged.connect(self.xvaluesChanged) # self.xvalues.textChanged.connect(self.somethingChanged) self.files.currentIndexChanged.connect(self.seriesChanged) self.sheet.currentIndexChanged.connect(self.sheetChanged) self.title.textChanged.connect(self.somethingChanged) self.maxSpin.valueChanged.connect(self.somethingChanged) self.plottype.currentIndexChanged.connect(self.somethingChanged) self.gridtype.currentIndexChanged.connect(self.somethingChanged) self.percentage.stateChanged.connect(self.somethingChanged) self.order.itemSelectionChanged.connect(self.somethingChanged) rw += 1 msg_palette = QtGui.QPalette() msg_palette.setColor(QtGui.QPalette.Foreground, QtCore.Qt.red) self.log.setPalette(msg_palette) self.grid.addWidget(self.log, rw, 1, 1, 4) rw += 1 done = QtWidgets.QPushButton('Done', self) self.grid.addWidget(done, rw, 0) done.clicked.connect(self.doneClicked) QtWidgets.QShortcut(QtGui.QKeySequence('q'), self, self.doneClicked) pp = QtWidgets.QPushButton('Plot', self) self.grid.addWidget(pp, rw, 1) pp.clicked.connect(self.ppClicked) QtWidgets.QShortcut(QtGui.QKeySequence('p'), self, self.ppClicked) cb = QtWidgets.QPushButton('Colours', self) self.grid.addWidget(cb, rw, 2) cb.clicked.connect(self.editColours) ep = QtWidgets.QPushButton('Preferences', self) self.grid.addWidget(ep, rw, 3) ep.clicked.connect(self.editIniFile) help = QtWidgets.QPushButton('Help', self) self.grid.addWidget(help, rw, 4) help.clicked.connect(self.helpClicked) QtWidgets.QShortcut(QtGui.QKeySequence('F1'), self, self.helpClicked) frame = QtWidgets.QFrame() frame.setLayout(self.grid) self.scroll = QtWidgets.QScrollArea() self.scroll.setWidgetResizable(True) self.scroll.setWidget(frame) self.layout = QtWidgets.QVBoxLayout(self) self.layout.addWidget(self.scroll) self.setWindowTitle('SIREN - flexiplot (' + fileVersion() + ') - FlexiPlot') self.setWindowIcon(QtGui.QIcon('sen_icon32.ico')) if self.restorewindows: try: rw = config.get('Windows', 'flexiplot_size').split(',') self.resize(int(rw[0]), int(rw[1])) mp = config.get('Windows', 'flexiplot_pos').split(',') self.move(int(mp[0]), int(mp[1])) except: pass else: self.center() self.resize(int(self.sizeHint().width() * 1.2), int(self.sizeHint().height() * 1.2)) self.log.setText('Preferences file: ' + self.config_file) self.show()
def initUI(self): config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) try: self.base_year = config.get('Base', 'year') except: self.base_year = '2012' self.parents = [] try: self.parents = getParents(config.items('Parents')) except: pass try: self.solarfiles = config.get('Files', 'solar_files') for key, value in self.parents: self.solarfiles = self.solarfiles.replace(key, value) self.solarfiles = self.solarfiles.replace('$USER$', getUser()) self.solarfiles = self.solarfiles.replace('$YEAR$', self.base_year) except: self.solarfiles = '' try: self.solarindex = config.get('Files', 'solar_index') for key, value in self.parents: self.solarindex = self.solarindex.replace(key, value) self.solarindex = self.solarindex.replace('$USER$', getUser()) self.solarindex = self.solarindex.replace('$YEAR$', self.base_year) except: self.solarindex = '' if self.solarindex == '': self.solarindex = self.solarfiles + '/solar_index.xls' try: self.windfiles = config.get('Files', 'wind_files') for key, value in self.parents: self.windfiles = self.windfiles.replace(key, value) self.windfiles = self.windfiles.replace('$USER$', getUser()) self.windfiles = self.windfiles.replace('$YEAR$', self.base_year) except: self.windfiles = '' try: self.windindex = config.get('Files', 'wind_index') for key, value in self.parents: self.windindex = self.windindex.replace(key, value) self.windindex = self.windindex.replace('$USER$', getUser()) self.windindex = self.windindex.replace('$YEAR$', self.base_year) except: self.windindex = '' if self.windindex == '': self.windindex = self.windfiles + '/wind_index.xls' self.grid = QtWidgets.QGridLayout() self.grid.addWidget(QtWidgets.QLabel('Solar Folder:'), 1, 0) self.ssource = ClickableQLabel() self.ssource.setText(self.solarfiles) self.ssource.setStyleSheet("background-color: white; border: 1px inset grey; min-height: 22px; border-radius: 4px;") self.ssource.clicked.connect(self.sdirChanged) self.grid.addWidget(self.ssource, 1, 1, 1, 4) self.grid.addWidget(QtWidgets.QLabel('Solar Index:'), 2, 0) self.starget = ClickableQLabel() self.starget.setText(self.solarindex) self.starget.setStyleSheet("background-color: white; border: 1px inset grey; min-height: 22px; border-radius: 4px;") self.starget.clicked.connect(self.stgtChanged) self.grid.addWidget(self.starget, 2, 1, 1, 4) self.grid.addWidget(QtWidgets.QLabel('Wind Folder:'), 3, 0) self.wsource = ClickableQLabel() self.wsource.setText(self.windfiles) self.wsource.setStyleSheet("background-color: white; border: 1px inset grey; min-height: 22px; border-radius: 4px;") self.wsource.clicked.connect(self.wdirChanged) self.grid.addWidget(self.wsource, 3, 1, 1, 4) self.grid.addWidget(QtWidgets.QLabel('Wind Index:'), 4, 0) self.wtarget = ClickableQLabel() self.wtarget.setText(self.windindex) self.wtarget.setStyleSheet("background-color: white; border: 1px inset grey; min-height: 22px; border-radius: 4px;") self.wtarget.clicked.connect(self.wtgtChanged) self.grid.addWidget(self.wtarget, 4, 1, 1, 4) self.grid.addWidget(QtWidgets.QLabel('Properties:'), 5, 0) self.properties = QtWidgets.QLineEdit() self.properties.setReadOnly(True) self.grid.addWidget(self.properties, 5, 1, 1, 4) self.log = QtWidgets.QLabel(' ') self.grid.addWidget(self.log, 6, 1, 1, 4) quit = QtWidgets.QPushButton('Quit', self) self.grid.addWidget(quit, 7, 0) quit.clicked.connect(self.quitClicked) QtWidgets.QShortcut(QtGui.QKeySequence('q'), self, self.quitClicked) dosolar = QtWidgets.QPushButton('Produce Solar Index', self) wdth = dosolar.fontMetrics().boundingRect(dosolar.text()).width() + 9 dosolar.setMaximumWidth(wdth) self.grid.addWidget(dosolar, 7, 1) dosolar.clicked.connect(self.dosolarClicked) dowind = QtWidgets.QPushButton('Produce Wind Index', self) dowind.setMaximumWidth(wdth) self.grid.addWidget(dowind, 7, 2) dowind.clicked.connect(self.dowindClicked) help = QtWidgets.QPushButton('Help', self) help.setMaximumWidth(wdth) self.grid.addWidget(help, 7, 3) help.clicked.connect(self.helpClicked) QtWidgets.QShortcut(QtGui.QKeySequence('F1'), self, self.helpClicked) self.grid.setColumnStretch(3, 5) frame = QtWidgets.QFrame() frame.setLayout(self.grid) self.scroll = QtWidgets.QScrollArea() self.scroll.setWidgetResizable(True) self.scroll.setWidget(frame) self.layout = QtWidgets.QVBoxLayout(self) self.layout.addWidget(self.scroll) self.setWindowTitle('SIREN - indexweather (' + fileVersion() + ') - Make resource grid file') self.setWindowIcon(QtGui.QIcon('sen_icon32.ico')) self.center() self.resize(int(self.sizeHint().width()* 1.07), int(self.sizeHint().height() * 1.07)) self.show()
def initUI(self): config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) try: self.base_year = config.get('Base', 'year') except: self.base_year = '2012' self.yrndx = -1 this_year = time.strftime('%Y') try: self.years = [] years = config.get('Base', 'years') bits = years.split(',') for i in range(len(bits)): rngs = bits[i].split('-') if len(rngs) > 1: for j in range(int(rngs[0].strip()), int(rngs[1].strip()) + 1): if str(j) == self.base_year: self.yrndx = len(self.years) self.years.append(str(j)) else: if rngs[0].strip() == self.base_year: self.yrndx = len(self.years) self.years.append(rngs[0].strip()) if this_year not in self.years: self.years.append(this_year) except: if self.base_year != this_year: self.years = [self.base_year, this_year] else: self.years = self.base_year self.yrndx = 0 if self.yrndx < 0: self.yrndx = len(self.years) self.years.append(self.base_year) parents = [] try: parents = getParents(config.items('Parents')) except: pass self.grid_stations = '' try: fac_file = config.get('Files', 'grid_stations') for key, value in parents: fac_file = fac_file.replace(key, value) fac_file = fac_file.replace('$USER$', getUser()) fac_file = fac_file.replace('$YEAR$', self.base_year) self.grid_stations = fac_file except: pass self.load_file = '' try: fac_file = config.get('Files', 'load') for key, value in parents: fac_file = fac_file.replace(key, value) fac_file = fac_file.replace('$USER$', getUser()) fac_file = fac_file.replace('$YEAR$', self.base_year) self.load_file = fac_file except: pass my_config = configparser.RawConfigParser() my_config_file = 'getfiles.ini' my_config.read(my_config_file) try: aemo_facilities = my_config.get('updateswis', 'aemo_facilities') except: aemo_facilities = '/datafiles/facilities/facilities.csv' try: aemo_load = my_config.get('updateswis', 'aemo_load') except: aemo_load = '/datafiles/load-summary/load-summary-$YEAR$.csv' aemo_load = aemo_load.replace('$YEAR$', self.base_year) try: aemo_url = my_config.get('updateswis', 'aemo_url') except: aemo_url = 'data.wa.aemo.com.au' self.grid = QtWidgets.QGridLayout() self.grid.addWidget(QtWidgets.QLabel('Host site:'), 0, 0) self.host = QtWidgets.QLineEdit() self.host.setText(aemo_url) self.grid.addWidget(self.host, 0, 1, 1, 2) self.grid.addWidget(QtWidgets.QLabel('Existing Stations (Facilities)'), 1, 0, 1, 2) self.grid.addWidget(QtWidgets.QLabel('File location:'), 2, 0) self.url = QtWidgets.QLineEdit() self.url.setText(aemo_facilities) self.grid.addWidget(self.url, 2, 1, 1, 2) self.grid.addWidget(QtWidgets.QLabel('Target file:'), 3, 0) self.target = ClickableQLabel() self.target.setText(self.grid_stations) self.target.setStyleSheet( "background-color: white; border: 1px inset grey; min-height: 22px; border-radius: 4px;" ) self.target.clicked.connect(self.tgtChanged) self.grid.addWidget(self.target, 3, 1, 1, 4) self.grid.addWidget(QtWidgets.QLabel('Excel file:'), 4, 0) self.excel = ClickableQLabel() self.excel.setText('') self.excel.setStyleSheet( "background-color: white; border: 1px inset grey; min-height: 22px; border-radius: 4px;" ) self.excel.clicked.connect(self.excelChanged) self.grid.addWidget(self.excel, 4, 1, 1, 3) self.grid.addWidget(QtWidgets.QLabel('Keep deleted:'), 5, 0) self.keepbox = QtWidgets.QCheckBox() self.keepbox.setCheckState(QtCore.Qt.Checked) self.grid.addWidget(self.keepbox, 5, 1) self.grid.addWidget( QtWidgets.QLabel('If checked will retain deleted facilities'), 5, 2, 1, 3) self.grid.addWidget(QtWidgets.QLabel('System Load'), 6, 0) self.grid.addWidget(QtWidgets.QLabel('Year:'), 7, 0) self.yearCombo = QtWidgets.QComboBox() for i in range(len(self.years)): self.yearCombo.addItem(self.years[i]) self.yearCombo.setCurrentIndex(self.yrndx) self.yearCombo.currentIndexChanged[str].connect(self.yearChanged) self.grid.addWidget(self.yearCombo, 7, 1) self.grid.addWidget(QtWidgets.QLabel('Wrap to prior year:'), 8, 0) self.wrapbox = QtWidgets.QCheckBox() self.wrapbox.setCheckState(QtCore.Qt.Checked) self.grid.addWidget(self.wrapbox, 8, 1) self.grid.addWidget( QtWidgets.QLabel('If checked will wrap back to prior year'), 8, 2, 1, 3) self.grid.addWidget(QtWidgets.QLabel('Load file location:'), 9, 0) self.lurl = QtWidgets.QLineEdit() self.lurl.setText(aemo_load) self.grid.addWidget(self.lurl, 9, 1, 1, 3) self.grid.addWidget(QtWidgets.QLabel('Target load file:'), 10, 0) self.targetl = ClickableQLabel() self.targetl.setText(self.load_file) self.targetl.setStyleSheet( "background-color: white; border: 1px inset grey; min-height: 22px; border-radius: 4px;" ) self.targetl.clicked.connect(self.tgtlChanged) self.grid.addWidget(self.targetl, 10, 1, 1, 4) self.log = QtWidgets.QLabel(' ') self.grid.addWidget(self.log, 11, 1, 1, 3) quit = QtWidgets.QPushButton('Quit', self) wdth = quit.fontMetrics().boundingRect(quit.text()).width() + 29 self.grid.addWidget(quit, 12, 0) quit.clicked.connect(self.quitClicked) QtWidgets.QShortcut(QtGui.QKeySequence('q'), self, self.quitClicked) dofile = QtWidgets.QPushButton('Update Existing Stations', self) self.grid.addWidget(dofile, 12, 1) dofile.clicked.connect(self.dofileClicked) dofilel = QtWidgets.QPushButton('Update Load file', self) self.grid.addWidget(dofilel, 12, 2) dofilel.clicked.connect(self.dofilelClicked) help = QtWidgets.QPushButton('Help', self) help.setMaximumWidth(wdth) self.grid.addWidget(help, 12, 3) help.clicked.connect(self.helpClicked) QtWidgets.QShortcut(QtGui.QKeySequence('F1'), self, self.helpClicked) self.grid.setColumnStretch(3, 5) frame = QtWidgets.QFrame() frame.setLayout(self.grid) self.scroll = QtWidgets.QScrollArea() self.scroll.setWidgetResizable(True) self.scroll.setWidget(frame) self.layout = QtWidgets.QVBoxLayout(self) self.layout.addWidget(self.scroll) self.setWindowTitle('SIREN - updateswis (' + fileVersion() + ') - Update SWIS Data') self.setWindowIcon(QtGui.QIcon('sen_icon32.ico')) self.center() self.resize(int(self.sizeHint().width() * 1.07), int(self.sizeHint().height() * 1.07)) self.show()
def itemClicked(self): for i in range(len(self.fields)): if self.fields[i][4].hasFocus(): suffix = '' has_user = False has_year = False upd_field = self.fields[i][4].text() if upd_field[-1] == '*': j = upd_field.rfind('/') suffix = upd_field[j:] upd_field = upd_field[:j] else: suffix = '' if upd_field.find('$USER$') >= 0: has_user = True if upd_field.find('$YEAR$') >= 0: has_year = True parents = getParents(list(self.parents.items())) for key, value in parents: upd_field = upd_field.replace(key, value) if self.fields[i][1] == 'dir': curdir = upd_field newone = QtWidgets.QFileDialog.getExistingDirectory( self, 'Choose ' + self.fields[i][2] + ' Folder', curdir, QtWidgets.QFileDialog.ShowDirsOnly) if newone != '': if self.fields[i][0] == 'Parents': self.parents[self.fields[i][2]] = newone else: longest = [0, ''] for key, value in self.parents.items(): if len(newone) > len(value) and len( value) > longest[0]: if newone[:len(value)] == value: longest = [len(value), key] if longest[0] > 0: newone = longest[1] + newone[longest[0]:] if has_year and self.parents['$YEAR$'] in newone: newone = newone.replace( self.parents['$YEAR$'], '$YEAR$') if has_user and self.parents['$USER$'] in newone: newone = newone.replace( self.parents['$USER$'], '$USER$') self.fields[i][4].setText(newone + suffix) elif self.fields[i][1] == 'fil': curfil = upd_field newone = QtWidgets.QFileDialog.getOpenFileName( self, 'Choose ' + self.fields[i][2] + ' File', curfil)[0] if newone != '': newone = QtCore.QDir.toNativeSeparators(newone) longest = [0, ''] for key, value in self.parents.items(): if len(newone) > len(value) and len( value) > longest[0]: if newone[:len(value)] == value: longest = [len(value), key] if longest[0] > 0: newone = longest[1] + newone[longest[0]:] if has_year and self.parents['$YEAR$'] in newone: newone = newone.replace(self.parents['$YEAR$'], '$YEAR$') if has_user and self.parents['$USER$'] in newone: newone = newone.replace(self.parents['$USER$'], '$USER$') self.fields[i][4].setText(newone + suffix) break