Wednesday, December 18, 2013

Volume of a Tetrahedon

In this article I give a rough outline of a derivation of the volume formula for a tetrahedron, given its four vertices.

Any set of three points in 3D are co-planar. If they are not co-linear, then they uniquely define a plane. They also uniquely define a triangle. With polygons of more than three sides/vertices, you need to specify which edges are drawn and which are not.  In a program, you might imply the edges according to the ordering of the points, but the order then is a means of indicating which edges to draw. You could not simply draw all of the possible edges and get a polygon, generally. But with a triangle, you take every pairing of points and draw an edge between them.

If you add a fourth point which is not in the same plane, you now have a tetrahedron (tretra = four)—a four sided polyhedron which is uniquely defined by four points. As in the case of the triangle, you draw an edge between every pairing of points. The number of combinations of 2 points is    
and so there are 6 edges.
A tetrahedron is a special case of a slanted pyramid. The same volume formula applies, namely,
                                                          
In order to use the formula, we must pick a face to serve as the base.  We choose the face with vertices P1, P2, and P3, in the above illustration. (It doesn't matter which ones as long as you're consistent.)  We need to calculate the area of the base and find the height of the pyramid. The height is the distance from P4 to the plane defined by the base points (the measure is taken perpendicular to the plane).

First we find the area. A well known formula for finding the area of a triangle given the length of two sides, say a and b, and the included angle, say θ,  is      
(With some minor trig you can figure this out, but if you just want to see it proved, see Area of Triangles Without Right Angles [1].) The cross-product comes in handy here since
where v and u are vectors and θ is the included angle. Thus, the area is
To find the distance from P4 to the base plane, we first find the plane. The equation of a plane can be expressed in terms of a normal vector and any point on the plane. The normal vector for our plane is
and the equation of the plane is
(This is a 3D analogue to the point-slope form of the equation of a line, albeit, it also resembles the general form.)

The height from the plane to P4 is the component of the vector (P4 – P1) which is in the direction of the normal vector, namely ([2], p. 679),

This leads to the volume formula
Sources:
  1. Math is Fun, Area of Triangles Without Right Angleshttp://www.mathsisfun.com/algebra/trig-area-triangle-without-right-angle.html
  2. Stewart, J., Calculus: Early Transcendentals, 3rd Ed., Brooks/Cole Publishing Company, 1995

Saturday, December 7, 2013

Convective Heat Transfer: Buildings in the Cold

Engineering Toolbox has an equation (here) for calculating a convective heat transfer coefficient:
   
where v is the wind speed in m/s and hc is in W/(m2 K).  When I first found this equation I thought that I had a way to calculate the hactual/hNW ratio more accurately than in my earlier post about "wind chill" on buildings.  As I reviewed my previous post however, I realize that this is awkward to compare.  The ratio that I would obtain using the above equation is hactual/hNW = 2.833 (this is comparing convective heat transfer with 15 mph wind versus no wind).  To see that something isn't quite copacetic, observe that if we use the equation used there, namely,

       TWC = TS – (hactual / hNW)(TS – Tactual)),

with 2.833 for the ratio and 88 °F as the skin temperature, we obtain

    TWC = 88 – (2.833)(88 – (–31)) = –249 °F,

the implausibility of which suggestion I am satisfied. Radiative heat loss may be complicating the situation. But whatever the reason, the wind chill equation makes no promises to us about its applicability to anything other than human skin.

The current day wind chill index is a bit of a backward way of looking at things. Notice that it is called an index. It is not a physical quantity. It is a measure of a phenomenon. The wind doesn't make the temperature outside colder.  It does make bodies which are warmer than the air loose heat faster. But be cautious with relative terms. Something does not really loose heat "faster".  Rather, it may lose heat "faster than something else". It is more helpful (to the understanding) to say that the absence of wind results in a building loosing heat less quickly than a wind swept building.

I say this because of the way one sets up the steady state heat equations. We set the temperature of the outside of the outer air film to be equal to the ambient outdoor temperature. And we assume a small air film with R value something like 0.15 so that the outside surface of the building is not much different in temperature than the ambient air temperature. However, this neglects the affects of sunlight. In the absence of wind, sunlight has the most beneficial effect to the exterior of a building (in winter). By heating up the exterior surface of the building, the thermal gradient across the envelope is less—there is less temperature difference from inside to outside—and therefore the rate of heat loss through the envelope is reduced. The benefit of sunlight is kept in check by the convection on the outside of the building. As the exterior of the building gets warmer, the temperature difference between it and the air increases, which increases the rate of heat loss from the surface of the building.  If there is significant wind, it will mean a larger convective heat transfer coefficient (relative to no wind) and therefore raise the rate at which exterior surface loses heat, which in time reduces the temperature difference between the air and the exterior surface.

Hence, in modeling a steady state temperature loss, the coldest the outside temperature of the envelope should be modeled at is the ambient outside temperature; this is the worst case scenario. To see that this is true, notice that at this point there is no temperature difference between the ambient and the exterior surface. Considering the convective heat transfer equation, this means there is no heat transfer. Thus,

       q = hc·A·(TS - Tair) = hc·A·0 = 0,

by which observation, with some thought, you might realize that this means the outside surface is necessarily warmer than the ambient air temperature, by at least some amount. Otherwise your building would stop losing heat, which would be very efficient indeed if it was possible!

If you want to model the benefits of reduced wind conditions and sunlight, you might model the exterior temperature as being warmer than ambient.  In short, wind lessens the benefits of sunlight to the thermal performance of a building envelope, but it does not make the exterior colder than ambient.

What I am saying is that the reason why heating requirements may be higher in windier places is because the less windy places are receiving (and retaining) a greater amount of benefit from sunlight and therefore have lesser heating requirements.

If Not "Wind Chill", Then What?


If the wind chill index is not totally real (though it is fine for its intended purpose), what should we be considering? The physical quantity that really matters is called heat flux. Heat is the transfer of thermal energy (1, p. 53). Of course, when a transfer is happening, it is happening at some rate.  So you can speak of loosing or gaining heat at a rate specified in Watts, kilowatts, Btu/h, etc. Heat flux is the rate of thermal energy gain/loss per unit time and area.  Possible units of measure include W/m2 and Btu/(h ft2).

