Friday, July 10, 2015

Using the Audio Jack for power and digital interface to smartphones!

If you have seen credit car readers on smartphones, you will see they are a small block that plugs into the smartphone's audio jack, what you might think of as its headphone jack.

This is a remarkably clever solution to the problem: how do I build an add-on for both iPhone and Android without paying licensing fees to either?

Project HiJack at University of Michigan gets the credit for figuring this stuff out.

  • For power, your app can play a tone out the speaker jack on, say, the left speaker channel.  That tone can be rectified in your external device to provide up to about 7.4 mW.
  • If you need to, you can send data to your external device from your sensor.  You essentially generate an audio tone in software as you might generate a radio frequency in hardware on a radio communicator.  The data modulates the audio tone.  You build a demodulator on your external device and you are set.  
  • You can get data from your external device.  You generate an audio tone on your external device and play it into the microphone lead of the audio jack.  The app on the smartphone can record that audio, represent it in software as an array of numbers (voltage values from an analog-to-digital converter (ADC)).  The data you are sending can modulate the audio tone, which modulation can be detected mathematically by processing the recorded ADC values from receiving the audio.  
This stuff is cool!

Monday, February 09, 2015

Gasoline Engines: a simple mostly linear model

If you have ever googled, the efficiency of a gasoline engine, you have likely found something like this:

While this is very much a standard diagram to see, by the end of this post I am going to replace it with a different figure that has the same information on it, just rearranged.  The beauty of the replacement figure is that it will show that at any given engine speed, the engine output power increases linearly with the amount of gasoline flowing in to the engine.  It will show that this is true except at very high flow rates of gasoline into the engine, where the power output of the engine is seen to "saturate," the engine becomes less efficient at converting gasoline to output energy when the gasoline is flowing in to the engine very fast.  

The above diagram is called a BSFC map, a Brake Specific Fuel Consumption map.  This is created by measuring the engine output with a brake dynamometer.  A brake dynamometer effectively puts a friction brake on the output shaft of the engine, or rather to something connected to the output shaft of the engine.  The friction brake can be applied to slow the engine output down.  The dynamometer is instrumented so that it can measure the braking effort currently applied to the output shaft of the engine.  That braking effort is measured in units of torque, which in the metric system has units of Newton-meters.  

If the dynamometer measures the engine output shaft rotation speed at the same time as it measures the braking torque on the output shaft, we can easily calculate the power that the engine is dumping into heating up the brake.  Torque times rotation speed gives power.  To get power in the standard metric system unit of Watts, the engine speed needs to be expressed as an angular velocity in radians per second. To do this, the RPM measurement is divided by 60, to convert it to rotations per second, then multiplied by 2π to convert it into radians per second. 

The way you use a dynamometer to get the figure above is you set the engine accelerator to a fixed setting.  Then you adjust the braking force over a range of values.  At each braking force, you measure 1) the braking torque, 2) the engine rpm, and 3) the fuel consumption, typically in grams per second.  At each x,y point you have measured, you know how many Watts (W) are being produced in rotational motion of the engine shaft because at that point you can multiply the torque by the angular velocity corresponding to that point.  Since you have also measured the gasoline consumption in grams per second (g/s), with a little straightforward math you can calculate the number of grams of gasoline that would be required to produce a kWh of rotational output energy.  kWh is "kilowatt-hour," it is the amount of energy that a 1000 W power source produces in 1 hour.  1 kWh = 3,600,000 J.  

The contour lines on the BSFC map are lines of constant energy efficiency.  At any point on, for example, the 280 g/kWh contour, the engine produces 1 kWh of output energy for every 280 g of gasoline that it consumes.  One can see from the chart that the engine is most efficient at an engine speed of about 2700 rpm and an output torque of 95 Nm.  At this efficient point, by using the math above we calculate the engine is putting out about 26.9 kW.

