Saturday, April 30, 2011

Umple tutorial 2: Basic state machines

This is the second tutorial on the Umple model-oriented programming language. The first tutorial was on attributes and associations.

The following is a UML state machine diagram for a hypothetical garage door opener. Keywords are shown in red, and state names are shown in blue.

The main states in the diagram are Closed and Open. Pressing a button causes the garage door to start opening (if it is closed) or to start closing (if it is open). Upon entry to Opening state, a signal is sent to the electronics to actually run the motor; the inverse happens upon entry to Closing state. There is a safety interlock: If the button is pressed when the door is closing, it reverses direction and opens again. There is also a second safety interlock: If the button is pressed to close the door, the closing will not commence if an obstruction is detected. There is also a light control; when the button is pressed to open the door, it turns on the light. When the safety interlock causes a closing door to reverse and open again, the light flashes before going on. The light turns off a minute after the door has finished opening.

The following is how you would program the above in Umple:

class Garage {
2    Boolean entranceClear;
3    GarageDoor {
4      Closed {
5        entry/{stopMotor();} 
6        entry/{triggerEnergySaveMode();}
7        exit/ {triggerNormalEnergyMode();}
8        pressButton -> /{turnLightOn();} Opening;
9      }
10     Opening {
11       entry/{runMotorForward();}
12       openingCompleted -> Open;
13     }
14     Open {
15       entry/{stopMotor();}
16       do {wait(60000); turnLightOff();}
17       pressButton [getEntranceClear()] -> Closing;
18     }
19     Closing {
20       entry/{runMotorInReverse();}
21       closingCompleted -> Closed;
22       pressButton -> /{flashLightOn();} Opening;
23     }
24   }
25 }

Copy and past the above into UmpleOnline (removing the line numbers) and generate Java code to see what happens.

Here's an explanation of the code:
  • Line 1: A state machine is defined in a class. There can be more than one per class.
  • Line 2: This is an ordinary Umple (UML) attribute. See Tutorial 1 for a discussion of attributes. One thing to note is that this declaration will result in methods getEntranceClear() and setEntranceClear() in the API of class Garage. The former is called on Line 17.
  • Line 3: A state machine called GarageDoor is being declared. In many respects a state machine functions as an attribute. The API getGarageDoor() is generated that returns an enum GarageDoor; the values of that enum will be each of the states.
  • Lines 4, 10, 14 and 19: These are the states of the GarageDoor state machine. The first state listed (on Line 4) is the 'start state'. When an instance of the class Garage is first created, it will therefore be in Closed state.
  • Lines 5, 6,. 11, 15 and 20: Upon entry into a state, these actions are to be performed. Arbitrary code can be placed in the parentheses. Such code will be passed through to the base language. Here we have used Java.
  • Line 7: Upon exit from a state, this action is to be performed. Again, it is arbitrary code.
  • Line 16: Whereas entry and exit code above is supposed to be 'instantaneous', i.e. to take no noticable computational time, the code specified in the 'do' block on this line can take an extended period. It therefore executed in a separately forked thread so as not to hold up the behaviour of the main state machine.
  • Lines 8, 12, 17, 21 and 22: These represent the state transitions. In the diagram shown earlier, they are the five arcs between pairs of states. The destination state of the transition follows the ->. Each event name on a transition is generated as a method in the API. Even through there are 5 transitions, there are only three possible events, since the transitions from three separate states respond to this event.
  • Lines 8 and 22: This shows a 'transition action'. This code is executed before transitioning to the new state.
  • Line 17: This shows a 'guard'. A guard is a Boolean expression; the transition to Closing will only be taken if this evaluates to true. The guard expression tests the Boolean attribute declared on line 2.
How do you make use of the above to build a complete system? You would do the following:
  • Write code somewhere else to call the event methods pressButton(),  openingCompleted(), and closingCompleted().
  • Write methods for each of the actions the state machine will call, such as stopMotor(), called in line 5 of the above Umple.
  • Write methods that call setEntranceClear() to manipulate the EntranceClear attribute  defined on line 2.
Why would you want to program a state machine in Umple, rather than writing the code directly in java?
  • Umple provides greater abstraction
  • You will have to write many fewer lines of code. The above 25 lines of Umple translates to over 180 lines of Java.
  • You are much less likely to make mistakes because error-prone code is generated for you.
  • You can model in UML and have a one-to-one representation in Umple.
Note that I have shown you only a small portion of the power of state machines. As in UML, in Umple you can nest state machines, you can have 'concurrent regions', and you can have such niceties as transitions to history. Actually, I am unaware of any other code generator for state machines that can handle as much of UML notation as Umple can.

And you can go far beyond that. With Umple you can have in the same file as your state machine UML associations, ordinary Java methods and many other things. Furthermore, you can compose a state machine from many separate files using Umple's mixin mechanism.

One final point: The state machine diagram here is discussed further in my book. Object-Oriented Software Engineering: Practical Software Development Using UML and Java.

