Friday, August 21, 2009

Applescripting with OmniGraffle: exporting all groups, draw some points

I haven't really spent a lot of time writing or using Applescript before. I dabbled only when I needed to tweak one that I'd found on the web. This is sensible since a web search is always a practical problem solver's first step in finding a solution. This is also due to my love of the Unix command line. If I need something quick and dirty then I write it in pipe and filter semantics with some command line voodoo using the likes of awk, sed, grep, tr, cut, paste, and sometimes add some Perl for good measure. After using Applescript for a few days and ruminating over its syntax, I think that it is crafty, compact, and extensible. Unlike most languages, it doesn't really 'do' anything. It is the laziest language I've come across and I like that. The way it works is to just literally 'tell' other applications what it wants done. It has data structures, and types (of sorts). And like many extensible languages, it suffers from a dearth of cohesive intelligible resources for understanding its use. Sure, there are books on Applescript, and lots of resources on the web, but a lot of basic things that should be covered (because of the downright weirdness of the language) are nowhere to be found. The dictionaries that are provided with each 'AppleScriptable' application provide the minimum information required with no examples of the use of particular objects or messages.

Nonetheless, this week I wrote three simple Applescripts for the OmniGraffle vector drawing application out of necessity. The first two export either all of groups or graphics of a OmniGraffle document as a particular format. This is useful if you create a large number of graphics that you want to export, or as I often do, create a large number of groups of graphics that each comprise an icon. There is no 'batch' export in OmniGraffle because they almost certainly figured that someone would just use Applescript to do it.

The third is even simpler; it just imports a comma-delimited list of value pairs as the endpoints of line segments. That is, it draws x-y coordinates as a single connected graphic.  The syntax for doing this can be learned by drawing something and then ->Edit->Copy As->Applescript....a very neat feature.

Just cut and paste the scripts below into the Script Editor and save them under ~/Library/Scripts/Applications/OmniGraffle (or OmniGraffle Pro)

OminGraffle export all groups
------------------------------------------------------------