One last little bit of mathematical conversion.  A gram of gasoline can be burned, and when it is burned it releases a certain amount of heat energy.  The amount of energy released is slightly variable because the mixture of hydrocarbons in gasoline is slightly variable depending on how it is formulated at the refinery.  The US EPA has settled on 33.7 kWh as a standard estimate of the energy content of one U.S. gallon of gasoline.  This translates to about 12.2 Wh/g energy content of gasoline.  So the contours of gasoline usage in units of "g/kWh" can actually be simplified to a pure energetic efficiency.

280 g of gasoline release 3.425 kWh of heat energy when burned.  but near the most efficient point of the engine shown in the BSFC fuel map above, we find we are able to get 1 kWh of rotational energy out of this engine for each 280 g of gasoline burned in the engine.  This means that the energy conversion efficiency of this engine operating on that 280 g/kWh contour is 1/3.425 = 29%.  That is to say that when this engine is operating at any point along the 280 g/kWh contour, is converting 29% of the thermal energy of the gasoline it is burning into rotational energy at the output shaft of the engine.

Finally, we combine all that we have said above and reformulate the BSFC fuel map into the following:


Here, the different colored dots come from digitizing points on the BSFC map above, and converting them so each one shows its output power, the rotational power of the output shaft of the engine, vs its input power, the heat energy of the gasoline flowing in to the engine to produce that output power.  We group data points by RPM.  At each RPM value, we find the best fit straight line through the points at that RPM.  What we find is generally: 1) at lower RPM, we convert gasoline heat energy into rotational energy more efficiently.  2) To get higher total output power, we need to go to higher RPM, but this costs us a little bit in efficiency.  3) at the high power end of each RPM value, there is some "saturation" visible: the output power falls below the best fit line.  The engine is a little less efficient when a lot of gasoline is flowing in to it then when less gasoline is flowing in to it.

We can rearrange the data in the Power out vs Power in plot by creating a y-axis showing values of Power_out / Power_in = Efficiency.  Here is that plot:
Plotting efficiency on the y-axis, we see that at each RPM, the efficiency of the engine rises as we drive it harder, as we pour more gasoline into it.  The efficiency drops to zero when we apply only enough gasoline to keep the engine idling: to keep the engine turning but with no extra energy available to be delivered through the engine's output shaft.

Note that each output line has an x-intercept, a value of gasoline flow into the engine which can keep the engine turning at this RPM value, but which produces no additional power at the output of the engine.  This is the fuel flow into the engine that is required to keep the idling engine turning at the specified RPM.  One could explore the points along the x-axis by putting the car in neutral gear, and revving the engine with the gas pedal.  If while doing this, you were able to measure the gasoline consumed at each RPM value, you would expect to measure directly the x-intercept values shown in this figure.

Here are plotted the x-intercept values, vs RPM.  Essentially this is a plot of the fuel flow rate required to keep the engine idling at a particular RPM value.



Saturday, January 10, 2015

Gasoline Usage at Idle with and without Air Conditioner Running

I logged gasoline usage with my car running at idle.  I varied the RPM to see how that affected it.  I turned the air conditioner on and off to see how that affected it.

The car is my 2005 Mercedes CLK320A.  This has a 3.2L V6 gasoline engine.  It is supposed to use "premium" fuel (91 Octane in the US), but I have been unable to determine any performance difference using what is sold as "regular" fuel (87 Octane in the US) in San Diego, where I live.  So I run it using regular fuel, and the results here are with regular fuel.

My set-up for testing this stuff is described in this post.

For the test, I used a warmed-up engine.  I ran the engine in my driveway and applied the accelerator pedal to achieve different RPM levels.  The RPM levels and fuel usage rates shown are those logged by the setup described in the other post throug the car's OBD2 connector.

For "air conditioner off" condition, everything in the car is turned off including the climate control.  The car does have running lights that stay on in the daytime, these were on.  No attempt was made to determine the state of the alternator, whether it was charging the battery or not during this test.

