def test_guess_weight(self): result = guess(23, 'g') self.assertEqual( result, Mass(g=23) )
def calculate_priming_sugar(priming_temperature, beer_volume, carbonation_level, sugar_type="TABLE_SUGAR"): """ :param float priming_temperature: Temperature of beer in fahrenheit :param float beer_volume: Volume of beer to prime in gallons US :param float carbonation_level: Desired carbonation level :return Weight: Weight of table sugar to use """ amount = ( 15.195 * beer_volume * (carbonation_level - 3.0378 + (0.050062 * priming_temperature) - (0.00026555 * (priming_temperature ** 2))) ) if sugar_type == "CORN_SUGAR": amount = amount + amount*0.1 elif sugar_type == "DRY_EXTRACT": amount = amount + amount*0.46 return Mass(g=amount)
def calculate_run(act): # Get the query parameters and merge in the activity params = request.args params.update({'activity': act}) form = forms.CalculateRunForm(params) if not form.validate(): return jsonify({ 'status': 'ERROR', 'errors': form.errors }), 400 try: calories = calorie_calculator.calculate_calories_burned( activity=getattr(activity, act.capitalize())(), # Distance in miles or kilometers, depending on "units" value distance=Distance(**{'mi' if form.units.data == 'imperial' else 'km': form.distance.data}), # Bodyweight in pounds or kilograms, depending on "units" value bodyweight=Mass(**{'lb' if form.units.data == 'imperial' else 'kg': form.bodyweight.data}), # Elevation gain in meters or feet, depending on "units" value elevation_gain=Distance(**{'ft' if form.units.data == 'imperial' else 'm': form.elevation_gain.data}), duration=timedelta( hours=int(form.hours.data), minutes=int(form.minutes.data), seconds=int(form.seconds.data) ) ) except Exception as e: return jsonify({ 'status': 'ERROR', 'message': str(e), }), 500 return jsonify({ 'status': 'SUCCESS', 'calories': calories, }), 200
def weight(self, value): self._weight = value if isinstance(value, Mass) else Mass(g=value)
from rest_framework.test import APIClient from model_bakery import baker from model_bakery.generators import random_gen from measurement.measures import Volume, Mass, Temperature from brivo.utils.measures import BeerColor, BeerGravity from brivo.users.models import User, UserProfile, UserBrewery from brivo.brewery.models import Style from brivo.users.tests.factories import UserFactory baker.generators.add('brivo.brewery.fields.BeerColorField', lambda: BeerColor(srm=10)) baker.generators.add('brivo.brewery.fields.BeerGravityField', lambda: BeerGravity(plato=10)) baker.generators.add('brivo.brewery.fields.VolumeField', lambda: Volume(l=10)) baker.generators.add('brivo.brewery.fields.MassField', lambda: Mass(kg=1)) baker.generators.add('brivo.brewery.fields.TemperatureField', lambda: Temperature(c=10)) baker.generators.add('modelcluster.fields.ParentalKey', random_gen.gen_related) ROOT_DIR = Path(__file__).resolve(strict=True).parent @pytest.fixture(autouse=True) def media_storage(settings, tmpdir): settings.MEDIA_ROOT = tmpdir.strpath @pytest.fixture def user(): user = UserFactory()
def test_mul__raise_for_same_type(self): with pytest.raises(TypeError) as e: Mass("1 kg") * Mass("1 kg") assert str(e.value) == "can't multiply type 'Mass' and 'Mass'"
from ..modules.converter import Converter from ..modules.utils import Measurement dist_convert = Converter(Distance(), return_unconverted=True) def test_convert_distance(): conversion_mi = next(dist_convert.convert([Measurement('1', 'mile')])) assert conversion_mi == Measurement('1609.34', 'm') conversion_ft = next(dist_convert.convert([Measurement('1', 'foot')])) assert conversion_ft == Measurement('0.3', 'm') no_conversion = next(dist_convert.convert([Measurement('1', 'm')])) assert no_conversion == Measurement('1.0', 'm') conversion_compound = list( dist_convert.convert( [Measurement('two', 'foot'), Measurement('five', 'inch')])) assert conversion_compound == [ Measurement('two', 'foot'), Measurement('five', 'inch') ] mass_convert = Converter(Mass()) def test_convert_mass(): conversion_kg = next(mass_convert.convert([Measurement('5', 'kg')])) assert conversion_kg == Measurement('5000.0', 'g')
def smooth_zero_weight_logs(user, method="lerp"): """ Resolves/updates log entries where user=user and weight=0 method is a string 'previous_avg' Replaces these weights with the average of the last 10 entries excluding other weight=0 entries 'lerp' Replace these weights with the linearlly interpolated weight using the previous nonzero weight, date and the next nonzero weight, date NOTE: lerp may allow weight=0 entries to remain in cases where there is no bounding nonzero weights available """ if method == "previous_avg": all_weights = list( Log.objects.filter(user=user).values_list( "date", "weight").order_by("date")) # list of tuples (date, weight) for i in range(len(all_weights)): entry = all_weights[i] # (date, weight) if entry[1] == Mass(g=0.0): # get last 10 weights previous = all_weights[i - 11:i - 1] # print("previous 10 weights", previous) # remove entries where weight is 0 previous = [ value[1] for value in previous if value[1] != Mass(g=0.0) ] # print("previous 10 weights without 0s", previous) # calculate average. if there is no elements in previous, set average to 0 if len((previous)): average = sum([value.lb for value in previous]) / len(previous) else: average = 0 # update this entry with average Log.objects.filter(user=user).filter(date=entry[0]).update( weight=Weight(lb=average)) print( "Updated", entry[0].strftime("%m/%d/%Y"), "with weight", Weight(lb=average), ) if method == "lerp": # first get all weight, dates as list of tuplesall_weights = list( all_logs = (Log.objects.filter(user=user).values_list( "date", "weight").order_by("date")) # list of tuples (date, weight) dates, weights = [e[0] for e in all_logs], [e[1] for e in all_logs] nonzeroweight_indices = [ i for i, e in enumerate(weights) if e != Weight(g=0) ] for i in range(len(dates)): if weights[i] == Weight(g=0): print("index", i, "has weight 0") # find previous date and weight that is non zero previous_found = next_found = False prev_search_index = next_search_index = i while prev_search_index >= 0 and previous_found == False: if prev_search_index in nonzeroweight_indices: w1 = weights[prev_search_index] y1 = dates[prev_search_index] previous_found = True else: prev_search_index -= 1 # find next date and weight that is non zero while next_search_index < len(weights) and next_found == False: if next_search_index in nonzeroweight_indices: w2 = weights[next_search_index] y2 = dates[next_search_index] next_found = True else: next_search_index += 1 if not (next_found and previous_found): # print("ERROR, failed to find a valid bounding weight entry") # print("next_found", next_found) # print("previous_found", previous_found) continue else: interpolated_weight = interpolate(w1, w2, y1, y2, dates[i]) # print(w1.lb, w2.lb, y1, y2, dates[i]) # print("interpolated as", interpolated_weight.lb) # update this entry with interpolated_weight Log.objects.filter(user=user).filter(date=dates[i]).update( weight=interpolated_weight) print( "Updated", dates[i].strftime("%m/%d/%Y"), "with weight", interpolated_weight, )
import pytest from domain import activity, vo2, calorie_calculator from measurement.measures import Distance, Mass from datetime import timedelta testdata = [ # 0 distance and 0 duration, should get 0 (activity.Walk(), Distance(mi=0), Mass(lb=180), Distance(ft=0), timedelta(seconds=0), 0), # 175 lb athlete running a flat 2 miles at an 8 min/mile pace (activity.Run(), Distance(mi=2), Mass(lb=175), Distance(ft=0), timedelta(minutes=16, seconds=0), 278), # Marathon (activity.Run(), Distance(mi=26.2), Mass(lb=180), Distance(ft=0), timedelta(hours=3, minutes=29, seconds=56), 3743), # 100 mile ultramarathon (activity.Run(), Distance(mi=100), Mass(lb=190), Distance(ft=0), timedelta(hours=21, minutes=56, seconds=56), 15856), # Short uphill walk (activity.Walk(), Distance(mi=1.5), Mass(lb=165), Distance(ft=100), timedelta(minutes=15, seconds=32), 131), # Hiking the incline in Manitou, Colorado (activity.Walk(), Distance(km=1.65), Mass(lb=185), Distance(m=620), timedelta(minutes=31, seconds=15), 583), ] @pytest.mark.parametrize("activity,distance,bodyweight,elevation_gain,duration,expected", testdata) def test_calculate_calories_burned(activity, distance, bodyweight, elevation_gain, duration, expected): assert expected == calorie_calculator.calculate_calories_burned( activity=activity, distance=distance, bodyweight=bodyweight, elevation_gain=elevation_gain, duration=duration )
def test_guess_weight(): assert guess(23, "g") == Mass(g=23)