--Copyright 2009, Sunny Fugate
--Creative Commons Attribution-Share Alike 3.0
--http://creativecommons.org/licenses/by-sa/3.0/us/
--
tell application "OmniGraffle Professional 5"
--Setup export options
set current export settings's area type to selected graphics
set current export settings's draws background to false
set current export settings's export scale to 1
set current export settings's include border to false
set current export settings's resolution to 2.0
--Retrieve the desired output export path
set myFolder to POSIX path of (choose folder)
--Get the desired output format
set outputTypeList to {"PDF", "TIFF", "PNG", "GIF", "JPEG", "EPS", "SVG", "PICT", "BMP"}
choose from list outputTypeList with prompt "Choose export format"
set exportformat to result as text
--Get the desired file prefix
set prefixDialog to display dialog "Enter a desired output file prefix or leave blank" default answer ""
set filePrefix to the text returned of prefixDialog
--Get the current document for later use
set currentDocument to document of front window
--Get a list of the canvases
set theCanvases to every canvas of currentDocument
--Use a counter for unique naming
set counter to 0
--Loop over each canvas
repeat with aCanvas in theCanvases
--Make sure that the current canvas is displayed 
--(export of currently selected only works in the displayed window
set canvas of front window to aCanvas
--get a list of groups for this canvas
set theGroups to every group of aCanvas
get theGroups
--loop over each group
repeat with aGroup in theGroups
get aGroup
--Set the selection of the window and save / export
set selection of front window to {aGroup}
save currentDocument as exportformat in POSIX file (myFolder & filePrefix & (counter))
set counter to counter + 1
end repeat
end repeat
end tell


OmniGraffle export all graphics
--------------------------------------------

--Copyright 2009, Sunny Fugate
--Creative Commons Attribution-Share Alike 3.0
--http://creativecommons.org/licenses/by-sa/3.0/us/
--
tell application "OmniGraffle Professional 5"
--Setup export options
set current export settings's area type to selected graphics
set current export settings's draws background to false
set current export settings's export scale to 1
set current export settings's include border to false
set current export settings's resolution to 2.0
--Retrieve the desired output export path
set myFolder to POSIX path of (choose folder)
--Get the desired output format
set outputTypeList to {"PDF", "TIFF", "PNG", "GIF", "JPEG", "EPS", "SVG", "PICT", "BMP"}
choose from list outputTypeList with prompt "Choose export format"
set exportformat to result as text
--Get the desired file prefix
set prefixDialog to display dialog "Enter a desired output file prefix or leave blank" default answer ""
set filePrefix to the text returned of prefixDialog
--Get the current document for later use
set currentDocument to document of front window
--Get a list of the canvases
set theCanvases to every canvas of currentDocument
--Use a counter for unique naming
set counter to 0
--Loop over each canvas
repeat with aCanvas in theCanvases
--Make sure that the current canvas is displayed 
--(export of currently selected only works in the displayed window
set canvas of front window to aCanvas
--get a list of groups for this canvas
set theGroups to every graphic of aCanvas
get theGroups
--loop over each group/graphic
repeat with aGroup in theGroups
get aGroup
--Set the selection of the window and save / export
set selection of front window to {aGroup}
save currentDocument as exportformat in POSIX file (myFolder & filePrefix & (counter))
set counter to counter + 1
end repeat
end repeat
end tell


OmniGraffle draw line from clipboard


--------------------------------------------
--Copyright 2009, Sunny Fugate
--Creative Commons Attribution-Share Alike 3.0
--http://creativecommons.org/licenses/by-sa/3.0/us/
--
--Expect values to be comma delimited x,y with linebreak between each value
set theData to the clipboard
set AppleScript's text item delimiters to (ASCII character 13)
set valueList to every text item of theData
--set numberString to "{"
set numberList to {}
set AppleScript's text item delimiters to {","}
repeat with value in text items of valueList
--stupid extra repeat which never repeats to emulate a repeat 'next/continue'
repeat while true
try
set x to item 1 of text items of value as number
set y to item 2 of text items of value as number
on error theError number errorNum
exit repeat
end try
set numberList to numberList & {{x, y}}
exit repeat
end repeat
end repeat
tell application "OmniGraffle Professional 5"
tell canvas of front window
make new line at end of graphics with properties {point list:numberList}
end tell
end tell

Wednesday, December 24, 2008

Astronomical energy density is key to becoming an interstellar species

I've been thinking recently about the actual energy costs of our consumer culture. The energy argument for most of what we do is concerned primarily with economies of scale. The idea is that by increasing the number of a given good we decrease its unit cost. My first question is: how are we measuring cost? Monetary cost? That doesn't seem very objective. How about total energy cost? And I do mean the whole process, not just some arbitrary human-defined subset of the process, like the cost of a cheeseburger being computed as just the cost to grill it.

What if we address the actual energy cost in say, producing, shipping, and cooking a domestic chicken and then dealing with the refuse in our conventional way. I suspect that the actual energy cost for just maturing the chicken is significant. If we compared it to the way in which a chicken lives in a state of nature when there are no humans to guide the process we would find that the energy gap is enormous. An ecology is pretty damn efficient in terms of energy use. Everything is useful to the ecosystem, and nothing goes to waste. For human use, the chicken would be a far lower energy cost if I were a hunter-gatherer and had hunted, killed, cooked, and eaten the bird myself. Our process doesn't achieve any efficiencies above this. In all likelihood, our process is abysmally inefficient when compared to an ecology. Our economies of scale just decrease this substantial difference.

So what is it about our methods that allow them to be successful? If the energy costs are so much greater, how are we able to accomplish anything? The answer is obvious. We inject our abundant energy resources into our manufacturing and production processes to speed things up. Currently that energy is primarily in the form of petroleum. Petroleum has a far higher energy density than the solar collected by living plants. We speed up a process by adding gobs and gobs of energy to it. This allows us to make tremendous progress in respect to human goals whereas ecosystems change at a leisurely pace, slow but incredibly efficient. Left alone (and free from catastrophic disaster) earth's ecosystems would far outlive any existing human system. But the processes by which biological systems evolve are as slow as they are efficient. If we didn't bootstrap ourselves using available energy we wouldn't have been able to do the things that we have done. Abundant and cheap energy enables human innovation.

So, we are burning through our low-density energy resources at a frenetic pace, a pace which quickens each year. We are on an asymptote of energy usage (and an asymptote of innovation). The possible failure modes of such meteoric increases can be seen in examples posed by nature (earthquakes, floods, hurricanes, volcanoes), or by the catastrophic failures of human systems (dam failure, exploding circuits, overpopulation and disease). The possible failure modes of unchecked growth are just as abysmal as our inefficiencies. My prediction is that we must, nonetheless, continue to ride the asymptote. And that if we peak in energy usage and roll-off or alternatively stabilize, then we will either crash and die off quickly, or live alone and sequestered to our dinky little speck of the galaxy. The reasons are manifold.

Clearly we can become much more efficient in doing what we do. If we approached ecological efficiencies and we stopped finding new ways to use energy, human energy usage would stabilize. If at the same time human populations were to stabilize, we would probably begin decreasing our overall energy usage. This sounds like exactly what we should be doing, decreasing our energy dependence by increasing efficiencies and stabilizing our populations. The problem is not the efficiency gains or the possibility of sustainable energy use. These are both good. The problem is that such a scenario makes no stipulation that we a) find new ways to use energy, and b) find new energy sources.