Friday, April 29, 2011

Will the NDP get us closer to proportional representation? Here's my suggestion

With the latest polls, such as those from Nanos and Ekos, showing the NDP is strongly positioned to challenge a Conservative minority, one of the NDP's long-term goals may have a chance for life.

That goal is proportional representation. It turns out to be also a goal of the Green Party, which I support.

In the distant past, when there were two main parties, our Westminster-stule first-past-the-post election system served just fine. However it prevents strong and legitimate national parties in third, fourth and fifth place from having their fair share of influence, and has shut out the Green's entirely, despite the fact that they had the support of a million Canadians. It also disproportionally increases the influence of regionally focused parties such as the Bloc Quebecois.

True proportional representation would rectify this. However most observers feel that we wouldn't want to throw away the concept of local MPs to achieve that. The most popular alternative the therefore a mixed-member system, where additional parliamentarians are chosen by the parties so that the total representation in the legislature matches the popular vote. However when a referendum was held in Ontario on this topic, there was public backlash against two aspects. The "no" forces didn't like the idea of the parties appointing 'party hacks' who weren't directly on the ballot; and there was also a backlash against increasing the size of the legislature. Additionally, the public just didn't understand the system since they would have to vote twice, once for their local member and once for their preferred party.

Here's what I propose:

  • Firstly, at the next redistribution of seats, a fixed proportion of seats in each province should be set aside for the 're-balancing' members who would represent the under-represented parties. Parliament would not be increased unduly to accommodate this.
  • Secondly, the seats for under-represented parties need not be in sufficient numbers to result in a complete match to the popular vote. Perhaps 10% of seats could be used for re-balancing.
  • Thirdly, the re-balancing members would automatically be those with the highest percentage of votes in existing electoral districts, but who did not win. So, for example, If the Green Party was given 14 seats, to better represent their proportion of the popular vote, then the 14 Green Party candidates getting the highest percentage of votes locally, but who did not win, would become MPs.

The advantages of such a system would be the following:

  • People would have less incentive to vote strategically since their vote would count in two ways, even if their vote did not result in their chosen candidate actually winning. Firstly, it would influence the overall national or provincial totals and thus determine which party gets the re-balacing seats. And secondly, since it might help their chosen candidate get a seat even if they come second.
  • The elected MPs would be known on election night.
  • All MPs would be directly elected; none would be appointed by parties.
  • Experienced MPs who lose tight races, may be able to retain a re-balancing seat. We need experienced people in parliament.
  • National parties would benefit at the expense of regional parties. The latter tend to be divisive.
A disadvantage of my system would be that some electoral districts would have two MPs, resulting in a perception of undue influence. But it seems to me this is the lesser of two evils. With the current system there is already a divergence of influence: Distrcts with Government MPs have more influence, and districts with opposition MPs have less influence.

Many will argue that any proportional system will result in perpetual minority governments or coalitions. I used to think this would be bad. Stephen Harper rails against minorities and constantly calls for a 'strong' majority. However, minority governments and coalitions have worked well in many Western democracies.

Here's how the re-balancing of seats in my system might have worked in the last parliament, if 10% additional seats were used for this purpose (i.e. 31 seats). My actual proposal calls for no additional seats, but rather that electoral districts be expanded to keep the number of seats the same, however, I can't know who would have been elected in such a different electoral map:

% % Popular Percent Resulting Resulting
Seats Seats Vote Below Rebalancing Seats Percent seats
Conservative 143 46.4 37.6 143 42.2
Liberal 76 24.7 26.2 1.5 3 79 23.4
BQ 50 16.2 10 50 14.7
NDP 37 12.0 18.2 6.2 13 50 14.7
Independent 2 0.6 1 0.4 1 3 0.8
Green 0 0.0 6.8 6.8 14 14 4.2

The main beneficiaries would have been the NDP which would have gained 13 seats, and the Green Party, which would have gained 14 seats (up from zero). The Conservatives would have still had a proportion of seats that was considerably greater than their proportion of the popular vote, but at least the other parties would have had a somewhat fairer representation.

The biggest loser in my system would have been the Bloc. However that seems fair: The Bloc has had far more influence than their proportion of the national vote would warrant. Note also that my system does allow for an extra independent MP; again, this would be the one who came closest with the highest percentage of votes, but didn't win. A modification of my system might only allow actual parties to gain seats in this manner, or only independents that got at least 30% of the vote in their district.

For earlier posts on the current Canadian Election, see:

Wednesday, April 27, 2011

Umple status update: The Umple open source version is ready to use

Development of the Umple model-oriented programming technology continues at a rapid pace. We have completed open-sourcing the vast majority of Umple, including the compiler, the Eclipse plugin and UmpleOnline.

Current developments

Recent additions include better support for Interfaces. The signatures of base-language methods are now parsed too.