For "air conditioner on" condition, the climate control in the car cabin was turned on.  The thermostatic control was set to 60° F in order to keep the air conditioner on constantly.  The fan blowing air in the cabin was set to its highest setting.

Results


Results are shown above.  Minimum mean square error line fit to the data are shown.  At lower RPM, results are pretty nice and linear.  

Idle Fuel Usage with Air Conditioner turned off

Without applying the accelerator, this engine idles at about 600 RPM.  The fuel usage at idle is about 0.25 gallons per hour, with the air conditioner turned off.  The idle fuel usage rises to about 1.0 gallons per hour at 2500 RPM.  The fitted line, with air conditioner turned off, nearly passes through 0 fuel usage at 0 RPM.  Thus for all intents and purposes, the idle fuel usage is:

(1 Gallon per Hour) * ( Engine RPM / 2500 )

What is the meaning of 0.25 gallons per hour of idling loss?  This is a car which gets about 22 miles per gallon averaged over my driving.  So an hour of idling uses the same amount of gasoline as driving about 5.5 miles.  At $4/gallon (as I write this prices in San Diego are as low as $2.40/gallon), idling costs $1/hour or 1.6 cents per minute.  My conclusion is that in regular use where idling more than a few minutes would be very unusual, idling is a very inexpensive process and not worth great efforts to avoid.  

Fuel Usage by Air Conditioner

The caption of the figure shows the linear fit equations for the fuel usage with air conditioner off and on.  The difference between these two linear fits is 0.16 gallons per hour.  This suggests that when the air conditioner is running, no matter what the RPM of the engine is, it is demanding fuel at a rate of 1 gallon every 6 hours.  

If the car gets 22 mpg with the air conditioner off, adding fuel flow of one additional gallon every 6 hours would correspond to moving the car at about 4 miles per hour.  Now this is with the air conditioner running constantly (it was set to 60° F for this test).  Since it cycles off and on in actual use, actual usage with air conditioner on will be less than this.  

At $4/gallon, air conditioner on constantly costs about 67 cents/hour.  Since in actual use air conditioner cycles on and off, a better rule of thumb might be 25 cents/hour.  

Gasoline Usage in your Car, the tools I use

You can learn a lot about gasoline usage in your car by, well, by logging gasoline usage in your car under a variety of conditions.  You can then analyze the logged results and figure out an astonishing amount of stuff!

In this post I just list the tools I use for getting results.  Following posts will show some of those results.

The Hardware


This is what I use.  It plugs into your OBD2 connector.  On my cars, this is located somewhere near where the hood release for the car is located, under the dashboard on the left side of the steering wheel.

The Software


Torque Pro is available for Apple and Android, I use the Android version.  Torque Pro has amazing real time gauges for displaying many things it can read from your car.  For this work, the real time displays are not so important.  What is important is the ability to log these data into spreadsheets, which spreadsheets can then be opened and analyzed later.  

After I have the spreadsheets of logged data from my driving runs, I write scripts in Matlab to do the analysis.  I have used Matlab for decades in my job.  It is a powerful and complicated tool.    

Tuesday, December 09, 2014

Stock Price Volatility: Log-Normal or Highly Deterministic superimposed with AWGN?

Below is a quick write-up of results I originally found in 2005 and am finally writing down in 2014.  I want to get it up so I can show it to someone who was asking about it.  As such there is a lot of unexplained stuff.  Volatility is a measure of the width of the distribution of price ratios, in many figures below it is the second number, the one following "+/-" in the title.  Volatility used here is the same "volatility" used in describing stock price motions.  Anyway, for what its worth here it is.

The Black-Scholes formula for estimating the value of a stock option is rather elegant.  It estimates the value of the stock option by assuming a particular random distribution of future stock price movements, and averaging over all of these to come up with the current value of a stock option as an expectation value over a random variable.  A second way of deriving the Black-Scholes formula is to come up with a strategy for fully hedging an options position by buying and/or selling short stock, in which case the Black-Scholes price of the option is the price at which there are no arbitrage gains to be had by trading options against stock positions.

