## Exploring Maximum Power Transfer with 3D Plots in Matlab

I recently took a course in circuit analysis where we learned the maximum power transfer theorem.  While there are many plots of the power transfer in the purely resistive case, I did not see any for the case where the source and loads are impedances (with both resistance and reactance).  I played around with 3D plots to get a better understanding of power transfer and to practice using Matlab.  Here is a write-up of what I did.

# Introduction

We will analyze the following circuit:

Image: “Source and load circuit Z“. Licensed under CC BY-SA 3.0 via Wikimedia Commons.

The relevant elements are as follows:

• $V_S$ is the voltage source, which we assume to be a steady-state sinusoidal source.
• $Z_S=R_S+X_Sj$ is the source or internal impedance (with resistance $R_S$ and reactance $X_S$).
• $Z_L=R_L+X_Lj$ is the load impedance (with resistance $R_L$ and reactance $X_L$).

The idea is to find the amount of power transferred to the load by the voltage source given a fixed source impedance.  We are particularly interested in finding the load impedance that will give us the maximum power transfer to the load.  There are many references that discuss these concepts, so I will not go into more detail here.  I will note however that there is an interesting article “Non-Calculus Derivation of the Maximum Power Transfer Theorem” by Dr. Kenneth V. Cartwright which discusses the theory in a non-traditional manner.

I will show the equations, but will not derive them – I will use the same notation and form as found in the “Maximum power transfer theorem” Wikipedia article.  I will include short Matlab code blocks throughout this document.  These are meant to be run in order (in other words, each code snippet will depend on variables or plots from previous snippets).  I am no Matlab expert, so I am sure there are better ways to write and present the code. For variables, I use the following convention: scalar constants are designated with lower case letters, whereas vectors and matrices are designated with upper case letters. For simplicity, I use the value 1 for all constants.  To get the most detail from the plots I include, you will need to click on the images.

# Power Transfer with Pure Resistance

For the purely resistive case ($X_L=X_S=0$), the average load power as a function of load resistance (we assume the source voltage and load resistance are constants) is:

$P_L(R_L)=\frac{1}{2}\frac{|V_S|^2R_L}{(R_S+R_L)^2}$

The plot of this power function is found in many places. We can plot it ourselves as follows:

vs = 1;        % Source voltage is normalized to 1V
rs = 1;        % Source resistance is normalized to 1 ohm

RL = 0:0.1:7;  % Use load resistance in the range (0,5) ohms

% Calculate power
P = 0.5 * (vs.^2 .* RL) ./ ((rs + RL).^2);

% Plot the power
figure;
plot(RL,P);
title('Power Transfer (Resistive Case)');
ylabel('Average Power Transfer');


As can be confirmed by the graph, maximum power transfer occurs at $R_L=R_S=1$ where $P=\frac{1}{8}W$

# Power Transfer with Impedance

The load power as a function of load impedance (as before we assume the source voltage and load impedance are constants) is:

$P_L(R_L,X_L)=\frac{1}{2}\frac{|V_S|^2R_L}{(R_S+R_L)^2+(X_S+X_L)^2}$

We can plot this function as follows:

xs = 1;        % Source impedance is normalized to 1 ohm

XL = -5:0.1:5; % Use load reactance in the range (-5,5) ohms

% Build a mesh grid for the 3D plot
[RL_mesh,XL_mesh] = meshgrid(RL, XL);

% Calculate power
P = 0.5 * (vs.^2 .* RL_mesh) ./ ((rs + RL_mesh).^2 + (xs + XL_mesh).^2 );

% Plot the power
figure;
surf(RL_mesh, XL_mesh, P);
title('Power Transfer (Reactive Case)');
xlabel('RL (ohms)');
ylabel('XL (ohms)');


# Lines of Maximum Power Transfer

For a given $R_L$ we can find the $X_L$ that gives the maximum power by solving the equation $\frac{\partial P_L}{\partial X_L}=0$ to get:

$X_L=-X_S$

Note that the impedance turns out to be independent of $R_L$.  We can plot a line to follow this maximum power:

% Calculate reactance where power is maximum for each resistance (note it is constant)
XLMAX = -xs * ones(size(RL));

% Calculate maximum power along the line
PMAX = 0.5 .* (vs.^2 .* RL) ./ ((rs + RL).^2 + (xs + XLMAX).^2 );

