Python for Power Systems

A blog for power systems engineers to learn Python.

Run PSSE From Python and Not the Other Way Around

What this, the Slashie, mean is you consider me the best actor slash model and not the other way around.

Fabio Zoolander

How do you run your Python scripts on PSSE? Do you open the PSSE program and run from the “Run Program Automation File..” menu? I know some of my colleagues have created macro buttons that sit on their customised toolbar. The macro button is linked to a Python file and when you click the button that Python file runs.

Both of these exemplify the case where PSSE is run first, and then your Python script is executed. PSSE is the boss and your Python script is the worker that is told when to run.

I’d like to take you through another way to run your Python scripts. The examples I’ll show you will enable your Python script to be the boss and for it to tell PSSE to run.

Why would I care who is the boss?

Many times, PSSE is just one small cog in your overall program. You need it to do all the heavy computations for your latest energy congestion forecast but you still want to send the results by email to your boss in Singapore, or publish your results on the interwebs (Yes you can do that, I’ll explain how in a later post). Then consider testing, debugging, calling your script from another program.

There are lots of cases where it absolutely makes sense to have Python firmly seated on the driver’s side with two hands on the steering wheel and its foot pushing the accelerator through the floor. PSSE is a great tool and running your programs from inside it is fine for some, but sometimes you need to let your Python scripts run free.

Show me the code

Ok, you asked and I’m not one to hold out on you. Here is some code that is suggested in the PSSE manual to get an External Interpreter Environment. I’ll take you through what it does, so you can see through the magic. I will suggest methods that will make including this in your own work a piece of cake.

First Python is its own language, complete with a full library of useful tools. The only way Python knows to find those useful tools is to look in every single directory listed in its path variable. Python does not know about PSSE at all. You need to tell it where to look to find the PSSE library files (psspy, redirect et al).

The first parts of the program, beginning with sys.path.append and os.environ['PATH'] are adding to the Python and system path variables. Only now does Python know where to look to find psspy. If you don’t believe me, try running the line import psspy from your Python shell (not inside PSSE). You should get an ImportError. Now tell Python where it can find psspy using the first three lines in the example and try import psspy again.. No error!

There are a couple of important other lines in the code before we are done, the rest are not helpful.

If you want output that PSSE would normally print while it is running to show up on the command line for your Python script use this

1
2
import redirect
redirect.psse2py()

Those lines are a matter of taste, your program won’t break without them.

1
import psspy

This was the whole point of the exercise, to get this psspy library. That is where the interaction with PSSE occurs. So here is the minimum that you need:

A word of warning about os.chdir

The best place for these commands is near the top of your Python script file or in another file in the same directory as your Python script file which you import. No one expects for a library they are importing to change the working directory, especially not to c:\work_dir so don’t use os.chdir.

Putting it all together

Here is a basic script that will open up the save case of your choice and run a fully coupled Newton-Raphson iterative solve. Just a starting point skeleton file to give you an idea of how all of this sits together:

Comments

Very helpful! thank you

Janath

this is brilliant!

KristjanP

Learn Python for PSSE

The whit team have developed a new training course specifically designed for power systems engineers to get a better handle on the Python language.
During the two or three day course you will learn advanced Python usage with examples and lessons featuring the PSSE package.
We run a maximum of 5 courses a year. Most events are for Melbourne, Sydney and Brisbane
Check out our dedicated training site for Python PSSE training.

Update:
For a brief introduction to getting started with Python for PSSE, check out our post on how to run PSSE from Python and not the other way around. Check out our other psse and python blog posts for inside information, tips and secrets that have never before been published.

whit now hosts a Python for PSSE Question and Answer forum. It is free and does not require you to sign up to ask, read or answer questions. We welcome you to come along and have a look around.

Patching Ancestor Revisions in Mercurial

Yesterday a bug was discovered in one of our production sites. The production site runs many Mercurial revisions behind the current preproduction head. We needed a way to fix the bug for the production site without requiring it update any further than that commit.

This post explains how we accomplished this task, which for some is a daily routine.

Mercurial graphlog extension

When running Mercurial from a terminal, the bundled graph log extensionis our favourite way to see an ascii drawing of our commit history. It really is a great extension to the default log command.

First: we updated to the tagged production head. Second: we applied the bug fix (and in the process created new head and branch). Third: we merged with the next descendant from the old production head. This was us merging back into the ‘mainline’.

At this point you will be left with two heads still. To remove that final head, we merged our changes with the master branch tip

Now to get that bug fix onto the production server, we need to update the code (hg up) to the revision where we merged back into the ‘mainline’. This revision contains only the bug fix changes.

Letter Pressed Business Cards Have Arrived

The whit. business cards were designed by our user experience lead Hima.

The letter press process required three passes over the design. One for each of the two colours and one for the blind stamp

Blind stamping is where the letter press plate has no ink and simply makes an indentation into the paper