Solar radiation is often expressed in these units.  Note however, that to model the effect of the sunlight effectively requires you to determine the fractional portion of the incident radiation which is actually converted into thermal energy. You also need to scale the result by the cosine of the incidence angle (measured perpendicular to the surface normal) since a non-direct (non-normal) angle "spreads out" a given amount of radiation over a broader area.

One of the merits of working with heat flux, is that you can compare a tendency to heat loss between objects of varying surface area. A really large building might be losing heat faster than a small building even though it is better insulated. If you wanted to compare their tendency to loose heat on a kind of level playing field, you would divide the rate of heat loss by surface area.  Your result would be heat flux—actually, average heat flux.

If you want to calculate heat flux (φ), divide area out of the convective heat transfer equation:
   
(For the convective heat transfer equation, see ASHRAE Fundamentals chapter 4 or [1].)

But we have now touched on an important issue in energy efficiency: bigger isn't always better. If you can reduce your volume, you reduce the amount of stuff to heat.  (This is most pertinent in spaces with redundant air space, where the hot air rises to the top and is useful only for increasing the rate of heat loss through your roof—and when I say useful, I mean not useful.)  If you reduce your surface area, you reduce the area through which you lose heat. If you don't need big, go small. After you decide the space you really need, configure the space to reduce exterior surface area, subject of course to meeting the functional requirements of the space.

An interesting case of balancing surface area with other considerations is in solar energy greenhouses (SEGs).  A long building a few meters wide with a broad glazed wall facing south (up here in Canada) allows the building to maximize the amount of sunlight captured and stored in the north thermal mass wall. A square footprint would reduce the surface area for a given volume, but it would result in redundant air space. (Plants at the south wall would be too far from the north wall to benefit from it and the roof would need to be higher to allow the sunlight to reach the north wall.)  For more information on these greenhouses, see [2] and [3].

Sources:
1. World of Energy, Chapter 4: Transfer of Thermal Energyhttp://www.physics.ohio-state.edu/p670/textbook/Chap_4.pdf
2. Bomford, M., Solar greenhouses, Chinese-style, http://energyfarms.wordpress.com/2010/04/05/solar-greenhouses-chinese-style/, 2010
3. Love, M., The solar solution, http://www.greenhousecanada.com/content/view/1562/38/
4. Wind Energy Institute of Canada, Wind Chill Temperature Index, http://www.weican.ca/links/011101-ec-windchill-index.php
5. Engineering Toolbox, Convective Heat Transfer, http://www.engineeringtoolbox.com/convective-heat-transfer-d_430.html
6. Irvine, D., Convective Heat Transfer on a Building Envelope (Wind Chill?),  http://darrenirvine.blogspot.com/2012/12/convective-heat-transfer-on-building.html, 2012

Saturday, November 23, 2013

Rotation of Planar Regions: Polyhedron in AutoCAD

In a previous post about the angle between intersecting planes, I noted the importance of measuring that angle perpendicular to the line of intersection.  Now I want to apply a similar notion to the rotation of planar regions.  In CAD programs that support solid and surface modelling, it is common to support planar regions. These programs do much more complicated things as well, of course, but they will certainly allow you to make, say, a hexagonal region.  A hexagonal region is not only the outline of the hexagon, but the area enclosed by that outline, all of which lies within the same plane as the outline.  Making a planar region in AutoCAD is straightforward:
  1. Change to one of the 3D workspaces.
  2. Create any closed sequence of line work (sometimes called a closed path), all of which should be coplanar.  (While you can create a closed path that is not coplanar, it won't suit our purpose here and you can't make it into a region.)
  3. Type Region, select the line work and press .
  4. To see the region, change the visual style as necessary:
    1. Click the View tab.
    2. Click the Visual Styles button on the Palettes pane.
    3. In the Visual Styles Manager (which should pop up) choose a style that shows the faces (if/when that is desirable).  I'm partial to Shaded with edges, but other styles may be suitable.
      1. Notice also the settings under Face Settings that can affect the way the faces appear (or not appear).
But I don't just want to make planar regions, we want to do something with them.  I want to rotate them about a line of intersection/adjacency and make multiple regions "fit" together.  I'm going to make, well, you'll see...(at the end of the video in this post)...

Description of the Problem

Suppose we are given three planar regions A, B, and C, such that A is adjacent to B and B is adjacent to C, with all of the regions being initially co-planar with each other.  We want to rotate A and C about their "line of adjacency" with B so that A and C are adjacent to each other.

Informally, we might say that A and C are the box flaps and B is the base.  You may intuit the analogy I'm making.  We are pretending we have a sheet of cardboard cut out in an unusual shape with two creases in it which will serve as the fold lines – our lines of adjacency.  Note also that the proximal lines of A and C (the ones we want to be coincident) need not be of equal length to do the kind of folding/rotating we want to do, but if they are not equal we may not get the result we desire.

We are currently looking at our box flaps in plan view.  Suppose we continue observing in plan view and fold the box flaps (about B).  B is unchanged in appearance but A and C appear "squished" in one direction.  Or, another way to think of it, every point on A will appear to move perpendicularly toward its line of adjacency with B.  Likewise for C.  Thus,


If for some reason the proximal lines of A and C were not of equal length (as they are above), for purposes of our construction, we would need to establish points of equal distance from their common vertex.  A circle centered on their common vertex would do nicely.  In AutoCAD we can work in 3D to do this rotation, but first let's consider how we would do this in 2D.  This will be informative as to how to proceed in 3D.