% Plot the line on top of the existing surface
hold on;
plot3(RL, XLMAX, PMAX,'LineWidth',2,'Color',[0 0 0]);


Likewise, for a given $X_L$ we can find the $R_L$ that gives the maximum power by solving the equation $\frac{\partial P_L}{\partial R_L}=0$ to get:

$R_L(X_L)=\sqrt{R_S^2+(X_S+X_L)^2}$

We can plot a line to follow this maximum power as well:

% Calculate resistance where power is maximum for each reactance
RLMAX = sqrt(rs^2 + (XL + xs).^2);

% Calculate maximum power along the line
PMAX= 0.5 .* (rs.^2 .* RLMAX) ./ ((rs + RLMAX).^2 + (xs + XL).^2 );

% Plot the line on top of the existing surface
hold on;
plot3(RLMAX, XL, PMAX,'LineWidth',2,'Color',[0 0 0]);


Maximum power occurs where the lines intersect. As can be confirmed on the graph, this occurs when the source and load impedances are complex conjugates of eachother:

$Z_L=Z_S^*=R_S-X_Sj=1-j$

As before the maximum power is $P=\frac{1}{8}W$.

# Efficiency

The efficiency (power dissipated in the load versus total power dissipated) is a function of resistance only:

$\eta(R_L)=\frac{R_L}{R_S+R_L}$

In the plots so far, the surface is colored automatically to match the magnitude of the power (blue indicates a smaller magnitude and red indicates a larger magnitude). We can also specify our own color scheme. For example we could color the surface to indicate the degree of efficiency:

% Calculate efficiency
EFF = RL_mesh ./ (rs + RL_mesh);

% Plot a new graph which indicates efficiency using color
figure;
surf(RL_mesh , XL_mesh, P, EFF);
title('Power Transfer (with Efficiency)');
xlabel('RL (ohms)');
ylabel('XL (ohms)');


Note that the numbers along the vertical axis of the graph still indicate power magnitude – efficiency is only indicated by color.  As expected, the efficiency increases asymptotically to 100% as load resistance increases (dark blue indicates 0% and dark red indicates close to 100%).

## Ant Build Script for Android Icons

I have been working on two small Android apps recently.  I did not want to manually create the icons since I do not have a lot of graphics design experience.  Because the icons are simple and do not need to be particularly original, I decided to build my icons mostly out of open source icons.  Because I was going to release the source code for my apps anyway, I ended up using icons from Wikimedia Commons that were released under the GPL license.

I wanted to automate this process as much as possible, so I created Ant build scripts.  I thought I would share the build scripts here.  I am sure that most Android icons are created manually using graphic design tools, but I still think build scripts would be useful for certain tasks.  For example, developers need to provide several duplicate launcher icons of different sizes (there are websites which provide this automated resizing functionality).  Also, it is recommended that you optimize your icons to make them smaller before packaging.

Although I am writing about Android icons, these build scripts could also be used for other types of icons: Windows ICO files or Linux SVG icons.  In fact, one of the build scripts I made does create these icons (see first icon below).

I still had to do a lot of manual editing.  Fortunately the original icons were in the SVG format, which uses vector graphics encoded in XML, so I was able to edit them using a text editor.  I also had to use a lot of trial and error with the build scripts to get everything sized and arranged properly.

The build scripts are designed to run using Apache Ant on Ubuntu Linux, and require the following tools to be installed:

If your source graphics are vector SVG files, you can edit them directly using a text editor (I am sure there are dedicated tools for editing them as well).  If you want to manipulate them using ImageMagick, you will need to rasterize them first, which will result in a loss of quality.  The SVG files can be easy to work with since they are basically scripts for drawing an image.

The exact build process will vary widely depending on your circumstances, but the general flow I used is as follows:

1. Convert the SVG files into raster/bitmap files (using Inkscape).
2. Draw any required graphics (using ImageMagick).
3. Crop/resize the graphics file as required (using ImageMagick).
4. Compose the graphics into a final icon (using ImageMagick).  Since the final image is a bitmap, make it at least as large as the largest size you need.  In other words, you always want to scale the image smaller when you resize it – scaling it larger will result in a loss of detail.  Make sure launcher icons have a transparent background.
5. Resize the icon into the various required sizes (using ImageMagick).
6. For the feature graphic, I used the launcher icon, but resized it (it uses a different aspect ratio than the launcher icons) and filled it in with a white background (using ImageMagick).
7. Optimize the final icons that will be packaged with the app (using OptiPNG).
8. The resulting icons can be placed directly into the Android folder hierarchy.