If we fail to do these two things then we will fail to leave this solar system. Period. If we fail to ever leave the solar system, this is a terminal species failure. The sun dies and then we die. Interstellar travel is necessary and the sooner we embark, the better. Low-density energy sources won't cut it, but they currently fuel our technological endeavors. These endeavors must become ever more fantastic or we risk the slow death of a species stranded on a lonely planet far from the nearest interstellar pub.

The energy cost of interstellar space travel is quite literally, astronomical. I suppose if we don't care how fast a colony reaches their destination then the energy required at first appears quite minimal. But this presupposes that a) it would be acceptable to take tens of thousands of years of travel time, and b) that somehow such a ship will sustain life in the void between solar systems for such an incredible duration. There is a great novel by Robert Heinlein that explores the likely failure of such a slow moving ship (Children of the Sky). The results would look something like Mad Max but where everybody is insane (even the law enforcers), the Manual of Astrophysics is treated as a book of analogical gospel, and the ship IS the universe.

So the scenario of low-energy interstellar travel is not a likely one. At the other extreme, we would prefer to reach another habitable star system with a portion of a human lifespan. Even if we choose one of our nearest stellar neighbors (Alpha Centauri), this means we would need to reach speeds approaching 10% of the speed of light giving us a travel time of around 50 years. The energy required for such a feat for even a very small craft is quite large. The Voyager I spacecraft left the solar system traveling at about 38,000 mph, putting it at Alpha Centauri distance in only 80,000 years. Clearly we have to move much, much faster to achieve speeds necessary to be successful in interstellar travel. 40 years would be nice. We would need to achieve (and decelerate from) speeds of 134,120,000 mph and provide 40 years of energy to sustain the lives of several hundred people. Achieving the speeds necessary is the easier part of the problem.

Clearly, we need some fantastic, astronomically-dense energy sources in order to travel unreasonable distances. Nuclear fission or fusion might work. The energy densities are orders of magnitude greater than those of chemical reactions (including the chemical rockets we currently use for extraterrestrial travel). We will require some very smart engineering to use these energy sources safely over a long journey. But right down here on the ground we will need to have already developed these technologies for widespread use. This means that we must continue to innovate and to find new and ever more fantastic uses for energy. It means that we must continue to increase our demand for energy by orders of magnitude and fuel this innovation. We need to ride the asymptote or we won't ever be able to leave. We must find and use new energy sources and technologies terrestrially to fill the very large energy-gap between us and any expectation of interstellar space travel.

Conservationism is still necessary. Efficiency is absolutely necessary, and becomes even more necessary as energy densities and power generation capabilities increase and we get closer to our technological goals. We must enable our species to use energy at an ever increasing pace. If our energy usage were to taper off now, we wouldn't likely ever have the ability to create the energy technologies necessary for interstellar travel. Such a decrease in energy usage would be an indicator that we had failed, terminally. I hope this won't happen. I think that unless catastrophe strikes (asteroid impact, thermonuclear war, bird flu kills too many people, zombies eat all of my neighbors), we will continue along our asymptotic energy consumption curve. I don't think the alternative is a viable option. We have to.