First observe how the arrows at the end of the proximal lines of A and C cross each other.  These arrows are in plan view with z = 0, but the point where these arrows intersect gives us the xy-coordinates of the point where the non-common vertices of the proximal lines will meet.  (If that doesn't make sense, just go with the picture.)  Now to make our 2D plan view work, we've got to do some single axis scaling.  Here's what we're looking at:


We need to scale region A along the y-axis by a factor of A2/A1 and scale C along an axis perpendicular to the line of adjacency with B by a factor of C2/C1.  Since we are working with only a small number of points here, we can simply draw lines of lengths A3 and C3 and scale them as needed.  We move and copy the lines as necessary so that we can move the vertices of the polygons to their new positions based on the newly scaled lines.  (To scale A in the y direction you could turn A into a block and scale the y-axis as desired.  To scale C you could use the "block"  and scale method too, but you'd have to adjust your UCS line up with the line adjacent to B – use the ucs command with the OBject option and click the line you want to line up with.)  Here's the scaled result:


I used the scale command with the reference option so that I didn't have to do the indicated math myself, but AutoCAD did in fact compute A3(A2/A1) and likewise for C.  (Incidentally, this doesn't work so nice with regions, though it works fine with polylines; it's a simple matter of moving vertices along a line perpendicular to the line of adjacency.)  As for making the other views work for you in 2D – you're on your own, because right now I'm posting how to do this in AutoCAD (full version).

Rotating Planar Regions to Make a Polyhedron in AutoCAD


Making of a Polyhedron in AutoCAD from Darren Irvine on Vimeo.


Wednesday, October 23, 2013

How to Determine the Rotation Direction of a List of 3 Points in 2D

Clockwise and counter-clockwise are directions which are fairly intuitive to most of us. But if you were not so smart—say perhaps about the intelligence of a computer—how would you know whether a list of three points had been listed in clockwise or counter-clockwise order?

If you were given 3 points (in 2D) and asked this question about them, you would probably do the same type of thing I would: plot them, perhaps put numbers beside them, sort of trace the points in the air with your finger and ask yourself, "Am I moving my finger clockwise or counter-clockwise?"

For example, are these points given as clockwise or counter-clockwise?
If you figured out which direction they are numbered in (CW vs. CCW), you likely used your hands or at least mentally traced it and imagined it as (or compared it to) a movement.

Computers, unfortunately for them (fortunately for us maybe), don't have hands.  And if they did, you would have to explain to them the significance of their actions and I imagine that being a bit complicated.  Better get them to use math. Way easier!

If we draw a couple of arrows, the matter is easier to see.
What makes the above traversal of points clockwise, is that every turn is a right turn.  If I am travelling from 1 to 2 and then I turn to go from 2 to 3, I must turn myself right, or clockwise.  The direction from 1 to 2 can be stated as D1 = P2 – P1 and the direction from 2 to 3 as D2 = P3 – P2 (if you'll allow the introduction of some letters).  One way to test for whether the direction D2 is a right turn from D1 is to rotate the points so that the line from 1 to 2 is at standard position and then inspect the rotated version of D2 for which quadrant it is in.  (Implicit to the problem is that we are disallowing turns greater than or equal to 180°.  If this seems to you like weaseling or a limitation of the method, revisit the first picture and remind yourself what the question really is.)

Rotating the points produces the following (roughly).

So now it is pretty clear.  If we rotate D2 by an angle sufficient to bring D1 to standard position, we can identify a right turn by a negative y value in the rotated version of D2 (quadrant 3 or 4) and a left turn by a positive y value (quadrant 1 or 2).  What remains is a method of rotation.

Consider the complex representation of the direction vectors (where r1 and r2 are positive):
                                 
We are concerned only with direction and so the change in magnitude is not a concern.  If the imaginary part of this last number is negative, then the points are in clockwise order.  If the imaginary part is positive, then the points are in counter-clockwise order.

Note also that we have avoided any calls to trigonometric functions by using this method.  The trig functions show in the derivation as a matter of proof, but are not actually called at run-time.

Additional info: I later found a numerically less involved method in Introduction to Algorithms (Thomas H. Cormen, et. al.). Just take the cross-product, retaining only the z-coordinate (x and y are 0 anyway).  Instead of considering vectors from (1 to 2) and (2 to 3), take (1 to 2) versus (1 to 3). The determination is still made based on the sign of the sine, but now it is the sine of the angle between the vectors.

Saturday, September 21, 2013

3D Analogue to the Trapezoid (part 3)

Suppose we have two parallel polygonal faces with a non-zero distance between such that, for some pairing of vertices, every consecutive pair of edges connecting the paired vertices are coplanar. It follows that the faces joining the two given parallel polygonal faces are quadrilaterals.  At first, it might not appear that this is a sufficient condition to assert that the shape thus described is a frustum of a slanted pyramid.  In this post I proceed to prove that it is.  For the volume formula of a frustum of a pyramid (slanted or otherwise), see this previous post of mine.

I term the parallel polygonal faces the end faces and the other faces as the side faces.

Proposition 1 (Transitivity of Parallel Lines).
  1. Let P be a plane and L a line parallel with P. Every line parallel with L is also parallel with P.
  2. Let L, M, N be lines. Then, if L is parallel with M and M with N, then L is parallel with N.
Proposition 2. The corresponding edges of the polygons are parallel with each other.
Fig. 1. Partial drawing of  two parallel planes.  AC is the "bottom edge" and BD is the "top edge".  AB and CD are "side edges".  Consecutive side edges are coplanar with each other.
Proof: Assume without limitation that the faces are parallel with the horizontal plane. Since the faces are parallel, the edges do not change in proximity vertically. Consider any two consecutive edges AB and CD joining the two end faces with corresponding vertices A with B and C with D. Draw line EF with E on line AC (edge of bottom face) and F on BD (edge of top face; extend BD as necessary) such that EF is perpendicular to AC. EF is coincident with the plane of quadrilateral ABDC and so is coplanar with all of its edges.
Fig. 2. We show the construction of B'D' as a line which is coincident with BD, but this is not given as a condition in the construction. That is to be proved. At construction we take neither parallelness nor coincidence with BD for granted. Because it is the same distance from AC as the point F, however, we do know there is at least an intersection between B'D' and BD at F.

Let B' and D' be points such that AB' and CD' are of length(EF), coincident with the plane of quadrilateral ABDC, and perpendicular to AC. Then AB' and CD' are parallel.

If you want to go crazy with the details to see that B'D' is parallel with AC, see the parenthetical section below. I obviously did want to go crazy. Normal people can skip ahead.

(By side-angle-side, triangle AB'C is congruent with triangle CD'A. Thus,
Also, since the non-right angles of a right triangle sum to 90°,

                                               
Thus, triangles B'AD' and D'CB' are congruent by side-angle-side. Hence,
By alternating interior angles,
Since the angles of a triangle sum to 180°,
Hence, angle B'D'C is a right angle.  By a similar argument, angle D'B'A is a right angle and so quadrilateral AB'D'C is a rectangle and thus B'D' is parallel with AC. Since F is length(EF) away from AC, in the same plane as quadrilateral AB'D'C, on the same side of AC, it is on line B'D'.)

Fig. 3. The shape we are discussing doesn't really look like this, but how do we know it doesn't look like this? How do we know Fig. 2. isn't the one that's wrong? See rest of argument below.
Assume that lines BD and B'D' are not coincident. Both are coincident with a common plane and so are coplanar. Since quadrilateral ABDC is on an angle from horizontal and BD and B'D' are not coincident, there is some point, P, on B'D' which is below BD. But point F is coincident with both BD and B'D'. Since BD is parallel with horizontal (it is part of a polygonal face which is horizontal), and B'D' has at a point on and a point below BD (points F and P, respectively), B'D' is not parallel with the horizontal plane. But, since AC is parallel with the horizontal plane, the parallel line B'D' must be parallel with the horizontal plane (Proposition 1), which is a contradiction. Thus our (limiting) assumption is wrong and lines BD and B'D' are coincident. It follows that BD is parallel with AC.■

Corollary 1. The walls of the prism are trapezoidal.

Proof: The corresponding edges of the end faces are parallel.■

Corollary 2. Every cross-section of the prism, parallel with the end faces, has corresponding edges parallel with the end faces.

Proof: Fix any cross-section parallel with the end faces and observe that the side edges are intersected by this cross-section so as to produce a polygonal face, whose vertices and edges correspond with the bottom face in the same way the top face did in the proof of Proposition 2. The same argument, therefore, applies.■

Proposition 3. The top and bottom faces are similar shapes.

Proof: It suffices to show that the interior angles at each pair of corresponding vertices are equal. Let A, B, and C be consecutive vertices of the bottom polygon and D, E, and F be the corresponding vertices of the top polygon, respectively. By Proposition 2, DE is parallel with AB and EF is parallel with BC. There exists vertices D’, E’, and F’ which are translated vertically from the top polygonal face down to the plane of the bottom polygon. By this we obtain lines D’E’ and E’F’, in the plane of the bottom polygon which are parallel with DE and EF, respectively. By Proposition 1, D’E’ is parallel with AB and E’F’ is parallel with BC. Draw a line through B and E’ to some point beyond E’, say, G (see Figure 1).
image
Figure 1. AB || D’E’ and BC || E’F’.

Then we have corresponding angles ABE' = D'E'G and CBE' = F'E'G. Thus, ABC = D'E'F'. We take for granted that the translation of DEF to D’E’F’ did not alter the angle between the lines and so we have our result.■

Corollary 3. The cross-section taken parallel with the end faces is everywhere similar to the ends.

Proof: By observing that the parallel cross-section intersects the trapezoidal walls of the prism so as to produce lines which are parallel to the base and top (Corollary 2), the argument applied for Proposition 3 applies here as well.■

Proposition 4.  The lines extended from the side edges intersect at a common point (the apex).

Proof:  Consider three consecutive vertices on the base A, B, and C, and corresponding vertices D, E, and F on an arbitrary parallel cutting plane parallel with ABC. By corollary 3,
Since AD and BE are coplanar, they intersect at some point P. Similarly, BE and CF intersect at some point Q. Assume that P ≠ Q. Take a section parallel to the base through P and label the vertices of the section which correspond to A, B, and C as D, E, and F and observe that the above proportion equation still follows from corollary 3. Also, D = E = P and so line segment DE = 0. However, since P ≠ Q, line segment EF ≠ 0, which contradicts the proportion above. Therefore, our assumption that P ≠ Q is wrong and we have P = Q. By the principle of mathematical induction, the proposition follows.  [Finding P is (i) 2 in S and establishing P = Q is (ii) the inductive step. 1 in S is either automatic or ill-defined I suppose, but irrelevant anyway.]■

The shape we have considered in this post is a frustum of a (possibly slanted) pyramid by proposition 4.

We conclude by noting that the argument for determining the volume of the frustum of a pyramid does not impose a condition that requires the top face to be centered over the bottom face. A slant does not alter the argument and therefore the result is the same. Note, of course, that the height must be measured perpendicularly to the end faces. It should be noted that we have not dealt in this post with the relationship between the cross-sectional area and the height, which relationship is needed in order to establish the volume formula.

Such proof involves 1) similar triangles, using the height of the apex as a reference, and 2) the relationship between linear dimensions and the area(s) they pertain to. Assurance of the existence of a proper apex is the critical component addressed in this post.

Thanks to one of my readers for the question at the end of a previous post that led to this post.

Friday, September 13, 2013

Find Snap Tangent Points

A common feature of CAD programs is support for tangent object snaps.  A line is drawn from some point, A, toward a circle with center C and radius r.  We want to find a point (or points), B, on the circle, such that AB is tangent to the circle.

Here's a sketch of the problem:



We are given the points A and C and the radius r.  The goal is to find B1 and B2.  We argue mainly for B1. The argument for B2 is the same.  We have assumed A is outside of the circle or else there are no solutions. (If you write code for this, you will need to check for this condition.)

Since AB1 is tangent to the circle and B1C is the radius of the circle, angle AB1C is a right angle.  The distances f and from A to C, say, d, may be calculated using the pythagorean theorem.  Now, we draw the altitude of triangle AB1C to E.  By similar triangles (ΔAB1C ~ ΔB1EC~ ΔAEB1) we determine that

and

and so, e = r2/d and a = f r/d.  We let δ be the normalized direction vector from C to A, namely,


Then point E is given by E = C + e δ.  Let δp= (δy, –δx), or the clockwise 90° rotation of δ.  Then points B1 and B2 are given by:

       B1 = E + a δp
and
       B2 = E – a δp,

which are the desired points.

Thursday, September 12, 2013

How Do You Write a Program Install Script in Windows 7?

Sometimes when you ask a simple question, you don't get a simple answer.  (I understand, however, if you ask a stupid question, the expected concord tends to occur.)  And you start to believe it's because there isn't an easy answer.  I wanted to know how to request admin rights in an install script running on Windows 7 so that a user could approve the request for admin privilege to install a program.  (I'm only dealing with the situation where the user has admin privilege to pass on to my program.)

