def __init__(self, values, ini_file=None): if ini_file is not None: config_file = ini_file elif len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') try: inf = open(config_file, 'r') lines = inf.readlines() inf.close() except: lines = [] del_lines = [] for section in values: in_section = False properties = values[section] props = [] for i in range(len(properties)): props.append(properties[i].split('=')[0]) for i in range(len(lines)): if lines[i][:len(section) + 2] == '[' + section + ']': in_section = True elif in_section: if lines[i][0] == '[': i -= 1 break elif lines[i][0] != ';' and lines[i][0] != '#': bits = lines[i].split('=') for j in range(len(properties) - 1, -1, -1): if bits[0] == props[j]: if properties[j] == props[j] + '=' \ or properties[j] == props[j]: # delete empty values del_lines.append(i) else: lines[i] = properties[j] + '\n' del properties[j] del props[j] if len(properties) > 0: if not in_section: lines.append('[' + section + ']\n') i += 1 for j in range(len(properties)): k = properties[j].find('=') if k > 0 and k != len(properties[j]) - 1: lines.insert(i + 1, properties[j] + '\n') i += 1 if os.path.exists(config_file + '~'): os.remove(config_file + '~') try: os.rename(config_file, config_file + '~') except: pass sou = open(config_file, 'w') for i in range(len(lines)): if i in del_lines: pass else: sou.write(lines[i]) sou.close()
def __init__(self, section, save_folder, ini_file=None): self.section = section config = configparser.RawConfigParser() if ini_file is not None: config_file = ini_file elif len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) section_items = config.items(self.section) section_dict = {} for key, value in section_items: section_dict[key] = value dialog = Table(section_dict, fields=['property', 'value'], title=self.section + ' Parameters', save_folder=save_folder, edit=True) dialog.exec_() values = dialog.getValues() if values is None: return section_dict = {} section_items = [] for key in values: try: section_items.append(key + '=' + values[key][0][6:]) except: section_items.append(key + '=') section_dict[self.section] = section_items SaveIni(section_dict, ini_file=config_file)
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, save_folder, ini_file=None): config = configparser.RawConfigParser() if ini_file is not None: config_file = ini_file elif len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) technologies = config.get('Power', 'technologies') technologies += ' ' + config.get('Power', 'fossil_technologies') technologies = technologies.split() for i in range(len(technologies)): technologies[i] = techClean(technologies[i]) technologies = sorted(technologies) tech_dict = {} for technology in technologies: area = 0. capital_cost = '' o_m_cost = '' try: area = float(config.get(technology, 'area')) except: pass try: capital_cost = config.get(technology, 'capital_cost') if capital_cost[-1] == 'K': capital_cost = float(capital_cost[:-1]) * pow(10, 3) elif capital_cost[-1] == 'M': capital_cost = float(capital_cost[:-1]) * pow(10, 6) else: capital_cost = float(capital_cost) except: pass try: o_m_cost = config.get(technology, 'o_m_cost') if o_m_cost[-1] == 'K': o_m_cost = float(o_m_cost[:-1]) * pow(10, 3) elif o_m_cost[-1] == 'M': o_m_cost = float(o_m_cost[:-1]) * pow(10, 6) else: o_m_cost = float(o_m_cost) except: pass tech_dict[technology] = [area, capital_cost, o_m_cost] dialog = Table( tech_dict, fields=['technology', 'area', 'capital_cost', 'o_m_cost'], save_folder=save_folder, title='Technologies', edit=True) dialog.exec_() values = dialog.getValues() if values is None: return SaveIni(values)
def __init__(self): config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) self.icons = { 'Biomass': 'biomass_g.png', 'CST': 'solar_g.png', 'Fossil': 'fossil_g.png', 'Geothermal': 'hot_rocks_g.png', 'Hydro': 'hydro_g.png', 'Other': 'question.png', 'PV': 'solar_pv_g.png', 'Solar Thermal': 'solar_g.png', 'Wave': 'wave_g.png', 'Wind': 'wind_g.png' } try: technologies = config.get('Power', 'technologies').split() for tec in technologies: tec = techClean(tec) try: self.icons[tec] = config.get(tec, 'icon') except: pass technologies = config.get('Power', 'fossil_technologies').split() for tec in technologies: tec = techClean(tec) try: self.icons[tec] = config.get(tec, 'icon') except: pass except: pass
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 __init__(self, year=None, scene=None): super(Resource, self).__init__() self.year = year self.scene = scene self.resource_items = [] self.be_open = True self.colours = {'dhi': ['DHI (Diffuse)', '#717100', '#ffff00', None], 'dni': ['DNI (Normal)', '#734c00', '#ff5500', None], 'ghi': ['GHI (Direct)', '#8b0000', '#ff0000', None], 'temp': ['Temperature', '#0d52e7', '#e8001f', None], 'wind': ['Wind Speed', '#82b2ff', '#0000b6', None], 'wind50': ['Wind @ 50m', '#82b2ff', '#0000b6', None]} self.hourly = False self.daily = False self.ignore = False self.detail = ['Daily By Month'] config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) if self.year is None: try: self.year = config.get('Base', 'year') except: pass self.map = '' try: tmap = config.get('Map', 'map_choice') except: tmap = '' # get default colours for key in self.colours: try: self.colours[key][1] = config.get('Colors', key + '_low') except: pass try: self.colours[key][2] = config.get('Colors', key + '_high') except: pass if tmap != '': # get this maps colours for key in self.colours: try: self.colours[key][1] = config.get('Colors' + tmap, key + '_low') self.map = tmap except: pass try: self.colours[key][2] = config.get('Colors' + tmap, key + '_high') self.map = tmap except: pass self.seasons = [] self.periods = [] try: items = config.items('Power') for item, values in items: if item[:6] == 'season': if item == 'season': continue bits = values.split(',') self.seasons.append(bits[0]) elif item[:6] == 'period': if item == 'period': continue bits = values.split(',') self.periods.append(bits[0]) except: pass if len(self.seasons) == 0: self.seasons = ['Summer', 'Autumn', 'Winter', 'Spring'] if len(self.periods) == 0: self.periods = ['Winter', 'Summer'] for i in range(len(self.periods)): for j in range(len(self.seasons)): if self.periods[i] == self.seasons[j]: self.periods[i] += '2' break try: self.helpfile = config.get('Files', 'help') except: self.helpfile = '' try: opacity = float(config.get('View', 'resource_opacity')) except: opacity = .5 try: period = config.get('View', 'resource_period') except: period = self.year try: steps = int(config.get('View', 'resource_steps')) except: steps = 2 try: max_steps = int(config.get('View', 'resource_max_steps')) except: max_steps = 10 try: variable = config.get('View', 'resource_variable') except: variable = self.colours['ghi'][0] try: variable = config.get('View', 'resource_rainfall') if variable.lower() in ['true', 'yes', 'on']: self.colours['rain'] = ['Rainfall', '#e6e7e6', '#005500', None] except: pass self.restorewindows = False try: rw = config.get('Windows', 'restorewindows') if rw.lower() in ['true', 'yes', 'on']: self.restorewindows = True except: pass yrf = rreplace(self.scene.resource_grid, '$YEAR$', self.year, 1) yrf = yrf.replace('$YEAR$', self.year) if not os.path.exists(yrf): self.be_open = False return mrf = rreplace(self.scene.resource_grid, '$YEAR$', self.year + '-01', 1) mrf = mrf.replace('$YEAR$', self.year) if os.path.exists(mrf): self.hourly = True self.detail.append('Hourly by Month') drf = rreplace(self.scene.resource_grid, '$YEAR$', self.year + '-01-01', 1) drf = drf.replace('$YEAR$', self.year) if os.path.exists(drf): self.daily = True self.detail.append('Hourly by Day') self.resource_file = "" self.the_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] self.mth_index = [0] for i in range(len(self.the_days) - 1): self.mth_index.append(self.mth_index[-1] + self.the_days[i] * 24) self.btn = [] self.grid = QtWidgets.QGridLayout() row = 0 self.detailCombo = QtWidgets.QComboBox() self.periodCombo = QtWidgets.QComboBox() self.dayCombo = QtWidgets.QComboBox() self.hourCombo = QtWidgets.QComboBox() for det in self.detail: self.detailCombo.addItem(det) if len(self.detail) > 1: self.grid.addWidget(QtWidgets.QLabel('Weather Detail:'), row, 0) self.grid.addWidget(self.detailCombo, row, 1, 1, 2) self.detailCombo.currentIndexChanged[str].connect(self.changeDetail) row += 1 self.grid.addWidget(QtWidgets.QLabel('Weather Period:'), row, 0) self.periodCombo.currentIndexChanged[str].connect(self.periodChange) self.grid.addWidget(self.periodCombo, row, 1, 1, 2) self.dayCombo.currentIndexChanged[str].connect(self.periodChange) self.dayCombo.hide() self.grid.addWidget(self.dayCombo, row, 3, 1, 2) self.hourCombo.currentIndexChanged[str].connect(self.periodChange) self.hourCombo.hide() self.grid.addWidget(self.hourCombo, row, 5, 1, 3) row += 1 prev = QtWidgets.QPushButton('<', self) width = prev.fontMetrics().boundingRect('<').width() + 10 prev.setMaximumWidth(width) self.grid.addWidget(prev, row, 0) prev.clicked.connect(self.prevClicked) self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.slider.valueChanged.connect(self.slideChanged) self.grid.addWidget(self.slider, row, 1, 1, 5) next = QtWidgets.QPushButton('>', self) width = next.fontMetrics().boundingRect('>').width() + 10 next.setMaximumWidth(width) self.grid.addWidget(next, row, 7) next.clicked.connect(self.nextClicked) row += 1 self.do_loop = False self.grid.addWidget(QtWidgets.QLabel('Period Loop (secs):'), row, 0) self.loopSpin = QtWidgets.QDoubleSpinBox() self.loopSpin.setRange(0., 10.) self.loopSpin.setDecimals(1) self.loopSpin.setSingleStep(.2) self.loopSpin.setValue(0.) self.loopSpin.valueChanged[str].connect(self.loopChanged) self.grid.addWidget(self.loopSpin, row, 1, 1, 2) self.loop = QtWidgets.QPushButton('Loop', self) self.grid.addWidget(self.loop, row, 3, 1, 4) self.loop.clicked.connect(self.loopClicked) row += 1 self.grid.addWidget(QtWidgets.QLabel('Weather Variable:'), row, 0) self.whatCombo = QtWidgets.QComboBox() for key in sorted(self.colours): self.whatCombo.addItem(self.colours[key][0]) if variable == self.colours[key][0]: self.whatCombo.setCurrentIndex(self.whatCombo.count() - 1) self.whatCombo.currentIndexChanged[str].connect(self.periodChange) self.grid.addWidget(self.whatCombo, row, 1, 1, 2) if len(self.detail) > 1: self.detailCombo.currentIndexChanged[str].connect(self.changeDetail) row += 1 self.grid.addWidget(QtWidgets.QLabel('Colour Steps:'), row, 0) self.stepSpin = QtWidgets.QSpinBox() self.stepSpin.setRange(0, max_steps) self.stepSpin.setValue(steps) self.stepSpin.valueChanged[str].connect(self.stepChanged) self.grid.addWidget(self.stepSpin, row, 1, 1, 2) row += 1 self.grid.addWidget(QtWidgets.QLabel('Opacity:'), row, 0) self.opacitySpin = QtWidgets.QDoubleSpinBox() self.opacitySpin.setRange(0, 1.) self.opacitySpin.setDecimals(2) self.opacitySpin.setSingleStep(.05) self.opacitySpin.setValue(opacity) self.opacitySpin.valueChanged[str].connect(self.opacityChanged) self.grid.addWidget(self.opacitySpin, row, 1, 1, 2) self.grid.addWidget(QtWidgets.QLabel('Grid only:'), row, 3) self.grid_only = QtWidgets.QCheckBox() self.grid_only.setCheckState(QtCore.Qt.Unchecked) self.grid.addWidget(self.grid_only, row, 4) row += 1 self.grid.addWidget(QtWidgets.QLabel('Low Colour'), row, 1) self.grid.addWidget(QtWidgets.QLabel('High Colour'), row, 2) row += 1 self.gradients = [] value = self.palette().color(QtGui.QPalette.Window) self.first_row = row for key in sorted(self.colours): self.gradients.append([]) for i in range(self.stepSpin.maximum() + 1): self.gradients[-1].append(QtWidgets.QLabel('__')) self.gradients[-1][-1].setStyleSheet('QLabel {background-color: %s; color: %s;}' % (value.name(), value.name())) self.grid.addWidget(self.gradients[-1][-1], row, i + 3) row += 1 row = self.first_row for key in sorted(self.colours): self.grid.addWidget(QtWidgets.QLabel(self.colours[key][0]), row, 0) if self.colours[key][1] != '': value = QtGui.QColor(self.colours[key][1]) self.btn.append(QtWidgets.QPushButton(key + '_1', self)) self.btn[-1].clicked.connect(self.colourChanged) self.btn[-1].setStyleSheet('QPushButton {background-color: %s; color: %s;}' % (value.name(), value.name())) self.grid.addWidget(self.btn[-1], row, 1) if self.colours[key][2] != '': value = QtGui.QColor(self.colours[key][2]) self.btn.append(QtWidgets.QPushButton(key + '_2', self)) self.btn[-1].clicked.connect(self.colourChanged) self.btn[-1].setStyleSheet('QPushButton {background-color: %s; color: %s;}' % (value.name(), value.name())) self.grid.addWidget(self.btn[-1], row, 2) if self.stepSpin.value() > 0: colors = gradient(self.colours[key][1], self.colours[key][2], self.stepSpin.value()) for i in range(len(colors)): value = QtGui.QColor(colors[i]) self.gradients[row - self.first_row][i].setStyleSheet('QLabel {background-color: %s; color: %s;}' % (value.name(), value.name())) row += 1 quit = QtWidgets.QPushButton('Quit', self) self.grid.addWidget(quit, row, 0) quit.clicked.connect(self.quitClicked) QtWidgets.QShortcut(QtGui.QKeySequence('q'), self, self.quitClicked) doit = QtWidgets.QPushButton('Show', self) self.grid.addWidget(doit, row, 1) doit.clicked.connect(self.showClicked) hide = QtWidgets.QPushButton('Hide', self) self.grid.addWidget(hide, row, 2) hide.clicked.connect(self.hideClicked) save = QtWidgets.QPushButton('Save', self) self.grid.addWidget(save, row, 3, 1, 4) save.clicked.connect(self.saveClicked) help = QtWidgets.QPushButton('Help', self) self.grid.addWidget(help, row, 7, 1, 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 - Renewable Resource Overlay') self.setWindowIcon(QtGui.QIcon('sen_icon32.ico')) self.stepChanged('a') if sys.platform == 'win32' or sys.platform == 'cygwin': move_right = False else: move_right = True if self.restorewindows: try: rw = config.get('Windows', 'resource_size').split(',') self.resize(int(rw[0]), int(rw[1])) mp = config.get('Windows', 'resource_pos').split(',') self.move(int(mp[0]), int(mp[1])) move_right = False except: pass if move_right: frameGm = self.frameGeometry() screen = QtWidgets.QApplication.desktop().screenNumber(QtWidgets.QApplication.desktop().cursor().pos()) trPoint = QtWidgets.QApplication.desktop().availableGeometry(screen).topRight() frameGm.moveTopRight(trPoint) self.move(frameGm.topRight()) QtWidgets.QShortcut(QtGui.QKeySequence('pgup'), self, self.prevClicked) QtWidgets.QShortcut(QtGui.QKeySequence('pgdown'), self, self.nextClicked) QtWidgets.QShortcut(QtGui.QKeySequence('Ctrl++'), self, self.nextClicked) QtWidgets.QShortcut(QtGui.QKeySequence('Ctrl+-'), self, self.prevClicked) self.setPeriod() self.resourceGrid() self.show()
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(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
def __init__(self, parent=None): QtWidgets.QDialog.__init__(self, parent) self.siren_dir = '.' if len(sys.argv) > 1: if sys.argv[1][-4:] == '.ini': self.invoke('sirenm', sys.argv[1]) sys.exit() elif os.path.isdir(sys.argv[1]): self.siren_dir = sys.argv[1] if sys.platform == 'win32' or sys.platform == 'cygwin': if self.siren_dir[-1] != '\\' and self.siren_dir[-1] != '/': self.siren_dir += '\\' elif self.siren_dir[-1] != '/': self.siren_dir += '/' else: self.siren_dir = getModelFile() self.entries = [] fils = os.listdir(self.siren_dir) self.help = 'help.html' self.about = 'about.html' self.config = configparser.RawConfigParser() ignore = [ 'flexiplot.ini', 'getfiles.ini', 'powerplot.ini', 'siren_default.ini', 'siren_windows_default.ini' ] errors = '' for fil in sorted(fils): if fil[-4:] == '.ini': if fil in ignore: continue mod_time = time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime(os.path.getmtime(self.siren_dir + fil))) ok, model_name, errors = self.check_file(fil, errors) self.entries.append([fil, model_name, mod_time, ok]) if len(errors) > 0: dialog = displayobject.AnObject(QtWidgets.QDialog(), errors, title='SIREN (' + fileVersion() + ') - Preferences file errors') dialog.exec_() if len(self.entries) == 0: self.new() self.setWindowTitle('SIREN (' + fileVersion() + ') - Select SIREN Model') self.setWindowIcon(QtGui.QIcon('sen_icon32.ico')) buttonLayout = QtWidgets.QHBoxLayout() self.quitButton = QtWidgets.QPushButton(self.tr('&Quit')) buttonLayout.addWidget(self.quitButton) self.quitButton.clicked.connect(self.quit) QtWidgets.QShortcut(QtGui.QKeySequence('q'), self, self.quit) self.newButton = QtWidgets.QPushButton(self.tr('&New Model')) buttonLayout.addWidget(self.newButton) self.newButton.clicked.connect(self.new) buttons = QtWidgets.QFrame() buttons.setLayout(buttonLayout) layout = QtWidgets.QGridLayout() self.table = QtWidgets.QTableWidget() self.table.setRowCount(len(self.entries)) self.table.setColumnCount(3) hdr_labels = ['Preference File', 'SIREN Model', 'Date modified'] self.table.setHorizontalHeaderLabels(hdr_labels) self.headers = self.table.horizontalHeader() self.headers.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.headers.customContextMenuRequested.connect(self.header_click) self.headers.setSelectionMode( QtWidgets.QAbstractItemView.SingleSelection) self.table.verticalHeader().setVisible(False) self.table.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) self.table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) max_row = 30 for rw in range(len(self.entries)): ln = 0 for cl in range(3): self.table.setItem( rw, cl, QtWidgets.QTableWidgetItem(self.entries[rw][cl])) ln += len(self.entries[rw][cl]) if ln > max_row: max_row = ln self.sort_desc = False # start in date descending order self.sort_col = 2 self.order(2) self.table.resizeColumnsToContents() self.table.viewport().installEventFilter(self) fnt = self.table.fontMetrics() ln = max_row * max(9, fnt.averageCharWidth()) ln2 = (len(self.entries) + 8) * (fnt.xHeight() + fnt.lineSpacing()) screen = QtWidgets.QDesktopWidget().screenGeometry() if ln > screen.width() * .9: ln = int(screen.width() * .9) if ln2 > screen.height() * .9: ln2 = int(screen.height() * .9) layout.addWidget( QtWidgets.QLabel( 'Left click on row for Desired Model or right click for Tools; Right click column header to sort' ), 0, 0) layout.addWidget(self.table, 1, 0) layout.addWidget(buttons, 2, 0) menubar = QtWidgets.QMenuBar() utilities = [ 'flexiplot', 'getmap', 'getmerra2', 'makeweatherfiles', 'powerplot', 'sirenupd' ] utilicon = [ 'line.png', 'map.png', 'download.png', 'weather.png', 'line.png', 'download.png' ] spawns = [] icons = [] if sys.platform == 'win32' or sys.platform == 'cygwin': for i in range(len(utilities)): if os.path.exists(utilities[i] + '.exe'): spawns.append(utilities[i] + '.exe') icons.append(utilicon[i]) else: if os.path.exists(utilities[i] + '.py'): spawns.append(utilities[i] + '.py') icons.append(utilicon[i]) else: for i in range(len(utilities)): if os.path.exists(utilities[i] + '.py'): spawns.append(utilities[i] + '.py') icons.append(utilicon[i]) if len(spawns) > 0: spawnitem = [] spawnMenu = menubar.addMenu('&Tools') for i in range(len(spawns)): if type(spawns[i]) is list: who = spawns[i][0][:spawns[i][0].find('.')] else: who = spawns[i][:spawns[i].find('.')] spawnitem.append( QtWidgets.QAction(QtGui.QIcon(icons[i]), who, self)) spawnitem[-1].triggered.connect(partial(self.spawn, spawns[i])) spawnMenu.addAction(spawnitem[-1]) layout.setMenuBar(menubar) self.model_tool = [ 'flexiplot', 'getmap', 'indexweather', 'makegrid', 'powermatch', 'powerplot', 'sirenm', 'updateswis' ] self.model_icon = [ 'line.png', 'map.png', 'list.png', 'grid.png', 'power.png', 'line.png', 'sen_icon32.png', 'list.png' ] help = QtWidgets.QAction(QtGui.QIcon('help.png'), 'Help', self) help.setShortcut('F1') help.setStatusTip('Help') help.triggered.connect(self.showHelp) about = QtWidgets.QAction(QtGui.QIcon('about.png'), 'About', self) about.setShortcut('Ctrl+I') about.setStatusTip('About') about.triggered.connect(self.showAbout) helpMenu = menubar.addMenu('&Help') helpMenu.addAction(help) helpMenu.addAction(about) self.setLayout(layout) size = QtCore.QSize(ln, ln2) self.resize(size)
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 __init__(self, stations, powers, main, year=None): super(Visualise, self).__init__() self.year = year self.stations = stations self.powers = powers self.scene = main.view.scene() self.save_View = main.save_View self.viewPrefix = None self.viewSuffix = None self.viewDo = False self.visual_group = QtWidgets.QGraphicsItemGroup() self.visual_items = [] self.scene.addItem(self.visual_group) self.be_open = True self.ignore = False self.detail = ['Diurnal', 'Hourly'] self.the_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] self.mth_index = [0] for i in range(len(self.the_days) - 1): self.mth_index.append(self.mth_index[-1] + self.the_days[i] * 24) config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) if self.year is None: try: self.year = config.get('Base', 'year') except: pass self.seasons = [] self.periods = [] self.daily = True try: items = config.items('Power') for item, value in items: if item[:6] == 'season': if item == 'season': continue i = int(item[6:]) - 1 if i >= len(self.seasons): self.seasons.append([]) self.seasons[i] = value.split(',') for j in range(1, len(self.seasons[i])): self.seasons[i][j] = int(self.seasons[i][j]) - 1 elif item[:6] == 'period': if item == 'period': continue i = int(item[6:]) - 1 if i >= len(self.periods): self.periods.append([]) self.periods[i] = value.split(',') for j in range(1, len(self.periods[i])): self.periods[i][j] = int(self.periods[i][j]) - 1 elif item == 'save_view': if value.lower() in ['true', 'yes', 'on']: self.viewDo = True except: pass if len(self.seasons) == 0: self.seasons = [['Summer', 11, 0, 1], ['Autumn', 2, 3, 4], ['Winter', 5, 6, 7], ['Spring', 8, 9, 10]] if len(self.periods) == 0: self.periods = [['Winter', 4, 5, 6, 7, 8, 9], ['Summer', 10, 11, 0, 1, 2, 3]] for i in range(len(self.periods)): for j in range(len(self.seasons)): if self.periods[i][0] == self.seasons[j][0]: self.periods[i][0] += '2' break self.stn_items = [] for i in range(len(self.stations)): self.stn_items.append(-1) for i in range(len(self.scene._stations.stations)): try: j = self.stations.index(self.scene._stations.stations[i].name) self.stn_items[j] = i except: pass self.grid = QtWidgets.QGridLayout() row = 0 self.detailCombo = QtWidgets.QComboBox() self.dayCombo = QtWidgets.QComboBox() self.hourCombo = QtWidgets.QComboBox() for det in self.detail: self.detailCombo.addItem(det) self.grid.addWidget(QtWidgets.QLabel('Detail:'), row, 0) self.grid.addWidget(self.detailCombo, row, 1, 1, 2) self.detailCombo.currentIndexChanged[str].connect(self.changeDetail) row += 1 self.grid.addWidget(QtWidgets.QLabel('Period:'), row, 0) self.periodCombo = QtWidgets.QComboBox() self.grid.addWidget(self.periodCombo, row, 1) #, 1, 2) self.grid.addWidget(self.dayCombo, row, 2) #, 1, 2) self.grid.addWidget(self.hourCombo, row, 3) row += 1 prev = QtWidgets.QPushButton('<', self) width = prev.fontMetrics().boundingRect('<').width() + 10 prev.setMaximumWidth(width) self.grid.addWidget(prev, row, 0) prev.clicked.connect(self.prevClicked) self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.slider.valueChanged.connect(self.slideChanged) self.grid.addWidget(self.slider, row, 1, 1, 5) nextt = QtWidgets.QPushButton('>', self) width = nextt.fontMetrics().boundingRect('>').width() + 10 nextt.setMaximumWidth(width) self.grid.addWidget(nextt, row, 7) nextt.clicked.connect(self.nextClicked) row += 1 self.viewSpin = QtWidgets.QSpinBox() self.viewSpin.setRange(0, 8760) self.viewSpin.setValue(0) if self.viewDo: self.grid.addWidget(QtWidgets.QLabel('Save Views:'), row, 0) self.viewSpin.valueChanged.connect(self.viewChanged) self.grid.addWidget(self.viewSpin, row, 1) row += 1 self.grid.addWidget(QtWidgets.QLabel('Repeat Loop:'), row, 0) self.repeat = QtWidgets.QCheckBox() self.repeat.setCheckState(QtCore.Qt.Unchecked) self.grid.addWidget(self.repeat, row, 1) row += 1 self.do_loop = False self.grid.addWidget(QtWidgets.QLabel('Period Loop (secs):'), row, 0) self.loopSpin = QtWidgets.QDoubleSpinBox() self.loopSpin.setRange(0., 10.) self.loopSpin.setDecimals(2) self.loopSpin.setSingleStep(.05) self.loopSpin.setValue(0.) self.loopSpin.valueChanged[str].connect(self.loopChanged) self.grid.addWidget(self.loopSpin, row, 1, 1, 2) self.loop = QtWidgets.QPushButton('Loop', self) self.grid.addWidget(self.loop, row, 3, 1, 4) self.loop.clicked.connect(self.loopClicked) row += 1 quit = QtWidgets.QPushButton('Quit', self) self.grid.addWidget(quit, row, 0) quit.clicked.connect(self.quitClicked) QtWidgets.QShortcut(QtGui.QKeySequence('q'), self, self.quitClicked) 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 - Visualise generation') self.setWindowIcon(QtGui.QIcon('sen_icon32.ico')) if sys.platform == 'win32' or sys.platform == 'cygwin': move_right = False else: move_right = True QtWidgets.QShortcut(QtGui.QKeySequence('pgup'), self, self.prevClicked) QtWidgets.QShortcut(QtGui.QKeySequence('pgdown'), self, self.nextClicked) QtWidgets.QShortcut(QtGui.QKeySequence('Ctrl++'), self, self.nextClicked) QtWidgets.QShortcut(QtGui.QKeySequence('Ctrl+-'), self, self.prevClicked) QtWidgets.QShortcut(QtGui.QKeySequence('Ctrl+Z'), self, self.loopClicked) self.setPeriod() self.periodCombo.currentIndexChanged[str].connect(self.periodChange) self.dayCombo.currentIndexChanged[str].connect(self.periodChange) self.hourCombo.currentIndexChanged[str].connect(self.periodChange) self.showPeriod(0) self.show()
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 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 __init__(self, ini_file=None, section='Colors', add_colour=False, palette=None, underscore=False): super(Colours, self).__init__() config = configparser.RawConfigParser() if ini_file is not None: self.config_file = ini_file elif len(sys.argv) > 1: self.config_file = sys.argv[1] else: self.config_file = getModelFile('SIREN.ini') self.section = section self.underscore = underscore config.read(self.config_file) groups = [ 'Fossil Technologies', 'Grid', 'Map', 'Plot', 'Resource', 'Technologies', 'The Rest' ] map_colours = [ 'background', 'border', 'fossil', 'fossil_name', 'station', 'station_name', 'town', 'town_name' ] plot_colours = ['cumulative', 'gross_load', 'load', 'shortfall'] resource_colours = [ 'dhi_high', 'dhi_low', 'dni_high', 'dni_low', 'ghi_high', 'ghi_low', 'rain_high', 'rain_low', 'temp_high', 'temp_low', 'wind50_high', 'wind50_low', 'wind_high', 'wind_low' ] colour_groups = {} for group in groups: colour_groups[group] = [] try: technologies = config.get('Power', 'technologies') technologies = technologies.split() except: technologies = [] try: fossil_technologies = config.get('Power', 'fossil_technologies') fossil_technologies = fossil_technologies.split() except: fossil_technologies = [] self.map = '' if self.section == 'Colors': try: self.map = config.get('Map', 'map_choice') except: pass self.colours = {} try: colours0 = config.items(self.section) for it, col in colours0: if it == 'ruler': continue self.colours[it] = ['', col] except: pass self.default_col = 1 if self.map != '': self.default_col = 2 try: colours1 = config.items(self.section + self.map) for it, col in colours1: if it == 'ruler': continue if it in self.colours: self.colours[it] = [col, self.colours[it][1]] else: self.colours[it] = [col, ''] except: pass if palette is not None and len(palette) > 0: # set palette of colours col = ['', ''] col[0] = QtWidgets.QColorDialog.getColor( QtCore.Qt.white, None, 'Select colour for item 1') if len(palette) > 1: col[1] = QtWidgets.QColorDialog.getColor( QtCore.Qt.white, None, 'Select colour for item ' + str(len(palette))) inc = [] for c in range(3): inc.append((col[1].getRgb()[c] - col[0].getRgb()[c]) / (len(palette) - 1)) for i in range(len(palette)): colr = [] for c in range(3): colr.append(int(col[0].getRgb()[c] + inc[c] * i)) QtGui.QColor.setRgb(col[1], colr[0], colr[1], colr[2]) if self.underscore: self.colours[palette[i].lower()] = ['', col[1].name()] else: self.colours[palette[i].lower().replace( ' ', '_')] = ['', col[1].name()] else: if self.underscore: self.colours[palette[0].lower()] = ['', col[0].name()] else: self.colours[palette[0].lower().replace( ' ', '_')] = ['', col[0].name()] group_colours = False try: gc = config.get('View', 'group_colours') if gc.lower() in ['true', 'on', 'yes']: group_colours = True except: pass self.old_ruler = '' for key, value in self.colours.items(): if key in fossil_technologies: colour_groups['Fossil Technologies'].append(key) elif key.find('grid') >= 0: colour_groups['Grid'].append(key) elif key in map_colours: colour_groups['Map'].append(key) elif key in plot_colours: colour_groups['Plot'].append(key) elif key in resource_colours: colour_groups['Resource'].append(key) elif key in technologies: colour_groups['Technologies'].append(key) else: colour_groups['The Rest'].append(key) for i in range(2): if value[i] != '': value[i] = QtGui.QColor(value[i]) self.colours[key] = value self.width = [0, 0] self.height = [0, 0] self.item = [] self.btn = [] self.grid = QtWidgets.QGridLayout() self.grid.addWidget(QtWidgets.QLabel('Item'), 0, 0) if self.map != '': self.grid.addWidget(QtWidgets.QLabel('Colour for ' + self.map), 0, 1) self.grid.addWidget(QtWidgets.QLabel('Default Colour'), 0, self.default_col) i = 1 if group_colours: bold = QtGui.QFont() bold.setBold(True) for gkey, gvalue in iter(sorted(colour_groups.items())): label = QtWidgets.QLabel(gkey) label.setFont(bold) self.grid.addWidget(label, i, 0) i += 1 for key in sorted(gvalue): value = self.colours[key] self.add_item(key, value, i) i += 1 else: for key, value in iter(sorted(self.colours.items())): self.add_item(key, value, i) i += 1 if add_colour: if self.underscore: key = add_colour.lower() else: key = add_colour.lower().replace(' ', '_') self.colours[key] = ['', ''] self.add_item(key, ['', ''], -1) self.showDialog(colour=key) buttonLayout = QtWidgets.QHBoxLayout() quit = QtWidgets.QPushButton('Quit', self) quit.setMaximumWidth(70) buttonLayout.addWidget(quit) quit.clicked.connect(self.quitClicked) save = QtWidgets.QPushButton('Save && Exit', self) buttonLayout.addWidget(save) save.clicked.connect(self.saveClicked) if self.section != 'Colors': add = QtWidgets.QPushButton('Add', self) buttonLayout.addWidget(add) add.clicked.connect(self.addClicked) buttons = QtWidgets.QFrame() buttons.setLayout(buttonLayout) layout = QtWidgets.QVBoxLayout() layout.addLayout(self.grid) layout.addWidget(buttons) self.setLayout(layout) self.grid.setColumnMinimumWidth(0, self.width[0]) self.grid.setColumnMinimumWidth(1, self.width[0]) if self.map != '': self.grid.setColumnMinimumWidth(2, self.width[0]) frame = QtWidgets.QFrame() frame.setLayout(layout) self.scroll = QtWidgets.QScrollArea() self.scroll.setWidgetResizable(True) self.scroll.setWidget(frame) self.layout = QtWidgets.QVBoxLayout(self) self.layout.addWidget(self.scroll) screen = QtWidgets.QDesktopWidget().availableGeometry() # if self.height[0] == 0: metrics = quit.fontMetrics() self.height[0] = metrics.boundingRect( quit.text()).height() + self.grid.verticalSpacing() * 3 height = (self.height[0] + self.grid.verticalSpacing() * 2) * self.grid.rowCount() + buttons.sizeHint().height() if height > int(screen.height() * .9): self.height[1] = int(screen.height() * .9) else: self.height[1] = height if self.width[0] == 0: self.width[1] = buttons.sizeHint().width() + 80 else: self.width[1] = self.width[0] * 3 + 80 self.resize(self.width[1], self.height[1]) # self.resize(640, 480) self.setWindowTitle('SIREN - Color dialog') self.setWindowIcon(QtGui.QIcon('sen_icon32.ico')) QtWidgets.QShortcut(QtGui.QKeySequence('q'), self, self.quitClicked)
def __init__(self, what, src_dir, tgt_fil): config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') self.log = '' files = [] fils = os.listdir(src_dir) for fil in fils: if (what[0].lower() == 's' and (fil[-4:] == '.csv' or fil[-4:] == '.smw')) \ or (what[0].lower() == 'w' and fil[-4:] == '.srw'): tf = open(src_dir + '/' + fil, 'r') lines = tf.readlines() tf.close() if fil[-4:] == '.smw': bits = lines[0].split(',') src_lat = float(bits[4]) src_lon = float(bits[5]) elif fil[-4:] == '.srw': bits = lines[0].split(',') src_lat = float(bits[5]) src_lon = float(bits[6]) elif fil[-10:] == '(TMY2).csv' or fil[-10:] == '(TMY3).csv' \ or fil[-10:] == '(INTL).csv' or fil[-4:] == '.csv': fst_row = len(lines) - 8760 if fst_row < 3: bits = lines[0].split(',') src_lat = float(bits[4]) src_lon = float(bits[5]) 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]) else: continue files.append([src_lat, src_lon, fil]) if tgt_fil[-4:] == '.xls' or tgt_fil[-5:] == '.xlsx': wb = xlwt.Workbook() fnt = xlwt.Font() fnt.bold = True styleb = xlwt.XFStyle() styleb.font = fnt ws = wb.add_sheet('Index') ws.write(0, 0, 'Latitude') ws.write(0, 1, 'Longitude') ws.write(0, 2, 'Filename') lens = [8, 9, 8] for i in range(len(files)): for c in range(3): ws.write(i + 1, c, files[i][c]) lens[c] = max(len(str(files[i][c])), lens[c]) for c in range(len(lens)): if lens[c] * 275 > ws.col(c).width: ws.col(c).width = lens[c] * 275 ws.set_panes_frozen(True) # frozen headings instead of split panes ws.set_horz_split_pos(1) # in general, freeze after last heading row ws.set_remove_splits(True) # if user does unfreeze, don't leave a split there wb.save(tgt_fil) else: tf = open(tgt_fil, 'w') hdr = 'Latitude,Longitude,Filename\n' tf.write(hdr) for i in range(len(files)): line = '%s,%s,"%s"\n' % (files[i][0], files[i][1], files[i][2]) tf.write(line) tf.close() self.log += '%s created' % tgt_fil[tgt_fil.rfind('/') + 1:]
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 __init__(self, menubar): super(FloatMenu, self).__init__() self.menubar = menubar config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) self.restorewindows = False try: rw = config.get('Windows', 'restorewindows') if rw.lower() in ['true', 'yes', 'on']: self.restorewindows = True except: pass try: open_menus = config.get('Windows', 'menu_open').split(',') except: open_menus = '' self.be_open = True self.menus = [] for lvl1 in self.menubar.actions(): if lvl1.text().find('&') >= 0: try: self.menus.append( [lvl1.text().replace('&', ''), lvl1.icon(), None, []]) except: self.menus.append( [lvl1.text().replace('&', ''), None, None, []]) try: for lvl2 in lvl1.menu().actions(): if lvl2.text().find('&') >= 0: try: self.menus[-1][-1].append([ lvl2.text().replace('&', ''), lvl2.icon(), None, [] ]) except: self.menus[-1][-1].append([ lvl2.text().replace('&', ''), None, None, [] ]) try: for lvl3 in lvl2.menu().actions(): self.menus[-1][-1][-1][-1].append( [lvl3.text(), lvl3.icon(), lvl3, '3']) except: pass else: self.thisaction = lvl2 self.menus[-1][-1].append( [lvl2.text(), lvl2.icon(), lvl2, '2']) except: pass else: self.menus.append( [lvl1.text(), lvl1.icon(), lvl1.actions()[0], '1']) self.grid = QtWidgets.QGridLayout() ctr = 0 self.butn = [] self.topmenus = {} self.buttons = {} for i in range(len(self.menus)): self.butn.append(QtWidgets.QPushButton(self.menus[i][0], self)) self.butn[-1].setIcon(self.menus[i][1]) self.butn[-1].setStyleSheet( 'QPushButton {color: #005fb6; border: 2px solid #e65900;' + ' border-radius: 6px;}') self.butn[-1].clicked.connect(self.menuClicked) self.grid.addWidget(self.butn[-1], ctr, 0, 1, 3) ctr += 1 self.topmenus[self.menus[i][0]] = [False, ctr, 0] if type(self.menus[i][3]) is list: for j in range(len(self.menus[i][3])): self.butn.append( QtWidgets.QPushButton(self.menus[i][3][j][0], self)) self.butn[-1].setIcon(self.menus[i][3][j][1]) # self.butn[-1].setStyleSheet('QPushButton {Text-align:left;}') self.butn[-1].clicked.connect(self.buttonClicked) self.butn[-1].hide() self.buttons[self.menus[i][3][j] [0]] = self.menus[i][3][j][2] self.grid.addWidget(self.butn[-1], ctr, 1, 1, 2) ctr += 1 if type(self.menus[i][3][j][3]) is list: for k in range(len(self.menus[i][3][j][3])): self.butn.append( QtWidgets.QPushButton( self.menus[i][3][j][3][k][0], self)) self.butn[-1].setIcon(self.menus[i][3][j][3][k][1]) # self.butn[-1].setStyleSheet('QPushButton {Text-align:left;}') self.butn[-1].clicked.connect(self.buttonClicked) self.butn[-1].hide() self.buttons[self.menus[i][3][j][3][k] [0]] = self.menus[i][3][j][3][k][2] self.grid.addWidget(self.butn[-1], ctr, 2) ctr += 1 self.topmenus[self.menus[i][0]][2] = ctr quit = QtWidgets.QPushButton('Quit Menu', self) self.grid.addWidget(quit, ctr, 0) quit.clicked.connect(self.close) QtWidgets.QShortcut(QtGui.QKeySequence('q'), self, self.close) for mnu in open_menus: strt = self.topmenus[mnu][1] stop = self.topmenus[mnu][2] for j in range(strt, stop): self.butn[j].show() self.topmenus[mnu][0] = True 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 - Menu') self.setWindowIcon(QtGui.QIcon('sen_icon32.ico')) if self.restorewindows: try: rw = config.get('Windows', 'menu_size').split(',') self.resize(int(rw[0]), int(rw[1])) mp = config.get('Windows', 'menu_pos').split(',') self.move(int(mp[0]), int(mp[1])) except: pass self.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.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 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) self.restorewindows = False try: rw = config.get('Windows', 'restorewindows') if rw.lower() in ['true', 'yes', 'on']: self.restorewindows = True except: pass self.be_open = True self.grid = QtWidgets.QGridLayout() tech_sizes = {} txt_lens = [10, 0] for st in self.stations: if st.technology[:6] == 'Fossil' and not self.flags[3]: continue if st.technology not in tech_sizes: tech_sizes[st.technology] = 0. if st.technology == 'Wind': tech_sizes[st.technology] += self.techdata[ st.technology][0] * float(st.no_turbines) * pow( (st.rotor * .001), 2) else: tech_sizes[st.technology] += self.techdata[ st.technology][0] * float(st.capacity) txt_lens[0] = max(txt_lens[0], len(st.technology)) total_area = 0. row = 0 for key, value in iter(sorted(tech_sizes.items())): labl = QtWidgets.QLabel('__') colr = QtGui.QColor(self.techdata[key][1]) labl.setStyleSheet('QLabel {background-color: %s; color: %s;}' % (colr.name(), colr.name())) self.grid.addWidget(labl, row, 0) self.grid.addWidget(QtWidgets.QLabel(key), row, 1) total_area += value area = '%s sq. Km' % '{:0.1f}'.format(value) txt_lens[1] = max(txt_lens[1], len(area)) self.grid.addWidget(QtWidgets.QLabel(area), row, 2) self.grid.setRowStretch(row, 0) row += 1 self.grid.setColumnStretch(0, 0) self.grid.setColumnStretch(1, 1) self.grid.addWidget(QtWidgets.QLabel('Total Area'), row, 1) area = '%s sq. Km' % '{:0.1f}'.format(total_area) txt_lens[1] = max(txt_lens[1], len(area)) self.grid.addWidget(QtWidgets.QLabel(area), row, 2) self.grid.setRowStretch(row, 1) row += 1 if self.flags[0]: txt = 'Circles show relative capacity in MW' elif self.flags[1]: txt = 'Circles show relative generation in MWh' else: txt = 'Station ' if self.flags[2]: txt += 'Squares' else: txt += 'Circles' txt += ' show estimated area in sq. Km' if len(txt) > (txt_lens[0] + txt_lens[1]): txts = txt.split() txt = txts[0] ln = len(txt) for i in range(1, len(txts)): if ln + len(txts[i]) > (txt_lens[0] + txt_lens[1]): txt += '\n' txt += txts[i] ln = len(txts[i]) else: txt += ' ' + txts[i] ln += len(txts[i]) + 1 self.grid.addWidget(QtWidgets.QLabel(txt), row, 1, 1, 2) self.grid.setRowStretch(row, 1) row += 1 quit = QtWidgets.QPushButton('Quit', self) self.grid.addWidget(quit, row, 1) self.grid.setRowStretch(row, 1) self.grid.setVerticalSpacing(10) quit.clicked.connect(self.quitClicked) QtWidgets.QShortcut(QtGui.QKeySequence('q'), self, self.quitClicked) 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 - Legend') self.setWindowIcon(QtGui.QIcon('sen_icon32.ico')) screen = QtWidgets.QApplication.desktop().primaryScreen() scr_right = QtWidgets.QApplication.desktop().availableGeometry( screen).right() scr_bottom = QtWidgets.QApplication.desktop().availableGeometry( screen).bottom() win_width = self.sizeHint().width() win_height = self.sizeHint().height() if self.restorewindows: try: rw = config.get('Windows', 'legend_size').split(',') lst_width = int(rw[0]) lst_height = int(rw[1]) mp = config.get('Windows', 'legend_pos').split(',') lst_left = int(mp[0]) lst_top = int(mp[1]) lst_right = lst_left + lst_width lst_bottom = lst_top + lst_height screen = QtWidgets.QApplication.desktop().screenNumber( QtCore.QPoint(lst_left, lst_top)) scr_right = QtWidgets.QApplication.desktop().availableGeometry( screen).right() scr_left = QtWidgets.QApplication.desktop().availableGeometry( screen).left() if lst_right < scr_right: if (lst_right - win_width) >= scr_left: scr_right = lst_right else: scr_right = scr_left + win_width scr_bottom = QtWidgets.QApplication.desktop( ).availableGeometry(screen).bottom() scr_top = QtWidgets.QApplication.desktop().availableGeometry( screen).top() if lst_bottom < scr_bottom: if (lst_bottom - win_height) >= scr_top: scr_bottom = lst_bottom else: scr_bottom = scr_top + win_height except: pass win_left = scr_right - win_width win_top = scr_bottom - win_height self.resize(win_width, win_height) self.move(win_left, win_top) 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) self.restorewindows = False try: rw = config.get('Windows', 'restorewindows') if rw.lower() in ['true', 'yes', 'on']: self.restorewindows = True except: pass self.be_open = True self.grid = QtWidgets.QGridLayout() pixmap = QtGui.QPixmap('sen_logo_2.png') lbl = QtWidgets.QLabel(self) lbl.setPixmap(pixmap) self.grid.addWidget(lbl) if os.path.exists('credits.html'): web = QtWidgets.QTextEdit() htf = open('credits.html', 'r') html = htf.read() html = html.replace('[VERSION]', fileVersion()) html = html.replace('[VERSION-YEAR]', fileVersion(year=True)) htf.close() if html[:5] == '<html' or html[:15] == '<!DOCTYPE html>': web.setHtml(html) else: web.setPlainText(html) web.setReadOnly(True) small = QtGui.QFont() small.setPointSize(10) web.setFont(small) self.grid.addWidget(web, 1, 0) else: bold = QtGui.QFont() bold.setBold(True) labels = [] labels.append( "SIREN - SEN's Interactive Renewable Energy Network tool") labels.append('Copyright (C) 2015-' + fileVersion(year=True) + ' Sustainable Energy Now Inc., Angus King') labels.append('Release:' + fileVersion()) labels.append( 'SIREN is free software: you can redistribute it and/or modify it under the terms of the' + ' GNU Affero General Public License. The program is distributed WITHOUT ANY WARRANTY' ) labels.append( 'The SEN SAM simulation is used to calculate energy generation for renewable energy' + ' power stations using SAM models.') labels.append( 'To get started press F1 (menu option Help -> Help) to view the SIREN Help file.' ) labels.append( 'Capabilities, assumptions, limitations (ie transmission, geographic capabilities,' + ' etc), verification') labels.append( 'Contact [email protected] for more information or alternative modelling' + ' capabilities/suggestions needed') labels.append( 'We acknowledge US DOE, NASA and OpenStreetMap as follows (press Ctrl+I, menu option' + ' Help -> About, for more details):') labels.append( 'SIREN uses System Advisor Model (SAM) modules for energy calculations. SAM is provided' + ' by NREL for the US DOE') labels.append( 'SIREN may use weather data obtained from MERRA-2 data, a NASA atmospheric data set' ) labels.append( 'SIREN may use a map derived from OpenStreetMap (MapQuest) Open Aerial Tiles' ) for i in range(len(labels)): labl = QtWidgets.QLabel(labels[i]) labl.setWordWrap(True) if i == 0: labl.setFont(bold) self.grid.addWidget(labl) 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) QtWidgets.QShortcut(QtGui.QKeySequence('q'), self, self.close) QtWidgets.QShortcut(QtGui.QKeySequence('F1'), self, self.help) QtWidgets.QShortcut(QtGui.QKeySequence('Ctrl+I'), self, self.about) screen = QtWidgets.QDesktopWidget().availableGeometry() if sys.platform == 'win32' or sys.platform == 'cygwin': pct = 0.85 else: pct = 0.90 h = int(screen.height() * pct) self.resize(pixmap.width() + 55, h) frameGm = self.frameGeometry() screen = QtWidgets.QApplication.desktop().screenNumber( QtWidgets.QApplication.desktop().cursor().pos()) tlPoint = QtWidgets.QApplication.desktop().availableGeometry( screen).topLeft() frameGm.moveTopLeft(tlPoint) self.move(frameGm.topLeft()) self.setWindowTitle('SIREN - Credits') self.setWindowIcon(QtGui.QIcon('sen_icon32.ico')) if self.restorewindows: try: rw = config.get('Windows', 'credits_size').split(',') self.resize(int(rw[0]), int(rw[1])) mp = config.get('Windows', 'credits_pos').split(',') self.move(int(mp[0]), int(mp[1])) except: pass self.show()
def __init__(self, mainwindow, scenarios_folder, scenarios, program='SIREN'): super(FloatStatus, self).__init__() self.mainwindow = mainwindow self.scenarios_folder = scenarios_folder self.scenarios = scenarios self.program = program if scenarios is None: self.full_log = False else: self.full_log = True config = configparser.RawConfigParser() if len(sys.argv) > 1: self.config_file = sys.argv[1] else: self.config_file = getModelFile('SIREN.ini') config.read(self.config_file) self.restorewindows = False self.logged = False try: rw = config.get('Windows', 'restorewindows') if rw.lower() in ['true', 'yes', 'on']: self.restorewindows = True except: pass self.log_status = True try: rw = config.get('Windows', 'log_status') if rw.lower() in ['false', 'no', 'off']: self.log_status = False except: pass self.be_open = True max_line = 0 lines1 = '' lines2 = '' max_line = 0 line_cnt1 = 1 line_cnt2 = 0 if self.full_log: try: for line in self.scenarios: lines1 += line[0] + '\n' line_cnt1 += 1 if len(line[0]) > max_line: max_line = len(line[0]) if self.log_status or not self.log_status: ssc_api = ssc.API() comment = 'SAM SDK Core: Version = %s. Build info = %s.' \ % (ssc_api.version(), ssc_api.build_info().decode()) line = '%s. SIREN log started\n Preference File: %s' + \ '\n Working directory: %s' + \ '\n Scenarios folder: %s\n %s' lines2 = line % (QtCore.QDateTime.toString(QtCore.QDateTime.currentDateTime(), 'hh:mm:ss'), \ self.config_file, os.getcwd(), self.scenarios_folder, comment) line_cnt2 = 1 if len(lines2) > max_line: max_line = len(lines2) else: line_cnt2 = 0 except: pass else: line = '%s. %s log started\n Preference File: %s' + \ '\n Working directory: %s' + \ '\n Scenarios folder: %s' lines2 = line % (QtCore.QDateTime.toString(QtCore.QDateTime.currentDateTime(), 'hh:mm:ss'), \ self.program, self.config_file, os.getcwd(), self.scenarios_folder) line_cnt2 = 1 max_line = len(lines2) self.saveButton = QtWidgets.QPushButton(self.tr('Save Log')) self.saveButton.clicked.connect(self.save) self.quitButton = QtWidgets.QPushButton('Quit') self.quitButton.clicked.connect(self.close) QtWidgets.QShortcut(QtGui.QKeySequence('q'), self, self.close) buttonLayout = QtWidgets.QHBoxLayout() buttonLayout.addStretch(1) buttonLayout.addWidget(self.quitButton) buttonLayout.addWidget(self.saveButton) self.scenarios = QtWidgets.QPlainTextEdit() self.scenarios.setFont(QtGui.QFont('Courier New', 10)) fnt = self.scenarios.fontMetrics() self.scenarios.setSizePolicy( QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)) self.scenarios.setPlainText(lines1) self.scenarios.setReadOnly(True) screen = QtWidgets.QDesktopWidget().availableGeometry() ln = (max_line + 5) * fnt.maxWidth() if ln > screen.width() * .80: ln = int(screen.width() * .80) h1 = (line_cnt1 + 1) * fnt.height() if self.log_status: self.loglines = QtWidgets.QPlainTextEdit() self.loglines.setFont(QtGui.QFont('Courier New', 10)) h2 = (line_cnt2 + 2) * fnt.height() if h1 + h2 > screen.height() * .80: # h1 = max(int(screen.height() * float(h1 / h2)), int(fnt.height())) h2 = int(screen.height() * .80) - h1 self.loglines.setSizePolicy( QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)) self.loglines.setPlainText(lines2) self.loglines.setReadOnly(True) self.loglines.resize(ln, h2) self.scenarios.resize(ln, h1) self.scenarios.setFixedHeight(h1) layout = QtWidgets.QVBoxLayout() if self.full_log: layout.addWidget(QtWidgets.QLabel('Open scenarios')) layout.addWidget(self.scenarios) if self.log_status: layout.addWidget(QtWidgets.QLabel('Session log')) layout.addWidget(self.loglines) layout.addLayout(buttonLayout) self.setLayout(layout) self.setWindowTitle(self.program + ' - Status - ' + self.config_file) self.setWindowIcon(QtGui.QIcon('sen_icon32.ico')) if self.restorewindows: try: rw = config.get('Windows', 'log_size').split(',') self.resize(int(rw[0]), int(rw[1])) mp = config.get('Windows', 'log_pos').split(',') self.move(int(mp[0]), int(mp[1])) except: pass self.show()
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 __init__(self, ini_file=None, parent=None): QtWidgets.QDialog.__init__(self, parent) file_sects = ['Parents', 'Files', 'SAM Modules'] dir_props = [ 'pow_files', 'sam_sdk', 'scenarios', 'solar_files', 'variable_files', 'wind_files' ] field_props = ['check', 'scenario_prefix'] config = configparser.RawConfigParser() if ini_file is not None: self.config_file = ini_file elif len(sys.argv) > 1: self.config_file = sys.argv[1] else: self.config_file = getModelFile('SIREN.ini') config.read(self.config_file) sections = {} for section in file_sects: props = [] try: items = config.items(section) except: continue for key, value in items: props.append([key, value]) if len(props) > 0: sections[section] = props bgd = 'rgba({}, {}, {}, {})'.format( *self.palette().color(QtGui.QPalette.Window).getRgb()) bgd_style = 'background-color: ' + bgd + '; border: 1px inset grey; min-height: 22px; border-radius: 4px;' bold = QtGui.QFont() bold.setBold(True) width0 = 0 width1 = 0 width2 = 0 row = 0 self.fields = [] self.fields.append( ['section', 'typ', 'name', 'value', QtWidgets.QLineEdit()]) self.grid = QtWidgets.QGridLayout() label = QtWidgets.QLabel('Working directory') label.setFont(bold) width0 = label.fontMetrics().boundingRect(label.text()).width() * 1.1 self.grid.addWidget(label, row, 0) self.fields[row][4].setText(os.getcwd()) self.fields[row][4].setReadOnly(True) self.fields[row][4].setStyleSheet(bgd_style) width2 = self.fields[row][4].fontMetrics().boundingRect( self.fields[row][4].text()).width() * 1.1 self.grid.addWidget(self.fields[row][4], row, 2, 1, 3) self.parents = {} sections['Parents'].append(['$USER$', getUser()]) now = datetime.datetime.now() sections['Parents'].append(['$YEAR$', str(now.year - 1)]) if 'Parents' in list(sections.keys()): for key, value in sections['Parents']: self.parents[key] = value row += 1 self.fields.append(['Parents', '?', key, value, '?']) if self.fields[row][0] != self.fields[row - 1][0]: label = QtWidgets.QLabel(self.fields[row][0]) label.setFont(bold) width0 = max( width0, label.fontMetrics().boundingRect(label.text()).width() * 1.1) self.grid.addWidget(label, row, 0) label = QtWidgets.QLabel(self.fields[row][2]) width1 = max( width1, label.fontMetrics().boundingRect(label.text()).width() * 1.1) self.grid.addWidget(label, row, 1) if key == '$USER$' or key == '$YEAR$': self.fields[row][1] = 'txt' self.fields[row][4] = QtWidgets.QLineEdit() self.fields[row][4].setText(self.fields[row][3]) width2 = max( width2, self.fields[row][4].fontMetrics().boundingRect( self.fields[row][4].text()).width() * 1.1) self.fields[row][4].setReadOnly(True) self.fields[row][4].setStyleSheet(bgd_style) self.grid.addWidget(self.fields[row][4], row, 2, 1, 3) else: self.fields[row][1] = 'dir' self.fields[row][4] = ClickableQLabel() self.fields[row][4].setText(self.fields[row][3]) width2 = max( width2, self.fields[row][4].fontMetrics().boundingRect( self.fields[row][4].text()).width() * 1.1) self.fields[row][4].setStyleSheet( "background-color: white; border: 1px inset grey; min-height: 22px; border-radius: 4px;" ) self.grid.addWidget(self.fields[row][4], row, 2, 1, 3) self.fields[row][4].clicked.connect(self.itemClicked) for section, props in sections.items(): if section == 'Parents': continue for prop in props: row += 1 self.fields.append([section, '?', prop[0], prop[1], '?']) if self.fields[row][0] != self.fields[row - 1][0]: label = QtWidgets.QLabel(self.fields[row][0]) label.setFont(bold) width0 = max( width0, label.fontMetrics().boundingRect(label.text()).width() * 1.1) self.grid.addWidget(label, row, 0) label = QtWidgets.QLabel(self.fields[row][2]) width1 = max( width1, label.fontMetrics().boundingRect(label.text()).width() * 1.1) self.grid.addWidget(label, row, 1) self.fields[row][3] = prop[1] if prop[0] in field_props: self.fields[row][1] = 'txt' self.fields[row][4] = QtWidgets.QLineEdit() self.fields[row][4].setText(self.fields[row][3]) width2 = max( width2, self.fields[row][4].fontMetrics().boundingRect( self.fields[row][4].text()).width() * 1.1) else: if prop[0] in dir_props: self.fields[row][1] = 'dir' else: self.fields[row][1] = 'fil' self.fields[row][4] = ClickableQLabel() self.fields[row][4].setText(self.fields[row][3]) width2 = max( width2, self.fields[row][4].fontMetrics().boundingRect( self.fields[row][4].text()).width() * 1.1) self.fields[row][4].setStyleSheet( "background-color: white; border: 1px inset grey; min-height: 22px; border-radius: 4px;" ) self.fields[row][4].clicked.connect(self.itemClicked) self.grid.addWidget(self.fields[row][4], row, 2, 1, 3) row += 1 quit = QtWidgets.QPushButton('Quit', self) self.grid.addWidget(quit, row, 0) quit.clicked.connect(self.quitClicked) QtWidgets.QShortcut(QtGui.QKeySequence('q'), self, self.quitClicked) save = QtWidgets.QPushButton('Save & Exit', self) self.grid.addWidget(save, row, 1) save.clicked.connect(self.saveClicked) self.grid.setColumnStretch(2, 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 - Edit File Sections - ' + ini_file[ini_file.rfind('/') + 1:]) self.setWindowIcon(QtGui.QIcon('sen_icon32.ico')) self.resize(int(width0 + width1 + width2), int(self.sizeHint().height() * 1.1)) self.show()