This indicates that we shouldn't be concerned so much with how much energy we use. Energy use is good, really, so much as it drives innovation and isn't just due to stupid human engineering deficiencies. It is also impossible to proceed if we are using low-energy-density bio-fuels. High-energy physics experimentation requires significant fractions of our current energy production. Future experiments will require larger energy resources still. Current power sources won't cut it. We need to replace petroleum, coal, and similar bio-fuels as soon as possible. For the future, they are useless. For now, they pollute and contaminate and prevent forward progress by maintaining energy scarcity and maintaining high energy costs. That energy costs have recently increased is a sign of our current failures. We are continuing to innovate, but our energy sources are not keeping pace. They are slowing us down. If this continues over many decades, it will be our first indicator of a potentially terminal species failure.

If we don't make major breakthroughs in astronomically high energy density technologies or we choose to curtail the research necessary to do so because we continually find new petroleum reserves or continue to invade unfortunate petroleum rich nations (or planets) ... it will take us an astronomically long time to innovate ourselves off of the planet and out of the solar system. If this happens, we will be here a very long time, all the while continually screwing up the efficient clockwork of Earth's ecosystems.


Some references used:

Tuesday, October 7, 2008

Computing Subversive's Bill Of Rights


Have you ever been told by an employer or academic institution that you MUST only use a specific hardware, operating system, or software solution? The reasons given are manifold and sometimes even appear rational and reasonable. Justifications that I have heard are: "We only want to support one system." "It is not allowed to use unsupported systems." "We cannot pay for support for any other system." "We don't know how to administer and support that system." "We don't know how secure the operating system that you want to use is." "There is no vendor contract or support for that software." "It might be spyware/malware/freeware/open-source." "It must be approved first." "We have an exclusive contract with a company that only provides their craptastic solution and the contract doesn't allow us to use other systems."

Even though the people carrying out the policy decisions of your company have every reason to suspect that your unsupported solution may be more secure, robust, or proficient than what they are using, they don't defend you. They only care that their costs 'appear' low or that there is an appearance that things are 'secure'. They want to legally protect themselves from you and the threat you pose by being a user of computing resources. You don't pass go. You don't collect $200. You are stuck with the shit you are given or you have to go through a painstaking process of proving one exception at a time that you have adequately prostrated yourself in the eyes of the policy managers. Then you might be able to use your unsupported system.

I am one of these subversives. I am a delinquent in the eyes of the policy mandate-ers with their cheeky pocketbooks, corn-fed contractors, and indignant securitizing homogeneity enforcers. I have been successful at using my choice of hardware, software, and operating system. I am able to do this because I am tenacious and because I demand that the computer systems that I use be flawless to the tasks that I have at hand. I am extremely proficient at my job and my use of computing systems. I outright refuse to accept any force-fed least-common-denominator solution.

My company has numerous policies setup to stop me. They want me to use any Microsoft supported version of Microsoft Windows and I have to always, always spend extra time justifying why each hardware purchase is not using the cheapest available solution. I abandoned the Microsoft Windows playground during my sophomore year as an EE student shortly after discovering the unnerving stupidity of Microsoft's basic design principles. I then immersed myself in world of Linux distros and command shell environments. I started my first post-graduate job expecting to use the most customized, specialized, and secure computer systems on the planet. And...I then quickly discovered that I was expected to throw away all of my hard-boiled Unix experience and to use a child's toy.

Ok. So you get that I am bitter. I get more bitter every time I am expected to justify myself. This happens every few months. Some new policy is born that has more or less ambiguous language that says I must not use what I am using. It will be taken away unless I can justify its use. Further, that I am not allowed to justify its use using an argument of personal preference or efficiency. And it doesn't matter that nothing has changed on my end. That the same justifications apply. I jump through the paper hoops of fire and navigate the gauntlet. I didn't choose to play a game of "hot lava" today, but am hop-skipping over imaginary flames nonetheless.  I can never guarantee that my efforts will be successful. I could end up with barbecued feet and an empty tool bag full of Fisher Price toys and a Dilbert etch-a-sketch to replace my sophisticated arsenal of computing tools.