Lots of people have had this question and answers abound.  Generally, I find that there are at least three categories of responses to questions that are a little off the beaten path:
  1. You can't/shouldn't do that! (Meaning, I think, sometimes, that they envy the questioner for thinking to ask the question and don't want a good answer to exist:  "That's stupid, so there!")
  2. Here's an awesome (or complicated) strategy for doing it!
  3. Um, I don't know if this is exactly what you want, but it might do what you need.  Depending on your situation, maybe it's good enough?
Regarding my latest problem, people say, "That would be a major security issue!" (Not so.  An install script is only logical where the requirement is that the user trusts the script.  Otherwise, why exactly is the user installing the program? Um, duh?)  Plenty of category 1) out there.  And in the same online forums, there are a few category 2) responses out there.  And "hats off" to them.  But I'm here to give you a category 3) response.

Create two files.  The first one is just a stub that requests the admin privileges for the second script.  The second script does all of the work.  Here is the first script:



Call the script (containing the above code) setup.js or some other suitable name.  Now, you go decide what your second script needs to do—the one named subsetup.js (or whatever you decide to call it).

A caveat needs to be mentioned—although the above scheme worked on my home machine, on another computer the "runas" operation did not trigger an administrator privilege request.  It could be related to policy restrictions.

Friday, September 6, 2013