Some side notes for non-Android icons:

• Windows ICO files contain multiple copies of the icon image at various sizes.  The ICO file can be generated using ImageMagick (see the first icon’s build script).
• The version of Linux I use (Ubuntu 12.04) uses SVG files for icons.  Since these use vector graphics, there is no need to perform many (or any) of the build steps if you use SVG as your source graphics – this is because many of the build steps involve working with bitmap files.  I am not familiar with all the types of Linux icons – I am sure there are other types besides SVG depending on your distribution and window manager.

When the scripts are run, all tasks are re-run even if dependencies have not changed.  It would be possible to only regenerate artifacts that are out of date, but I did not feel it was worth the effort in my case.

First Icon

Final icon created by build script:

This icon is basically the composite of two original icons.  I manually edited the arrow SVG file to remove its shadow and get this result.  I then manually added the arrow to the globe icon.  The build script was only used to rasterize the icon and perform cropping, resizing, etc..

Note that this build script also creates an ICO file (for Windows) and an SVG file (for Linux), which are there for future use.

The build resources can be viewed here:

Second Icon

Final icon created by build script:

This icon was a little more complex than the first.  The green “share” logo was drawn using ImageMagick and then overlaid onto the “document” icon.  I manually edited the document icon to remove the wrench and get this result.

The build resources can be viewed here:

## Use “sdelete -z” when Shrinking a Windows Guest’s Virtual Hard Drive

I was installing Windows 7 in a VirtualBox Virtual Machine, and tried to shrink the dynamic virtual hard drive (vdi format). There are several guides out there explaining how to do this. SDelete is commonly used to zero out the virtual hard drive’s free space before compacting the hard drive file.  As the SDelete manual page states, “-z” is the correct option to use for this purpose.  However, many of the guides I read use the “-c” option.  This is counterproductive since it results in random data being written to the free space, thus causing the virtual hard drive file to expand to its maximum size (in my case, this filled my host PC’s hard drive).  This issue has been discussed quite a bit in forums and blog comments; “-c” at one time was the correct option to use, but the semantics of the “-c” and “-z” options changed with one of the recent SDelete releases (I understand it was with version 1.6).

Conclusion: With the latest version of SDelete, use the “-z” option when you are shrinking a virtual hard drive.

As a side note, it took a long time for SDelete to finish on my machine – I think it was because I made my virtual hard drive very large.  I chose a size much larger than I actually needed, since I thought there would be no disadvantage to having too much space (since it is a dynamic drive, the extra virtual space takes no physical space).  In hindsight, maybe I should have chosen a smaller size.

Update: I found this blog entry, which has a similar post.

## VirtualBox – PowerShell Script to Start a Virtual Machine with the Maximum Number of Monitors

With the help of a Plugable UGA-2K-A, I sometimes attach an extra monitor to my PC.  I have a VirtualBox virtual machine that I like to run across all of my physical monitors, and I used to manually change the virtual machine’s Monitor Count when connecting or disconnecting the extra monitor.  I now have a PowerShell script which automatically detects the number of monitors connected to my PC, sets the Monitor Count of the virtual machine, and then starts the machine.  I am using the script on a Windows 8 host. I posted the script in this GitHub Gist.

Update: I found this blog entry, which has a similar script (although some of the mechanics are different).

## Configuring OpenOCD with an Olimex ARM-USB-TINY-H in Ubuntu 12.04 64 bit

I have an Olimex ARM-USB-TINY-H JTAG programmer which I recently installed in Ubuntu 12.04 64 bit (running inside Virtualbox).  I am using the programmer with OpenOCD.  I had some old instructions I wrote up, which I updated to work with 12.04.  I had some issues (due to some stupid mistakes on my part) and I came across this post while doing research.  My instructions are generally the same, but they differ somewhat in the details.  I decided to post what I have in case it helps anyone out.

## Configure the Programmer

The programmer uses the FTDI chipset, so we need to install the FTDI drivers – we will use the libFTDI driver:

sudo apt-get install libftdi-dev libftdi1

Now Ubuntu should recognize the programmer when it is plugged in. But, by default it requires root privileges to use. Therefore, we need to set up a udev rule to change the permissions.  This rule assigns the device to the plugdev group – which was introduced in Linux for hot-pluggable devices – and then gives the group read and write access.  Make sure your user is in the plugdev group; my user was in it by default.

