foodcost – The Industrious Squirrel https://blog.chadweisshaar.com Sat, 10 Aug 2013 03:06:58 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.3 https://blog.chadweisshaar.com/wp-content/uploads/2016/07/favicon.png foodcost – The Industrious Squirrel https://blog.chadweisshaar.com 32 32 Scoring the Nutrition of Foods https://blog.chadweisshaar.com/2013/08/09/scoring-the-nutrition-of-foods/ https://blog.chadweisshaar.com/2013/08/09/scoring-the-nutrition-of-foods/#respond Sat, 10 Aug 2013 03:06:19 +0000 http://gator3305.temp.domains/~cweissha/blog/?p=405 Continue reading "Scoring the Nutrition of Foods"]]> Part of the Food Cost Calculator project is to determine the nutritional value of different foods. The program can be used to calculate the cost of a food per calorie or weight. But I also want it to calculate the overall nutritional value of the food and the cost per nutrient.

There are certainly a lot of different opinions about what makes a food healthy. The program will have flexibility for a user to set up the scoring system based on the nutrients available in the USDA database.

One way to score a food is to calculate how much of the recommended vitamins/minerals the food provides. Another thing to consider may be the amount of fat/carbohydrate/protein in the food.

This post will describe the scoring system in the food cost program and how I setup the scoring system for myself.

The score of a food is independent of the number of calories in a particular amount of the food. When a food is scored, the program pretends that food is the only thing you ate all day. So if it is scoring a 200 calorie food and you want 2000 calories per day, it will multiply all the nutrient amounts by 10.

All the nutrients that the program tracks aren’t equally important. People have different dietary goals or restrictions, so the program lets the user set a “weight” for each nutrient. A particular nutrient can score up to its “weight” in points. I setup my weights so that they add up to 100. That way a food can, at most, score 100 points.

Once the nutrient amounts have been scaled to a full day of calories, each nutrient amount is compared to the desired range of that nutrient. If the amount is within the desired range the score is 100% of the weight. If it is outside the range the score is reduced.

ScoreGraphThere are three types of nutrients.

  • “Good” nutrients where you want at least X grams. For this type of nutrient, I set the min to the amount that I want and the max to infinity.
  • “Good in moderation” nutrients, where you want between the min and the max.
  • “Bad” nutrients where you want no more than X grams. For this type of nutrient, I set the min to zero and the max to the most I want to get in a day.

Vitamins and Minerals

The FDA publishes several guidelines for how much of each vitamin and mineral a person needs. First is the “Dietary Reference Intakes: Recommended Dietary Allowance” which is the minimum daily intake to satisfy the needs of 97% of people. They also publish a “Dietary Reference Intakes: Tolerable Upper Intake” which is the highest daily intake that should pose no risk to otherwise healthy people. Some vitamins and minerals have no upper limits.

I am not certain that these are definitive values, the science is probably somewhat fuzzy and there are probably variations by weight and activity level that aren’t captured in these recommendations. But they are reasonable values.

Fats

The FDA recommends that adults get 20-35% of their calories from fat. Of course this recommendation is controversial, with different groups and diets recommending widely different values. I personally agree with this recommendation and feel that the important factor is the type of fat. The RDA recommends keeping consumption of saturated fat and trans fat as low as possible and getting 5-10% of calories from omega-6, 0.6-1.2% of calories from omega-3. I set the daily limits for trans fat and saturated fat to 5 grams and 1 gram respectively.

Carbohydrates and Protein

The FDA recommends that adults get 45-65% of their calories from carbohydrates and 10-35% from protein. Like the fat recommendation, there isn’t much agreement between different diets about these numbers, but they seem reasonable to me.

The FDA recommends 38 grams of fiber per day. This number is independent of calories. They also recommend that added sugars make up less that 25% of the calories. Unfortunately, the USDA database doesn’t distinguish between “added” sugars and naturally occurring sugars. I feel like 25% of calories from added sugar is too much, so I just went with 25% of calories from any sugar.

Cholesterol