a letter pressed whit. business card

Menu With a Difference

ngenworks’ menu runs on an increasing angle throughout their site

This approach works well for sites that do not have a secondary menu link and is an example of how to incorporate corporate branding with angles into design

The site uses the ff-tisa-web-pro font, which is a popular serif font

BackType Makes Sense of Billions of Tweets

Backtype (edit: they have since pivoted it seems) uses a good visual hierarchy to draw attention to the important data

Large row of numbers at the top provide important easy to digest stats like number of followers

Each of the charts, while useful on a web browser can only show so much information. The BackType team has included a link to download the data for every chart. Customers could then post process this using any tool they wanted.

Finally, making decisions when faced with a lot of information is difficult, so BackType have included some ‘recommendations’ at the bottom of the screen based on their analysis of the data

Add a Foreign Key to forms.Form

How do you get that standard ForeignKey select box with the “+” add another icon next to it on your form? This post will take you through the steps that I took to get the ForeignKey working like it does in the Django admin.

How does the Django admin create a ForeignKey select field

Django creates a forms.ModelChoiceField with queryset and to_field_name arguments as the default form field for a foreignkey. To see for yourself, have a look at django.db.models.fields.related.py under the ForeignKey class and method formfield here.

Now we know to use the ModelChoiceField. But what about those arguments queryset and to_field_name, and how does the “+” add icon appear?

The queryset argument should be a queryset or manager for the model your ForeignKey is to. For the following example:

1
2
class SpaceMen(models.Model):
  company = models.ForeignKey('SpaceCompany')

We are trying to build a form.Form with a ForeignKey type field to SpaceCompany we might use:

1
queryset = SpaceCompany._default_manager

I don’t know what to_field_name does. So I’ve left it out of this discussion. Don’t worry though, to_field_name, will appear later on.

How Django admin adds that “+” add icon

Django actually replaces the default select widget on the ModelChoiceField with its own django.contrib.admin.widgets.RelatedFieldWidgetWrapper. This swap occurs in django.contrib.admin.options near the top of the file in formfield_for_dbfield method of the BaseModelAdmin class. This code is interesting for two reasons:

  • It checks if the current user has permission to add a new SpaceCompany
  • The RelatedFieldWidgetWrapper requires knowledge of the admin_site

But where can I make this widget swap occur? and how do I get an instance of admin_site?

This will largely depend on how and why you are using the forms.Form in the first place. I was using the forms.Form as one of the FormWizard’s forms. So in render_template I was able to create a hook that checked the form for any ModelChoice fields and did the switch, and checked for permissions. I had a copy of the admin_site on my FormWizard thanks to this article onFormWizard in the Django admin. If you were not using ModelChoiceField in the admin, then you probably don’t need that “+” add another icon, because it is created using the reverse of admin_site.name amongst other things (more details in django.contrib.admin.widgets.py class RelatedFieldWidgetWrapper)

Python Based Link Checker

I recently needed a link checker to create a csv formatted list of all links (especially hosted pdfs) on a client site.

There is a tool called webcheck by arthur de jong which does a great job of checking all of the links on a website and creating a pretty html report.

This got me most of the way there, I could see that in the output there was a page dedicated to a list of every url that was encountered during the search, which looked like what I wanted but was formatted as html

I wrote a small file which will use webcheck’s own code to read in its stored .dat file and write all of the links to a csv file with the format:

1
path, extension, internal, errors

Where path is the url, extension is the url ending (for example .pdf, .html, ..), internal is a boolean True or False if the link is an internal link and errors is the error (for example 404, ..) if any for that link.

IE7 Bug - Absolute Div Inside Relative Div

This is a short post to document a problem I was having displaying a side bar in Internet Explorer 7.

The side bar contained some text that did not completely fill the space as desired. So I put that text on a absolute div and set the top, bottom and left attributes to stretch it out to completely fill the space. By making the parent container a relative, the absolute position would stick to it, rather than the entire screen.

This is the sidebar content

This is the second sidebar content

Progress Update for the Dailie Website

Our website entry for the Victorian Government App My State competition has been completed. Dailie, the public events sharing system is an experimental site that allows users to view festivals in Victoria that are scheduled to occur during the following week. Users can select and save details about the festivals that they would like to remember and then share those details as a calendar reminder on Google Calendar. 

The website is novel in that there is no requirement at any stage during this process for a user to sign up. Why should a user be required to fill out a sign up form to use the website? Our unique system automatically creates an account for the user, so that their selections can be saved for when they return to the site. All of this occurs without the need for any personal information. There is an option for a user to sign up for an account if they wish to use multiple computers, but this is not actively encouraged by the website. 

This freedom from sign up process has been largely influenced by our observations of the stack overflow website. We know that filling out sign up forms can be a turn off for many potential customers. Whether that be purchasing something from your website store, or using some facilities that you provide, ask yourself whether you really need the customer to sign up.