Snap Perpendicular Code

"Snap perpendicular" is a way certain drawing programs (like AutoCAD and DraftSight) help the user to draw a line starting from some point C and draw it up to an existing line such that the new line is perpendicular to the existing one.  What would we do without "snap perpendicular"?  The alternative, I suppose, would be to hold a set-square on the computer screen.  Or, calculate the destination point.  Of course, the aforesaid programs do just that.  And so does the Maxima code at the end of this post.

Derivation

We're given an existing line segment AB in space and a point C.  We want to find a point P on line AB such that line segment CP is perpendicular to AB.  (We won't worry about whether it is on the line segment AB, just on the line AB; we omit a "range check".)  We observe that the perpendicular distance between a point and a line is the shortest possible distance and so we will treat this as a minimization problem, using the methods of calculus.  Let A = (Ax, Ay, Az) and similar for points B and C.  Then line AB is described by the parametric equations:

      x(t) = Ax + (Bx – Ax) t,
      y(t) = Ay + (By – Ay) t,
      z(t) = Az + (Bz – Az) t,

where P(t) = (x(t), y(t), z(t)).  We want to find P(t) such that line segment CP(t) is as small as possible, which is equivalent to finding when the square of the distance is minimized.  So, we define

D(t) = (C– x(t))2 + (C– y(t))2 + (C– z(t))2
       = (Cx – Ax – (Bx – Ax) t)2 + (Cy – Ay – (By – Ay) t)2 + (Cz – Az – (Bz – Az) t)2.

Taking the derivative yields:

D'(t) = 2 (Cx – Ax – (Bx – Ax) t) (– (Bx – Ax)) + 2 (Cy – Ay – (By – Ay) t) (– (By – Ay)) +2 (Cz – Az – (Bz – Az) t) (– (Bz – Az))

We solve for t when D'(t) = 0 as follows:

0 = (Cx – Ax – (Bx – Ax) t) (Bx – Ax) + (Cy – Ay – (By – Ay) t) (By – Ay) + (Cz – Az – (Bz – Az) t) (Bz – Az)

[(Bx – Ax)2 + (By – Ay)2 +  (Bz – Az)2] t = (Cx – Ax)(Bx – Ax) + (Cy – Ay)(By – Ay) +  (Cz – Az)(Bz – Az)

t = [(Cx – Ax)(Bx – Ax) + (Cy – Ay)(By – Ay) +  (Cz – Az)(Bz – Az)]/[(Bx – Ax)2 + (By – Ay)2 +  (Bz – Az)2],
which can be stated more succinctly in vector notation as
\[t = \frac{(B-A)\cdot (C-A)}{(B-A)\cdot (B-A)}\]
from whence derives the below Maxima code:



To prove that the point thus obtained is indeed the desired "Snap Perpendicular" point, it would be sufficient to show that the dot product of the vectors (A – B) and (C – P) is equal to zero, which check I omit.

Saturday, July 27, 2013

How Do We Deal with What We All Produce?

"Every man knows what he has to do and it costs two sous to do it!"—providers of bucket toilet services  in France in the 1800s (Rose George, The Big Necessity, 2008, p. 132)

At the present time, there are approximately 2.5 billion people that do not have access to a toilet of any kind—meaning, not even a latrine.  If you don't have a toilet, where do you go?  In the bush, in a field, on the road, in a plastic bag, in the nearest stream.  The nice part of the stream option is you have running water right there to wash up with.  You can fill in the bad part; some from history, some today:  the Thames, the Ganges.  Systematically putting human waste into the water isn't a good thing.

Even in Canada, we haven't completely cleaned up our act, though we're moving forward.  (Here is a publication from 2004 on the topic The National Sewage Report Card.  Basically it grades the sewage treatment of 22 Canadian cities, giving a few low marks.  Overall, the state of things improved from 1999 to 2004.  I hope the trend has continued at least as well to the present.)

One favorite suggestion for dealing with our waste problem is composting.  But, as often happens to lofty ideals of perfect solutions, the search for a practical implementation in the present—and actual, rather than imagined—deflates the idea somewhat.  (To clarify, I am actually in favor of composting toilets.  Or, at least, I would like to be.)

One of the hindrances to using a composting toilet, is the installation.  If you are going to use a "big bin in the basement" version, you need the requisite building layout.  There must be a location to store the "stuff" as it is deposited.  Most builders are not concerned with making that kind of layout.  What sells is a bathroom upstairs and downstairs.  And what gets built easily is one bathroom over top of another, to simplify the plumbing.