The FDA includes cholesterol in the list of nutrients that you should limit to as little as possible. The American Heart Association recommends no more that 300 mg per day. However, recent studies have shown very little correlation between dietary cholesterol and blood cholesterol. I set my daily maximum to 500 mg.

Sodium and Potassium

The FDA recommends 1500-2300 mg of sodium for people under 50, 1300-2300 mg between 50 and 70 and 1200-2300 mg for people over 70. The American Heart Association recommends no more than 1500 mg per day. I feel like I am easily affected by salt and so I should limit my intake. I set my range from 1200-1500 mg.

The FDA recommends at least 4700 mg of potassium per day.

All nutrient ranges and weights

[table]

Nutrient, Minimum, Maximum, Weight
Calories,1700,1900,0
Fat(g),40,70,5
Saturated fat(g),0,5,5
Monounsaturated fat(g),25,40,2
Polyunsaturated fat(g),15,30,2
Omega-3(g),1.2,2.4,2
Omega-6(g),10,20,2
Trans fat(g),0,1,5
Cholesterol(mg),0,500,2
Sodium(mg),1200,1500,7
Potassium(mg),4700,–,7
Carbohydrate(g),203,293,5
Fiber(g),38,–,8
Sugar(g),0,112,8
Protein(g),45,157,15
Vitamin A,900,3000,1
Vitamin E,15,1000,1
Vitamin D,15,100,1
Vitamin C,90,2000,1
Vitamin K,120,–,1
Thiamin (B1),1.2,–,1
Riboflavin (B2),1.4,–,1
Niacin (B3),16,35,1
Pantothenic acid (B5),5,–,1
Vitamin B6,1.3,100,1
Folate DFE (B9),400,1000,1
Vitamin B12,2.4,–,1
Calcium,1000,–,1
Iron,6,–,1
Magnesium,420,–,1
Phosphorus,700,–,1
Zinc,11,–,1
Copper,0.7,–,1
Manganese,2.3,–,1
Selenium,55,–,1
Water(g),2800,–,5
[/table] ]]> https://blog.chadweisshaar.com/2013/08/09/scoring-the-nutrition-of-foods/feed/ 0 Programming the Food Cost Calculator https://blog.chadweisshaar.com/2013/08/04/programming-the-food-cost-calculator/ https://blog.chadweisshaar.com/2013/08/04/programming-the-food-cost-calculator/#respond Sun, 04 Aug 2013 19:54:54 +0000 http://gator3305.temp.domains/~cweissha/blog/?p=392 Continue reading "Programming the Food Cost Calculator"]]> This blog post describes some of the design decisions I made, and programming challenges I encountered, while writing the food cost calculator application. This post is probably too detailed for anyone to read. Consider yourself warned.

Language

I decided to write this program in C#. I find it easy to create GUIs with Visual Studio and .NET, and I have already written database and data display code for the MediaDB and PriceTracker in C#. My original food program is in C++, so I considered using C++ .NET, but I really dislike the look of managed C++ code.

Entity Data Model

Some features have been added to the C# language since the last time I did a large project, and I wanted to try out the Entity Data Model and the built in database designer. I was limited by not owning the full version of Visual Studio and by not wanting to have to run a full database server on the client machines. I first tried to make an SQL Express database, then I tried to use the LINQ version of SQLite. After much trial and error with Visual Studio and different versions of the SQLite.NET wrappers, I was able to get it to work; but I found that it was very difficult to manipulate the displayed data independent from the database. The DataSet makes it very easy to pull some or all the rows from a table and display them on a DataGridView. Edits on the GUI are replicated in the DB automatically. But if you want to filter or sort, you have to go back to the database. If you want to have derived fields on the display you have to write a bunch of connector code. So I gave up and manually built a small SQLite database accessed with straight SQL commands.

Building the food database