1. Create a file /etc/udev/rules.d/olimex-arm-usb-tiny-h.rules
2. Put this single line in the file:
SUBSYSTEM=="usb", ACTION=="add", ATTR{idProduct}=="002a", ATTR{idVendor}=="15ba", MODE="664", GROUP="plugdev"

## Install OpenOCD

1. Change into the directory where you will download and build OpenOCD. I use my home folder:
cd ~
2. You can download the distribution from the OpenOCD website, but I prefer to get the source code from its git repository.  If you go down this route, you will need to have some extra packages:
sudo apt-get install git libtool automake texinfo
3. Get the source code
git clone git://openocd.git.sourceforge.net/gitroot/openocd/openocd
cd openocd
4. Check the tags to see what versions are available (you can also reference the OpenOCD website):
git tag -l

The version distributed with my programmer was 0.3.0 , but that is way out of date at this point.  At the time of writing, the lastest version is 0.6.0, so that’s what I use:

git checkout v0.6.0
5. Do the build – this uses the libFTDI drivers we installed earlier:
./bootstrap
./configure --enable-maintainer-mode --enable-ft2232_libftdi
make
sudo make install

## Test OpenOCD

Make sure the programmer is plugged in to the computer and into a board/microcontroller, and then run openocd (use the appropriate target for your microcontroller).  If there is a problem connecting to your programmer, you should quickly get an error message about not being able to open the ftdi device:

openocd -f interface/olimex-arm-usb-tiny-h.cfg -f target/stm32f1x.cfg

## Troubleshooting tips

• If openocd cannot find your FTDI device, run openocd as root (e.g. using sudo).  If that works, then you have a permission issue.
• Run this command to view attached USB devices:
lsusb

You should see something similar to this line:

Bus 001 Device 002: ID 15ba:002a Olimex Ltd. ARM-USB-TINY-H JTAG interface
• Devices can be found under /dev/bus/usb/001/004 (in this example 001 is the bus and 004 is the device).  If the udev rule is working, this device file should have permissions as described above.  If the rule is not working, the device file will belong to the root group.
• A /dev/ttyUSB device is not created by default, and openocd does not need it if it is using libFTDI (the libFTDI driver does not rely on the kernel drivers).
• Run this command to get detailed attributes for a device – useful for modifying or troubleshooting a udev rule (substitue your bus and device number):
udevadm info -a -p  \$(udevadm info -q path -n /dev/bus/usb/001/004).
• Run this command to test your udev rule against the device and see why it does not work (substitue your bus and device number):
udevadm test /dev/bus/usb/001/004
• The OpenOCD interface and target cfg scripts are located under this folder by default: /usr/local/share/openocd/scripts

## Problem Using Windows Encryption with Dropbox Folder

I have Dropbox installed on my Windows 7 PC, and decided to encrypt the Dropbox folder for added protection.  While TrueCrypt seems popular, I decided to use Windows’ built-in encryption.  After some time, I noticed that some of the files in my Dropbox folder were not encrypted.  This was odd since the default Windows behavior is to automatically encrypt new files placed inside an encrypted folder.  Eventually, I figured out that when Dropbox creates a file (by syncing it from another PC), the new file is not being encrypted.  I tried the following tests:

1. I created a new file locally under the Dropbox folder.  It was automatically encrypted.  This is normal behavior.
2. I copied an existing local file from another folder into the Dropbox folder, it was also automatically encrypted.  Again, this is normal behavior.
3. I created a file on another machine, and let Dropbox sync it to my Windows 7 PC.  The synced file was not encrypted.  This is not what I expected to happen – I expected it to be encrypted like in tests 1 and 2.

The folder looks like this after the tests (Windows highlights the encrypted folders green):

My interim solution is to occasionally re-encrypting the entire folder at the command line using this command:

cipher /E /S:c:\User\XYZ\Dropbox

After which I am supposed to run this command for good measure (I understand this command wipes the free space on the whole C: drive):

cipher /W:c:\Users\XYZ\Dropbox

It is recommended that you exit Dropbox during this process to free any file locks it may have (don’t forget to start it back up afterwards).  This is my first experience with the cipher command, but it appears to work.  It would be nice to be able to stop and start Dropbox from the command line as well, but I haven’t found a good way to do it yet.

I contacted Dropbox support, and they recommended that I just use volume-based encryption (like TrueCrypt) and avoid Windows encryption altogether.