Underlying the calculation of the Black-Scholes price is the assumption that price variations are log-normally distributed.  That is to say, if P2 is the price of the stock at time t2, and P1 is the price of the stock at time t1 = t2 - dt, then for all different values of t2, the variable x = log( P2/P1 ) is a random variable with normal (or Gaussian) distribution.

In 2005 I analyzed stock prices for a real stock to see if they did fit a log-normal distribution after all.  I took the daily closing prices for a tech company stock for a 14 year period.
14 years of closing prices
Now I take the price data and find the ratio of the closing prices on sequential days.  I take the logarithm of those values and plot them in a histogram.
Price ratios for 1 day spacing between prices
The dashed line shows a "best fit" Gaussian, where the fit is found as a Gaussian with the same mean and standard deviation as the histogram, and with amplitude chosen to make the area under the Gaussian equal the total number of data points plotted.  The title shows the mean and standard deviation of the Gaussian, but normalized to annualized change rates.  So the actual mean of the above Gaussian is 32.1% divided by 252 trading days in a year, the actual standard deviation is 62.2% divided by sqrt(252 trading days in a year).  

Finally, we will show plots like this with a logarithmic y-axis so that tail behavior can be seen clearly.  The daily volatility plot above then looks like this:
Daily Volatility with y-axis on logarithmic scale
What looked like a great fit to the data on a linear scale is now seen to have really serious problems in its tails.  There are about 10 ratios on the low side on the left of the plot, and maybe 12 on the high side, on the right, where the underlying Gaussian distribution would have predicted a VERy low probability of seeing any events at all in the 14 years of data.  In particular, the log-normal prediction is that we had less than 1 in 1000 chance of seeing any log(PriceRatio)>0.2, but we actually see 3!  Even the "close-in" outliers are highly improbable price ratios.  And yet the central part of the price ratios distribution looks fit rather well by a Gaussian.  

Price Ratios with about 1 Month between Prices
With about 1 month in prices, we can see that the log of price ratios is bigger than with only 1 day between prices.  This makes sense, the price of a stock changes more in 1 month than in 1 day.  In fact, from the log-normal model of daily prices, we would expect the price changes over N days to be on average sqrt(N) higher than the price changes over 1 day.  And in fact, the annualized volatility shown in the title of the plot is about the same as for the 1 day.  The annualized volatility is found by taking the actual volatility and multiplying it by sqrt(N/252) where N is the number of days between price points and 252 is the number of trading days in a year.  So as long as we see that volatility number (the second number in the title) staying about the same, the price ratios are behaving as you would expect for log-normal variables uncorrelated on the daily scale.  
About half a year between prices
With about a half year between prices, we are seeing a very strong bunch of outliers on the positive price ratio side.  And one can imagine one sees a narrowing gaussian peak for "most" of the non-outlier points, and a separate set of high ratio points that are not part of the Gaussian distribution.

Price Ratios with about 1 year between prices
With one year between the prices, we are seeing significant deviation from Guassian distribution.  Our best fit Gaussian does NOT fit the "central peak" very well anymore.  The outliers on the right have increased the mean of log(price ratio) to a higher value than characterizes the central peak.  The outliers on the right are also dominating the standard deviation calculation so that the "best fit" Gaussian is now clearly too wide and clearly too far to the right compared to the "central peak" of the data.  At this point we would probably want to model the data as "some points fit a Gaussian, the rest do not."  





Tuesday, March 04, 2014

Really? Gay wedding photography heading towards the Supreme Court?


When I talk to people who are against gay marriage because "it isn't right," in a withering response I say to them, "you do realize that allowing gay people to marry does not require you to participate."  This has always been the linchpin of my socially progressivism.  I do my thing, you do your thing, and I am HAPPY to have you not like it, just keep your stupid nose out of my stupid business.