Here's what is coming up:
  • We are moving from our own parser to an XText-based parsing technology, which generates the metamodel in Ecore
  • We are adding a tracing sublanguage to allow generation of tracing (dynamic analysis) directives from within a model
  • GUI generation from a model is being added. This was created some time ago for Julian Solano's thesis, but we are now in the process of open-sourcing the work.
  • We are working towards adding C++ code generation.

Links to the Umple project

Here are some handy easy-to-type links to various aspects of the Umple project. -> The google code site where we are hosting Umple. If you have a google account you can become a contributer -> A quick link to UmpleOnline, where you can try out the language. -> A wiki maintained on the Google code site where help and documentation resides -> The system where we are maintaining our list of issues. -> Blog posts from Tim Lethbridge's blog that refer to Umple. -> The Umple mailing list. -> Quick link to the root of the source code tree for Umple -> The Cruise Control continuous integration build server for Umple. Any time changes are committed to Umple, a build will automatically occur, and the results of the build will be visible here. ->  Results of the automatic testing of Umple. -> The umple home page we maintain on our own servers.

Previous posts on this topic:
To look back at my previous Umple posts, see the following:
January 2011 status report
Tutorial on attributes and associations in Umple
Overview of Model-Oriented Programming

Tuesday, April 26, 2011

The Anyone-But-The-Conservatives forces are turning this into an interesting election

Wow, the surge towards the NDP in the Canadian election is simply amazing, it reminds me of the surprise we Ontarians woke up to on Sept 6, 1990 when Bob Rae's NDP stunningly claimed a majority in the provincial election. I doubt that will happen in this federal election, but political shockers are not unknown. Clearly it is the anybody-but-the-Conservatives (ABC) sentiment of 60% of Canadians that are driving this force.

The latest EKOS poll is giving the NDP 100 seats, which would make Jack Layton opposition leader, and with a good chance of becoming prime minister following a quick defeat of of the Conservatives in the House of Commons.

I would probably never vote for the NDP, they have too much left-wing ideology in their grass roots, much like the Conservatives have too much right-wing ideology. However, I would very much prefer the NDP to the Conservatives.

The things I would fear about an NDP government (formed after defeat of the Conservative budget) are:
  • Lack of attention to reining in the deficit
  • Anti-corporatism, leading to economic damage to the country
These, however, are almost certain to be tempered by whoever would support them in a coalition, or on a vote-by-vote basis.

The other possible outcome of the election is a conservative majority, and I fear that far more, for the following reasons:
  • Harper has an explicit platform proposal to chop the per-vote funding of political parties. This can only benefit parties with strong ideologies and wealthy supporters, i.e. his own, that can drum up more individual donations.
  • Harper comes from deep right-wing roots; regardless of what he says, he really doesn't like publicly funded services such as our medical system, the CBC and many others. He admires the US Republicans, and dislikes gun control.
  • He believes in populism, as opposed to evidence-based policy, so supports nonsense like putting more people in prison instead of fighting the cause of crime. Again, this is following the lead of the right wing in the US, despite it being an obvious failure.
  • He cares very little for the environment, claiming that we must focus on the economy. However the economy will be shattered by future environmental problems unless we tacked these problems right away.
  • The Conservatives are an embarrassment to Canada on the international stage. We lost our landing rights in the UAE due to incompetent diplomacy; we were trounced in the Security Council vote, and we are a laughing-stock on environmental issues, we have withdrawn funding from agencies supporting development in Africa.
  • They show contempt for democracy by not being open with Parliament and not actively trying to work with the other parties, as a minority governing party should.
  • They don't have intellectual depth, something made obvious by the fact that Harper muzzles his candidates so they don't accidentally say things that might embarrass the party.
The sad thing about the ABC movement is what may be happening to the Green Party. It'll be interesting to see how much of the environmental and protest vote moves to the NDP (Frankly I don't think the NDP has a very good environmental track record). However the youth vote could be the wildcard. It seems certain that the youth vote is under-counted in the polls since many of them don't have home phones. If Rick Mercer's rant brings them out in droves, many will vote Green I suspect. I am very impressed by my local Green candidate Jean-Luc Cooke, and will certainly be voting for him; the local Conservative incumbent is, to me, an embarrassment.

Tuesday, April 19, 2011

Is Sugar Toxic - an interesting article exploring a key medical issue

I highly recommend this New York Times article by Gary Taubes entitled "Is Sugar Toxic?"

One always hears the dogma that fat is the bad thing in one's diet. This article is a highly readable summary of the argument that in fact it is sugar, not dietary fat that is bad, and not just for causing diabetes and obesity, but cancer too. For example, he discusses the point that cancers used to be rare in the Inuit (who ate lots of fat, but little sugar) but have risen since their sugar intake rose.

I predict that eventually, this issue will be finally settled, and the dogma about fat being the evil will be put to rest. It will be interesting at that time to see how many lawsuits are filed against all the health agencies and corporations that have for decades railed against fat in the diet, while ignoring sugar, and against the industries that promote sugary diets.