Also, it would require some kind of creativity to make the basement toilet a composting toilet in this scenario. For one, you need to get out of the way of the chute from the upstairs toilet.  So it needs to be an angled chute.  This means some water is required—non-stick coatings still need some cleaning (if you're not laughing already, think about gravity for a bit).  You also need to place the seat above the top of the big bin, which means you must ascend "the throne" to do business.

The general marketplace isn't ready for composting toilets that are integrated into the house.  That leaves it to the DIYers.  The modification is not widely considered as adding value to the home, so there goes the house flippers and young families that have any concern about being able to move with career changes or development.  Even if you live on a farm and won't be selling the farm house to anyone for the indefinite future, you have to be pretty committed to the idea before you dive in.  (Er, poor choice of words...)  If you're interested in how effective they are or whether they smell, see here.

What I have learned over the years about composting is that you need heat to make the process work efficiently and produce safe compost.  We are familiar with pasteurization, where pathogens are killed off with heat.  The same should be done with any compost where there is a chance there are pathogens.  In compost based on household waste (kitchen scraps, weeds, leaves, etc.), there are two villains: weed seeds and plant diseases.  They can both be "killed" with heat.  Heat also hastens the decomposition.  However, unless you have a good sized pile (think, "farm") and are prepared to moisten and aerate it, as well as make sure of an appropriate mix of nitrogen and carbon sources ("greens" and "browns"), you aren't going to get the heat that is needed.  At least for standard composting, a temperature between 55°C and 65°C is recommended to kill as many pathogens as possible but still maintain a thermophilic ("heat loving") bacteria population to keep the process going (http://compost.css.cornell.edu/microorg.html, 2013).  A small batch of compost can also be finished by cooking it.  Some have used solar cooking as a means of killing off pathogens and weed seeds that may have survived the composting process.

If you don't have the volume of material to develop that kind of heat, some supplementary heat is required. In the context of a composting toilet, the heat also has the effect of evaporating the urine which I'm sure reduces odor significantly.  The Excel composting toilet has a heater which has an average power usage of 150 W (SUN-MAR, 2013). That's (150/1000) (24) (365) = 1314 kWh, annually.  At the Manitoba residential electricity rates of $0.0694/kWh, that's about $91.  Eek.  $91 for soil.  And without any social indirection as to where it comes from.  Compost is supposed to be dirt cheap—I thought.  I should mention though, that if I had a cabin somewhere that didn't have appropriate plumbing, a composting toilet like this one would be worthwhile to me.

The change is not impossible.  But at the national level, it's a tough sell.

Saturday, July 6, 2013

Introspecting the Lisp Representation of a Maxima Variable

I recently wanted to know how Maxima (a computer algebra system) implemented something.  I searched and searched and couldn't solve my problem.  Specifically, I wanted to access a Maxima structure from within Lisp code.  However, I didn't know how the structure was implemented in Lisp and therefore didn't know how to access it.

All you need is a single line of inline Lisp:



structures is a global variable which stores the structures that have been defined in the session by using defstruct().  I wasted a few hours looking for this information to come up with 25 characters that would answer my question.  Applying the same general idea to an instance of PanelStruct() tells me how it is implemented.  By the way, the answer to my questions looks like this:

((MLIST)
  ((|$PanelStruct|) $SIZE $TOP $CENTER $BOTTOM $ZENITH $AZIMUTH |$rdv|)
  ((|$RayStruct|) $START $DIRECTION) 

  ((|$PlaneStruct|) $NORMAL $CONSTANT)      
  ((|$PanelStruct|) $SIZE $TOP $CENTER $BOTTOM $ZENITH $AZIMUTH |$rdv|)   
  ((|$RayStruct|) $START $DIRECTION) 
  ((|$PlaneStruct|) $NORMAL $CONSTANT)) 
((MLIST) 
  (($PanelStruct) $SIZE $TOP $CENTER $BOTTOM $ZENITH $AZIMUTH $rdv) 
  (($RayStruct) $START $DIRECTION) 
  (($PlaneStruct) $NORMAL $CONSTANT)
  (($PanelStruct) $SIZE $TOP $CENTER $BOTTOM $ZENITH $AZIMUTH $rdv) 
  (($RayStruct) $START $DIRECTION) 
  (($PlaneStruct) $NORMAL $CONSTANT))

The near repeat is caused by the print function returning what it has printed and Maxima outputting it.  The $ indicates a references to a Maxima variable and the | | symbols indicate a case sensitive reference.  Oddly, the case is reversed for RDV (which is documented) but not for PanelStruct which surprises me.  (These structures are not built-in but were user-defined in my Maxima session.)

I will still need to figure out how I'm going to use the information, but I have a working concept.

Wednesday, June 19, 2013

Ad Hoc Wind Shelter for My Tomatoes

I have a 10' by 20' garden plot at Hummingbird Community Garden (Brandon, MB, CA—see here for info).  Last year I planted muchos herbs and dried them, but maybe more on that later.

At the garden I get to see how everybody else does their garden.  Sheltering your tomatoes from the wind while they are young seems to be very popular.  I've seen it done with milk container, sour cream containers, 11 liter ice cream pails with a few holes cut in the sides (to let more light in), cedar shakes or shingles, and I've even seen a bit of plywood (protecting I-forget-what, but probably tomatoes).  I've not seen the like of 6 mil polyethylene on the garden sites in my past years at the garden, but that has changed this year.  Behold, the monstrosity which I have erected:


Allow me to enumerate its most noteworthy features:
  1. Ugly.
  2. Cheap.
  3. Reasonable resistance to wind.  This picture is after a 51 km/h wind...No, it looks the same as it did before the wind...well okay, one of the more rickety posts was even more rickety, but still standing.
  4. Some assembly required.
As so often happens in life, not long after I built the silly thing, I thought of a significant improvement to this design.  But first, what is good about this design?  

The key thing I want to point out is the means of attachment of the poly to the posts.  If the poly was merely stapled to the posts, that 51 km/h wind previously mentioned would have made short work of the shelter.  By screwing through plywood into the posts, I have spread out the stresses on the attachments.

But there's a better way than what I've done above and it isn't too much work with the right tools. (Which I do have, so I don't have that as an excuse.) It's dirt simple:  

1)  Make rectangular frames out of 2×2s. Two sidewalls, two end walls. Dimension the lengths according to the needs of your plants.  You probably don't need them any higher than 2'. (The wind shelter is really only to help them through the earlier part of the season.)

2)  Staple the poly to each frame and trim off excess. Probably the smart thing would be to have a wrap around the outsides of the frame (as much of a wrap as you can manage). The advantage of the wrap is that the tighter you pull it the more frictional force develops between the wood and the poly which (partly) helps the connection.