So along come the rest of the progressives, the kinds of people who give progressives a bad name.  The kind of people who give life to the slippery slope arguments that the gays will insert themselves in everything if not banned by law from most public institutions.

A woman in New Mexico asked a wedding photographer to photograph her gay wedding.  The wedding photographer said that she only photographs "traditional" weddings.

So before we go down the rabbit hole, how is that not the end of it?  Why would you ever even consider hiring a wedding photographer who didn't want to photograph your wedding?  Is there a shortage of gay-friendly photographers?  Is there even a shortage of gay photographers?

Do you really think you would like the job that a photographer who did not want to photograph your gay wedding would do?  Are you going to sue them for violating your civil rights if some of the pictures are blurry and they don't get a shot of you dancing with Aunt Mildred who is 101 years old and came all the way from Poughkeepsie to see the wedding?

But no.  Here I am a totally died in the wacky wool social progressive. And I look over at the other wacky social progressives, and for some of them, not being stopped from having everything they want is not enough!  They need the people who they beat in legislation, the people they beat in courts, to bow down before the great fascist power of their self-righteous sodomy!

Upon verifying with the photographer that she did not photograph gay weddings, our blushing bride filed a complaint with the New Mexico Human Rights Commission for discriminating against her based on her sexual orientation in violation of the NMHRA And on it has gone from there in a clown-car journey from court to court.

I can't imagine paying a photographer who didn't want to photograph my wedding to do it.  I would expect crap from them.

I can't imagine there aren't wedding photographers all over the place who would be happy to photograph a gay wedding.

I can't believe there is no American court that can moot the case by pointing out that "you'd have to be a f***ing idiot to hire a photographer who did not want to photograph your wedding.

I can't believe I am not seeing other commentary pointing out the pure basic nastiness, stupidity, and fascism of bringing legal action against a photographer who did you a favor when she said she didn't want the job.

Why do we need to interfere with every person out there and get them to kowtow under the law to a particular set of social choices?

Honestly, how do I argue with people who want to ban gay civil rights because they don't want gays inserting their influence into their families' lives by pointing out that "allowing gays to marry does not obligate you to participate."  Because apparently it does.

Saturday, June 15, 2013

What about NSA spying?

In briefest summary, we have learned that the NSA is collecting and saving information about every phone call in the US.  One assumes they are analyzing this as well, that they are creating graphs of who talks with whom and how much.  Presumably on demand they can go back and see who you were talking to at a certain time, and find accomplices to various activities they discover by doing so.

Yes I actually do have the same INITIAL reaction as everyone else, well almost anyway.  Pretty much, WTF?  But then my internal reverse engineer takes over and I ask myself questions like: 1) does this really matter?  2) Is this sort of thing inevitable with current technology (and therefore less worth tilting against)?  3) Is it really so bad, or is there something very much like what is going on that would not be really so bad?

SO here is a thought I just had that prompted me to write this post now.  Suppose there was a telephone system which was programmed so that it only worked for "good" calls, but simply did not work for calls that involved plotting or planning illegal violence.  And it did this automatically, no human intervention.  When you called your girlfriend to talk about her shopping trip it worked, when you called her to threaten her because you think she was paying too much attention to your brother it would not work.  When you called Walmart to get a price on a gun for self-protection it would work, but when you called them to ask about the price of a gun you wanted to commit armed robbery, it would not work.  When you called about flight school because you wanted to be a pilot, it would work, but when you called to learn how to take off, but did not need to learn to land, it would not work.

OK, such a system might be difficult to implement, but SOME of you are  already thinking of ideas about how you would approach this.  But this post is not about a new technology, it is about what we think of this feature set, good idea or bad idea?

As I have described it, it seems like a GREAT feature set to me.  A tool that can only be used for good.  No other human issues.