I use the USDA’s SR and FNDDS databases to populate my database of foods. The SR database is the “National Nutrient Database for Standard Reference” and contains the nutrient values for thousands of raw foods. The FNDDS database is the “Food and Nutrient Database for Dietary Studies” and has some packaged foods and more human-readable food names for things in the SR database. These databases have data for more nutrients and foods than I care about, so the DB loader screen lets me pick a sub-set of nutrients/foods. For the FoodDiary program, I used the USDA SR database, so I was able to re-use some of the code from that project.

Ribbon

I wanted to try out Microsoft’s ribbon UI style in this program. It is a separate download and has to be manually added to the Visual Studio GUI builder. Once this was done, I tried to use it and found that the visual style looked like Vista instead of Windows 8. After doing some research online, it seems that Microsoft has given up development of the .NET ribbon for non WPF applications. I briefly tried the WPF version. I worked better, but getting the appearance correct was still a very manual process. If Microsoft really wants the ribbon to be adopted by third parties, they need to make it easier for programmers to use.

Data Display

My plan for the program’s main GUI is to display a searchable and sortable list of foods and a separate list of recipes. There will also be a toolbar with buttons to bring up dialogs for creating foods/recipes, editing the food scoring algorithm and editing the energy costs.

To display the list of foods and recipes I use the DataGridView. It is one of the most flexible and useful classes in .NET. It links to any List<T> and lets you display the fields of T as columns in the grid. User edits/adds/deletes are replicated back to the underlying data. There are lots of events that you can listen for, and you can make your own custom columns or cells. I have used this class in every C# project that I have built. However, I have never needed to do quite as much customization as I did for this project. For this project, I wanted to use a combo box to display the possible foods and measures. The problem that I encountered was the limitation that a column that displays data as a ComboBox has to have the same set of pull-down options for the whole grid. This is fine in a lot of cases (like month, state, sex, etc). But I wanted to do two unsupported things: One was to filter the list of foods based on what has been typed so far. The second was to display the list of measures valid for just the food on the current row.

IngredientEntryForm

To get the list of available measures to match the food on that row, I created a custom column and cell that updated its items any time the row’s food changed. I was able to use the built in ComboBoxCellEditor for this column with the slight wrinkle of converting the ComboBoxCellEditor’s string to my Measure object when the edit is complete.

The food column was more complicated. As the user types in the food column, I wanted to filter the list of foods and color the foods that the user has used before. To get this to work, I had to create a custom column, cell and cell editor. The cell editor is a panel with a text box for the user to type in and a list view showing the foods that match.

I spent a lot of time on these two columns. The .NET documentation is missing some key information about how the DataGridView works underneath. A timeline of which events fire when the user does different thing to the grid would have saved me lots of time. It also doesn’t help that there are three different data grids in .NET:

  • System.Web.UI.WebControls.DataGrid – introduced in 1.0
  • System.Windows.Forms.DataGridView – introduced in 2.0
  • System.Windows.Controls.DataGrid – introduced in 4.0

This is a problem with the whole .NET framework. They have built three full GUI systems and still support all three in the same framework. I was mostly using System.Windows.Forms.*, but some things (common enumerations, utility stuff) comes from the old 1.0 systems. Another big problem with having multiple systems in .NET is that it is difficult to find help online without finding answers for the other two systems.

Generic accessors and functional programming

Two features of C# that didn’t exist when I learned the language (.NET 2.0) are very nice. The first is generic accessors where C# will assume a hidden member and a basic accessor. Here is example code in C++, C# 2.0 and C# 3.0:

// C++
private: int myCount;
public:
int count() const { return myCount; }
void count(int value) { myCount = value; }
// C# 2.0
private int myCount;
public int Count { get { return myCount; } set { myCount = value; } }

// C# 3.0
public int Count { get; set; }

The second is the LINQ system of functional programming. I didn’t really get to use its capabilities for database queries, but I really appreciated the lambda expressions and extension methods. Here are two examples of how they save a bunch of typing:

// Old
List<NutrientAmount> setNutrients = new List<NutrientAmount>();
foreach ( Nutrient n in displayedNutrients )
  if ( n.Amount > 0 )
    setNutrients.Add(n);