I think that the problem is, however, far deeper than my unrest and unease. The problem is one of a large institution making a definitive choice of a specific implementation of a computer system, when, by definition each of these Turing machines is fully capable of emulating the others. The difference being in user familiarity, in implementation and user interface details, in their level of proprietary or open design, in their methods for product testing and making guarantees. Sure, I understand that an organization has needs, and when it needs one, an organization should acquire a large petaflop computing system and use it for boiling eggs or performing network and computing security tasks. But in respect to 'personal' computing, an organization doesn't use these, individuals use personal computers. I use personal computers. I might access mainframes, but my daily tasks are done right here in Sunnyland. And in Sunnyland I need a computing system built to the oddities of my brain, my experiences, and my tasks.

Even if the organizational organism itself uses a personal computer, it shouldn't ever specify one for you. Clearly you will use a personal computer in a very different way than an organization organism. You have hands! It would be slightly better if it were your office-mate or next door neighbor telling you what software you should run or what type of computer you have to buy. But even this is complete nonsense. Just because you sit in the same cubicle or live on the same street gives someone no insight into your cognitive abilities and peculiarities. If I've got a different driving style than you and am most efficient using a 6-speed manual transmission, I should damn well be able to..no..I should have the right to choose a the manual over any automatic.

So, you are reading this and being a business owner, or policy enforcer, you think that I am out of my fucking mind. If you let your employees drive whatever computing vehicle they wanted, you would not be able to afford the cost! You wouldn't be able to guarantee computer security! So, yeah, I'm not talking about cost. If you want to put a restriction on how much I am allowed to spend, do it, but if I am a expert and expect the best tools I will either quit my job or purchase them for myself. If I am expected to perform at my peak performance within the bounds of a budget I must still be able to choose the computing environment that fits my specific needs. And if you are smart you won't use cost limiting as a method to get me to use a pre-chosen solution. Clearly, if you are doing this, you've missed the point.

And as for the 'security' arguments...If you are only doing security on the host level...you've lost. If you want secure personal computers, the only way to do this is to educate your population! You don't tell your scientists that they can't use a hammer because they might smash their fingers! Just teach them how to hit the nails without damaging themselves, their tools, or their colleagues. So you don't have that type of security expertise in house? Pay for external security firms to educate them for you. You'll will be better off doing this instead of trying to keep up with the incredibly fast-paced world of software.

The proposal that I am taking my sweet time in getting to is this: A Bill Of Rights guaranteeing an individual free choice of human-machine interface. Give the individual the inalienable right to choose for themselves the type(s) of computing environment(s) that work best for their tasks. I am sure that this is the right approach. Our organizations, if they are mandating a specific environment, do not have your best interests at heart. Your health and cognitive proficiencies are being used against you. They are wasting you. They are throwing away tens of thousands of your precious life hours in order to fulfill some pre-ordained requirement created by financiers of big-business or big-government. I do not have the time to have my life wasted so blithely. I should have the right to work as proficiently and efficiently as I know how. The real screwed up part of this is, we are currently the minority. Most computer users don't care about computing environments because they don't know enough about their computing environments to give a damn. So when a bunch of don't cares are thrown on a balance scale against individuals organization make up any damn thing they choose and throw away their most proficient computing resources. Us!

I don't expect such a computing subversive's bill of rights to be mandated for all companies, except in the particular case when that company is the U.S. Government. As a taxpayers and employees we must repair this problem or risk everything by steeping our best and brightest in the mud of mediocrity. Just think this: if you were an Olympic runner, would you be able to perform if forced to run in flip-flops? Just remember, in respect to human-machine-interface, your flip-flops may just be my rocket-boots.

Some related examples of writing on computing consumer rights. Note that all of these are concerned with consumer rights in respect to product quality. These are necessary protections but I believe are related to basic product guarantees rather than providing users with the ability to choose HMI specifics.

I believe that for any of these usability and accessibility guidelines to make a difference, first and foremost, a user of a computing system must be able to choose an optimal solution for their individual characteristics.