3)  Screw strips of plywood though the poly into the frame. Use 1 1/4" ceramic screws @ play it by ear O/C. An adhesive might also help, but I'm optimistic it wouldn't be necessary.

With your frames ready, all you need to do now is put posts in the ground and attach the frames to them. Now if you want a cold frame, you have a more interesting task ahead of you to put a roof on the thing, but I would like the rain, so I will skip that challenge.

Saturday, June 1, 2013

Lumpers and Splitters (and the Spreading-out Principle)

It has been said that there are two types of people (scientists?):  lumpers and splitters. Those might not be real words but they are good descriptors.

Lumping is the act of bringing things together. You take two lumps and you work them into the same lump. Splitting, of course, is dividing things up.

Lumpers and splitters that know the same information, tend to describe it differently. Splitters (at the extreme) spend their effort on describing every case and they want a different name for each case. Lumpers want to subsume several of these categories under a single heading. Both lumping and splitting are an important part of interpreting information and you should learn to do both. At the end of the day, however, the lumpers and splitters may disagree about the best way to categorize the information. But both bring something important to the table.

I was thinking about this in the context of language this morning, but I remember an excellent example of lumping from my grade 10-12 science/chemistry teacher that has stuck with me.

Some things have a tendency to spread out from where there is lots of it to where there is not so much of it.  For example,
  1. Heat moves from hot to cold.  (Heat energy spreads out.)
  2. Moisture moves from wet to dry.  (Moisture spreads out.)
  3. A substance dissolved into a liquid diffuses.  (Dissolved substances spread out.)
  4. Gases expand to fill their container.  (Gases spread out to fill a container.)
  5. If you move into a larger dwelling, you will buy and retain more stuff to fill it.  (Families and their stuff spread out to fill a container.  Unfortunately, they are not as easily compressed as gases.)
  6. If people are finding a seat in a place that is very large compared to the number of people in it, they will tend to sit further apart from each other.  (People spread out in a room.  This does not explain the "everybody-at-the-back-when-there's-a-presentation" tendency, which seems to be an overriding principle, at least in western Canadian culture.)