double totalScore = 0;
foreach ( int key in Nutrient.allNutrients.Keys )
  totalScore += nutrientScore(key);
totalScore /= 100;

// New
var setNutrients = displayedNutrients.Where(n => n.Amount > 0).ToList();
double totalScore = Nutrient.allNutrients.Keys.Sum(key => nutrientScore(key))/100);

Searching foods

Searching for a food is a very common task in this program and I wanted it to work as well as possible. As the user types into the search box, the displayed lists updates automatically. Only foods that match at least one of the words the user has entered are displayed and the sort order takes into account how many of the words match, how many times the food has been used in a recipe, whether the food has been edited or created by the user, and the length of the name of the food. I am pretty happy with the results and can usually find the right food quickly.

]]>
https://blog.chadweisshaar.com/2013/08/04/programming-the-food-cost-calculator/feed/ 0
Home Cooking Costs Project https://blog.chadweisshaar.com/2013/07/09/home-cooking-costs-project/ https://blog.chadweisshaar.com/2013/07/09/home-cooking-costs-project/#respond Tue, 09 Jul 2013 23:44:44 +0000 http://gator3305.temp.domains/~cweissha/blog/?p=389 Continue reading "Home Cooking Costs Project"]]> I read the book Make the Bread, Buy the Butter: What You Should and Shouldn’t Cook from Scratch a few months ago and it got me thinking about the cost of cooking at home. I recommend the book (and/or her blog) for the personal stories and recipes as much as for her advice about what to make at home. The stories are funny and the recipes have been consistently good. But everyone is different in how much they value their time and enjoy cooking; and the book is targeted toward people who consider cooking a hobby and are willing to do in their free time.

I enjoy cooking and have lots of free time, so her advice is pretty good for me. If she says you should buy it, you should buy it. I thought that I had found one exception: Rice pudding. I figured that she just didn’t try (or want to recommend) using a pressure cooker. My rice pudding was pretty good, especially warm, but Kosy Shack was better, especially the next day. And tapioca is better anyway.

Each recipe in the book has a cost to make and the price to buy. I double-checked her prices for the first few recipes that I made and they were pretty close. A direct comparison is difficult in many cases because the store-bought item and homemade item are too different (hot-dog buns are a prime example).

As I got more curious about how much different foods cost to make, I started to wonder which of the things I eat are the best value and how home cooking compares to dining out in terms of cost. I also wanted to consider the nutritional value of the foods and to include (like the book did) the energy costs involved. I started tracking this in a spreadsheet, but it was too much hassle to keep track of which foods I’d entered already and to do all the conversions between different amounts of foods. So I started looking for software that would help.

Nine years ago I created a FoodDiary program because I was curious about how nutritious my diet was. Was I getting all the vitamins and minerals that I needed? What about all the amino acids? This was about the time that I was giving up beef and pork and I was worried about missing some proteins (I wasn’t). I considered re-writing that program to track food costs but I was turned off by the idea of revisiting the old wxWindows (a C++ graphics library) code. Instead I downloaded the trial version of the popular Living Cookbook software. Their software is pretty nice, and it allows you to track food costs and will figure the cost of a recipe. It has some pretty severe limitations though:

  • You had to enter a food price for a particular quantity (their choice) of the food
  • When you updated a food, the program had to update all the recipes that contained that food. This process took 15-30 seconds for common foods.
  • A recipe couldn’t contain another recipe.
  • When entering a recipe you have to enter each ingredient twice: once for the description and once for the nutrition data.
  • There is no way to “score” a food. You can look at the amount of each nutrient, but there is no way to consider it as a whole. This was the main focus of my FoodDiary software.

So I finally decided to write a new program to do exactly what I wanted. I probably come to this conclusion a bit too easily and often. I think it’s because it is so easy to underestimate how hard the program will be to write. I had the same problem when I was getting paid to program: I’d take my best guess, double it, and often be way under.

]]>
https://blog.chadweisshaar.com/2013/07/09/home-cooking-costs-project/feed/ 0