Instead of carefully memorizing several laws, remember that certain things tend to spread out.  These are all examples of things that spread out in a non-directional way.  (By direction, I'm meaning the limited sense of direction which applies to movements and orientation in physical space, like 30° East of North or 20° Zenith.)  They also don't indiscriminately spread out equally in all directions, like a non-directional sound or light source.  They don't just start moving in a certain direction and keep going that way.  What determines their direction at any point in time or space is relative abundance versus relative absence.  The abundance goes to where it is not.  

Note that there can be other principles that overrule or interact with this one and it does not apply to everything.  Also, each of the situations described above are affected or limited by barriers of some kind.

We have a tremendous abundance of food in Canada.  There are lots of places that do not have this abundance.  If food followed this spreading out principle there should be an equal amount of food everywhere by now.    There have indeed been movements of people to try to spread out the food, but there are other factors.  For one, which we can't do much about, disasters and droughts happen.  If at any point we were to approach equality, a disaster comes and changes things.  Secondly, and where there is a choice involved, human selfishness and indolence tend to frustrate efforts to move the abundance to where it is needed.  (Please note, I'm not giving a justification but a reason why.  I'm describing a human tendency which is actually evil: selfishness and indolence.)

But back to my main thought.  Both lumping and splitting are important activities in learning and researching.  You lump to make memorization and understanding easier and you split in order to recognize significant distinctions to make your understanding more thorough.  But I am describing these as learning activities.  I may find that I need to do some splitting in order to understand something more thoroughly, but at the end of the day decide that a relatively lumped description is a more apt and helpful expression of what I have learned.  The objectivity of such lumping and splitting decisions made by anyone may be questionable or debatable, but both activities are part of gaining better understanding.

Saturday, February 9, 2013

Lighting Distribution

I've written a simple Maxima program which uses linear interpolation and lamp luminous intensity data to determine the illuminance on a flat surface (read floor or work surface) caused by several lamps in different locations.  It displays a color contour do show you how the light is distributed.  I could probably tweak some things to get a nicer selection of colors for the color contour but as far as a result which is easy to interpret, this works fine.  Behold:


Never mind the clutter in the bottom left hand corner.  This is just the z-axis numbers written on top of one another because we are looking straight down on the graph.  Small price to pay for the cool result and you can edit the picture afterward if you need something for presentation purposes.  An additional problem I observe is the aspect ratio.  It should look square because my chosen room is square (8' × 8').  Dauntless, I press on.

To implement this program with your own example you need:

  • Maxima:  a free computer algebra system.
  • Light data
  • A room and light configuration.

Light Selection
You need to select a light and find the manufacturer data.  I am using the Cooper RPN3MR-E3MRC.  This is a combination of the light fixture and the lamp in the fixture.  The data you need will indicate how the candle power changes with vertical angle.  The assumed situation is that the light is pointing down.  The vertical angle is measured between the vertical line passing through the center of the light fixture and the line drawn through the center of the fixture to a location on the floor (or incident surface).  This vertical angle affects the "amount of light" (measured in candelas) that is going in that direction.  To input the data for your luminaire-lamp combination you enter it on the line that says "lampData:".  The data is in the form of a list of lists where the nested lists (two items each) represent points.  The pattern for each point in the master list is [angle in degrees, candle power in candelas].  If your data doesn't go all the way to 90 degrees, then put a final point [90, 0] to indicate there will be no light going in that direction.

Considerations in the Calculation
The vertical angle not only affects the "amount of light" in that direction but the angle of incidence with the floor.  We are assuming the light is "facing" the floor.  (The floor is horizontal.  The light is shining straight down onto it, although, of course it "spreads out" as it goes down.)  Remembering that the "angle of incidence" is measured relative to the normal line (perpendicular to the floor), you can see that the angle of incidence is an alternating angle with the vertical angle and therefore equal to it.  An angle of incidence affects how the light "spreads out" across a surface because the same amount of light gets spread out more if the surface is at an angle (not "facing head on") to the beam of light.  Also, not every point of the floor is the same distance away from each light.  As light travels it spreads out in two directions.  If you spread the same amount of anything (sound, light, peanut butter) over a larger area, there isn't as much of it in a given area.  The basic formula is:

$fc = \frac{cp}{d^2}\cos{\theta}$,

where
      fc = foot-candles (a measure of illuminance: cd/ft2)
      cp = candle power (candelas: cd, same unit in metric and imperial, relates to the Watt)
      d = distance (in feet)  
      θ = angle of incidence (measured from the normal).

The formula is the same if you use metric, but the units change.  Instead of entering feet and getting foot-candles, you enter meters and get lux.  You use the same lamp data which is in candelas.  Candelas are the same in metric and imperial.  To put it very simply:

lux = cd/m2
fc = cd/ft2

Using the Program
If you want metric, enter all distances in m (you will get lux).  If you want imperial, enter all distances in ft (you will get foot-candles).
  1. As always, choose a coordinate system and stick to it.  Pick a corner of your room to be (0,0) and one of the sides to be the positive x-axis.
  2. Enter the length and width of your room.  I have called these x_length and y_length to avoid misunderstandings based on the usual understanding of width < length.  Just pick a dimension to be the x direction length and one for the y direction length.  Doesn't matter which is set to which.  Just be consistent with step 1.  Sorry, only rectangles.  You're welcome to program something more interesting if you get bored some day.  Or, maybe your room can pretend to be a rectangle?
  3. Enter the locations (positions) of your luminaires.  These are in terms of [x, y, z].  I have entered the height of the luminaires for the the z value (12.5 feet).  You could instead enter their height above a work surface (the results would only be correct for the work surface).  Alternatively, you can change the Illum(x,y) function definition to use a z-value of the height of the work surface instead of 0 (same caveat as previous suggestion).


Note:  P2P_Illum() means Point-to-Point Illuminance.  Illum() is the sum of the illuminance contributions of each luminaire to a given point.

Possible Improvements to the Program
  1. Change the color selections for the plot.  Perhaps yellow for higher values.  Might be a fiddly thing to get right.
  2. Include a more explicit boundary (wall) definition mechanism.  A list of vertices would satisfy the wall definition needs.  But then some programming would need to be done to determine which lights have a line of sight to a given x,y point.  There would also be a need to either crop the end result or indicate some neutral value for places in the plot area but not within the boundaries of the room.
  3. Allow the incident surface shape to be specified.  
    • This might be as simple as allowing inputs of areas at different heights.  This would be the simplest and most widely useful approach.  It would be helpful to indicate the locations of the different surfaces on the plot as well.  It might be necessary to directly use the draw package to do this. [First, load(draw).  Then learn how to use draw.  I haven't looked much into it yet.]
    • More complex surface entry would require more complex angle of incidence calculations.  The angle of incidence would not necessarily be equal to the vertical angle.  If the incident surface (or part thereof) was represented as an analytic function of two variables, you could use the partial derivatives to determine the tangent plane and thus the direction of the normal.  Given the direction of the normal and the direction toward a given luminaire, you take the dot product of these (normalized/unit) vectors to get the cosine of the angle of incidence (which is what you need; see formula above).

Sunday, January 6, 2013

Rhetorical Idioms Should be Said in the Right Order

It is common when using rhetorical idiomatic phrases to switch the order of clauses from what actually conveys the idea.  People usually understand anyway, because they recognize an idiom.  However, they may only get it by context, because they see what you are arguing for overall.  In particular, I'm talking about:

Even...let alone/never mind

No matter what anybody says, you have to apply the word "even" to the correct word or phrase to get the right meaning.  This word sometimes goes along with "let alone", which can also be used without "even" (in which case, "even" is implied).  Thus,
They can't meet even less stringent requirement, let alone meet more stringent requirement.
Or,
They can't meet less stringent requirement, let alone meet more stringent requirement.
The word "even" in this usage refers to the item which is in some sense less.  The phrase "let alone" applies to the greater.  "Never mind" can fulfill the function of "let alone" in this type of sentence.  (In a lot of cases "even" is applied to the greater, but here there is a negation involved.)

Here is an example to contrast the right way and wrong way to use the phrase "let alone".  A similar line of example (and argument) would apply for "even" or "let alone".
Right:  Darren can't play the kazoo, let alone the tuba!
Wrong:  Darren can't play the tuba, let alone the kazoo!
Consider the logic of the right way of saying the above phrase:  If Darren lacks the ability to play the kazoo (which for some reason we are sure about--or feign ourselves so to be), we most certainly should not entertain the thought that he can play the tuba.  The tuba is way harder!  We should leave off from having such an idea.  We should discontinue thinking that way.  We should "let it alone" and "never mind" such a thought.  On the other hand, suppose we are only confident that Darren cannot play the tuba.  Should we "let alone" or "never mind" the possibility that he can play the kazoo?  We should not let alone such an idea, for many have this lesser ability who do not have the ability to play the tuba.  (Somewhere out there, a professional kazoo player is burning up.)

You might think I am being unduly prescriptive.  After all, you might reason, since people will know that kazoos are easier to play than tubas, they will understand the intended logic whether I use the Right way or the Wrong way.  I have two reasons for insisting (other than being annoyed at the Wrong way,..., okay, so I have three reasons):

Firstly, misunderstandings can happen when one or both of the two things thus compared are unfamiliar to the audience.  What is alarming to me is that some people seem to systematically use the Wrong way.  If I find myself reading from someone who always says it the Wrong way (unbeknownst to me) and I don't know very much about the two things (in our example, the kazoo and tuba), I will come away with the erroneous idea that playing the kazoo is much harder than playing the tuba!  As I consider the context I will probably find myself confused because I will intuit an inconsistency between what they are currently saying and what they previously said.  Then I will have to figure out which of the things which they have said they actually mean or which of the things I have misapprehended.  In this case, because we do know about kazoos and tubas, it is actually quite hard to think of the Wrong way as meaning what it literally says.  I tried, it was hard.  (But the Wrong way still bothered me!)  That is probably what leads to this phrase being so hard for people to keep straight.

Secondly, but more importantly for you:  The reason you decided to use this rhetorical idiom, was to pack a little punch in your argument or reply.  By reversing the order, you are set to make the impact of a wet noodle, which is probably not what you're looking for.