Example #1
0
    def insert_one(self, activity):

        new_activity = Activity()

        if "activity" in activity:
            new_activity.activity = activity["activity"]

        if "user_id" in activity:
            new_activity.user = User.objects.get(pk=activity["user_id"])

        new_activity.save()
        return False if new_activity.pk is None else new_activity
def add_activity(request):
    """
	Add new person into MySQL databases
	Http form MUST includes `name`, `date` and `time`
	:param request: httpRequest
	:return: status (success or fail), err_info and err_code
	"""
    if request.method == 'POST' and token_check(request):

        try:
            activity_info = json.loads(
                request.body.decode('utf-8'))['activity']

            new_activity = Activity(
                name=activity_info['name'],
                date=activity_info['date'],
                time=activity_info['time'],
                place=activity_info['place']
                if 'place' in activity_info.keys() else '',
                participation=activity_info['participation']
                if 'participation' in activity_info.keys() else 0,
                participator=activity_info['participator']
                if 'participator' in activity_info.keys() else '',
                content=activity_info['content']
                if 'content' in activity_info.keys() else '',
                images=activity_info['images']
                if 'images' in activity_info.keys() else '')

            participators = new_activity.participator.split(',')

            for stu_num in participators:
                person = Person.objects.get(student_number=stu_num)
                person.participation += int(new_activity.participation)
                person.save()

            new_activity.save()

            return JsonResponse({'status': 'success'})

        except DatabaseError as e:
            return JsonResponse({
                'status': 'fail',
                'err_code': e.args[0],
                'err_info': e.args[1],
            })
Example #3
0
class FITParser:
    activity_data = None
    activity = None
    records = None
    laps = None
    power = None
    tz_offset = None
    decoded = None

    def parse_fit(self, file: InMemoryUploadedFile):
        # TODO: Bulk update?
        self.decoded = FitFile(file.read())

        records = [r for r in self.decoded.get_messages(name='record')]
        self.set_offset()

        self.load_records(records)

        self.load_activity()

        self.load_laps()

        Lap.objects.bulk_create(self.laps)

        for j in range(len(self.laps)):
            for i in range(self.laps[j].record_start,
                           self.laps[j].record_end + 1):
                self.records[i].activity = self.activity
                self.records[i].lap = self.laps[j]

        Record.objects.bulk_create(self.records)

    def set_offset(self):
        self.activity_data = [
            r for r in self.decoded.get_messages(name='session')
        ][0]

        lat = self.activity_data.get_value('start_position_lat') * 180 / 2**31
        long = self.activity_data.get_value(
            'start_position_long') * 180 / 2**31

        tzw = tzwhere.tzwhere()
        tz = pytz.timezone(tzw.tzNameAt(lat, long))
        start_time = self.activity_data.get_value('start_time')

        self.tz_offset = tz.utcoffset(start_time)

    def find_max(self, k):
        t = sum(self.power[:k])
        m = t

        for i in range(len(self.records) - k):
            t -= self.power[i]
            t += self.power[i + k]
            if t > m:
                m = t

        return {'duration': k, 'power': m / k}

    def load_curve(self):
        activity_curve = [0 for _ in range(len(self.records) // 5 + 1)]
        self.power = [r.power for r in self.records]

        pool = Pool(processes=4)
        activity_curve = pool.map(
            self.find_max,
            [1 if a == 0 else a * 5 for a in range(len(activity_curve))])
        pool.join()
        pool.close()
        activity_curve = sorted(activity_curve, key=lambda x: x['duration'])
        print(activity_curve)
        print(self.activity.max_power)

        power_curve = PowerCurveEntry.objects.all()

        i = 0
        while i < len(power_curve) and i < len(activity_curve):
            if activity_curve[i] > power_curve[i].power:
                power_curve[i].power = activity_curve[i]
                power_curve[i].activity = self.activity
                power_curve[i].save()
            i += 1

        for i in range(len(power_curve), len(activity_curve)):
            entry = PowerCurveEntry()
            entry.activity = self.activity
            entry.power = activity_curve[i]
            entry.duration = 1 if i < 1 else i * 5
            entry.save()

    def load_activity(self):
        self.activity = Activity(
            start_time=pytz.utc.localize(
                self.activity_data.get_value('start_time') + self.tz_offset),
            elapsed_time=self.activity_data.get_value('total_elapsed_time'),
            start_position_lat=self.activity_data.get_value(
                'start_position_lat'),
            start_position_long=self.activity_data.get_value(
                'start_position_long'),
            timer_time=self.activity_data.get_value('total_timer_time'),
            distance=self.activity_data.get_value('total_distance'),
            strides=self.activity_data.get_value('total_strides'),
            speed=self.activity_data.get_value('enhanced_avg_speed'),
            max_speed=self.activity_data.get_value('enhanced_max_speed'),
            calories=self.activity_data.get_value('total_calories'),
            ascent=self.activity_data.get_value('total_ascent'),
            descent=self.activity_data.get_value('total_descent'),
            lap_count=self.activity_data.get_value('num_laps'),
            heart_rate=self.activity_data.get_value('avg_heart_rate'),
            max_heart_rate=self.activity_data.get_value('max_heart_rate'),
            cadence=self.activity_data.get_value('avg_running_cadence'),
            max_cadence=self.activity_data.get_value('max_running_cadence'),
            aerobic_training_effect=self.activity_data.get_value(
                'total_training_effect'),
            anaerobic_training_effect=self.activity_data.get_value(
                'total_anaerobic_training_effect'),
            max_power=0,
            power=0)

        for r in self.records:
            if r.power > self.activity.max_power:
                self.activity.max_power = r.power
            self.activity.power += r.power

        self.activity.power /= len(self.records)

        self.activity.save()

    def load_laps(self):
        self.laps = [
            Lap(activity=self.activity,
                start_time=pytz.utc.localize(
                    lap.get_value('start_time') + self.tz_offset),
                end_time=pytz.utc.localize(
                    lap.get_value('timestamp') + self.tz_offset),
                start_position_lat=lap.get_value('start_position_lat'),
                start_position_long=lap.get_value('start_position_long'),
                end_position_lat=lap.get_value('end_position_lat'),
                end_position_long=lap.get_value('end_position_long'),
                elapsed_time=lap.get_value('total_elapsed_time'),
                timer_time=lap.get_value('total_timer_time'),
                distance=lap.get_value('total_distance'),
                strides=lap.get_value('total_strides'),
                speed=lap.get_value('enhanced_avg_speed'),
                max_speed=lap.get_value('enhanced_max_speed'),
                calories=lap.get_value('total_calories'),
                ascent=lap.get_value('total_ascent'),
                descent=lap.get_value('total_descent'),
                heart_rate=lap.get_value('avg_heart_rate'),
                max_heart_rate=lap.get_value('max_heart_rate'),
                cadence=lap.get_value('avg_running_cadence'),
                max_cadence=lap.get_value('max_running_cadence'),
                lap_trigger=lap.get_value('lap_trigger'),
                power=lap.get_value('Lap Power'))
            for lap in self.decoded.get_messages(name='lap')
        ]

        for lap in self.laps:
            ground_time = 0
            air_power = 0
            form_power = 0

            j = 0
            while j < len(self.records
                          ) and self.records[j].timestamp < lap.start_time:
                j += 1
            lap.record_start = j
            while j < len(self.records
                          ) and self.records[j].timestamp <= lap.end_time:
                ground_time += self.records[j].ground_time
                air_power += self.records[j].air_power
                form_power += self.records[j].form_power
                j += 1
            if j == lap.record_start:
                break
            lap.record_end = j - 1
            lap.ground_contact = ground_time / lap.timer_time
            lap.air_power = air_power / lap.timer_time
            lap.form_power = form_power / lap.timer_time

    def load_records(self, records):
        self.records = [
            Record(
                timestamp=pytz.utc.localize(
                    r.get_value('timestamp') + self.tz_offset),
                position_lat=r.get_value('position_lat') * 180 / (2**31),
                position_long=r.get_value('position_long') * 180 / (2**31),
                distance=r.get_value('distance'),
                speed=r.get_value('enhanced_speed'),
                altitude=r.get_value('enhanced_altitude'),
                heart_rate=r.get_value('heart_rate'),
                cadence=r.get_value('cadence'),
                power=r.get_value('Power'),
                ground_time=r.get_value('Ground Time'),
                air_power=r.get_value('Air Power'),
                form_power=r.get_value('Form Power'),
            ) for r in records if r.name == 'record'
        ]
Example #4
0
def importDataFromExcel(file, year=2019):
    wb = openpyxl.load_workbook(file, data_only=True, read_only=True)
    sheet = wb._sheets[0]

    locale.setlocale(locale.LC_ALL, 'sv_SE')

    events = dict()
    eventTypes = dict()
    activityTypes = dict()
    n = 0
    et_name = None

    try:
        for cols in sheet.rows:
            n += 1
            if n <= 9:
                continue

            if cols[0].value is None and et_name is None:
                continue

            et_name = cols[0].value or et_name
            et = eventTypes.get(et_name)
            if et is None:
                #logger.info(f"Event type {et_name}")
                try:
                    et = EventType.objects.get(name=et_name)
                except EventType.DoesNotExist:
                    et = EventType(name=et_name)
                    et.save()
                eventTypes[et_name] = et

            if cols[2].value is None:
                break

            event_name = f"{et_name} vecka {cols[1].value}"

            date = cols[2].value
            if year is not None:
                date = date.replace(year=year)

            event = events.get((event_name, date))

            if event is None:
                #logger.info(f"Event {event_name} {date}")
                try:
                    event = Event.objects.get(name=event_name,
                                              start_date=date,
                                              type=et)
                except Event.DoesNotExist:
                    event = Event(name=event_name,
                                  start_date=date,
                                  end_date=date,
                                  type=et)
                    event.save()

                    coord = cols[19].value

                    if coord is not None:
                        if ' ' in coord:
                            first, last = coord.split(' ', maxsplit=1)
                        else:
                            first = coord

                        try:
                            coordinator = Member.objects.get(
                                user__first_name=first, user__last_name=last)
                            event.coordinators.add(coordinator)
                        except Member.DoesNotExist:
                            print(
                                f"Failed to find member {coord} to use as coordinator for {event_name}"
                            )

                events[event_name] = event

            at_name = cols[5].value
            at = activityTypes.get(at_name)
            if at is None:
                #logger.info(f"Activity Type: {at_name}")
                try:
                    at = ActivityType.objects.get(name=at_name)
                except ActivityType.DoesNotExist:
                    at = ActivityType(name=at_name)
                    at.save()
                activityTypes[at_name] = at

            ebd = cols[18].value

            activity = Activity(
                name=f"{at_name} {calendar.day_name[date.weekday()]}",
                event=event,
                type=at,
                earliest_bookable_date=ebd)

            interval = cols[4].value.replace('—', '-').replace('–', '-') \
                .replace(' ', '').replace('.', ':')

            try:
                (start_time, end_time) = interval.split('-')
            except ValueError as e:
                logger.error(e)
                logger.error(interval)

            #logger.info(f'{activity.name} {interval}')
            (sh, sm) = start_time.split(':')
            (eh, em) = end_time.split(':')
            activity.start_time = datetime.time(hour=int(sh), minute=int(sm))
            activity.end_time = datetime.time(hour=int(eh), minute=int(em))

            activity.full_clean()
            activity.save()

        print(f'''Database row count:
            {EventType.objects.all().count()} event types
            {ActivityType.objects.all().count()} activity types
            {Event.objects.all().count()} events
            {Activity.objects.all().count()} activities'''.replace(
            '    ', ' '))

    except:
        print(f"Error on row {n}")
        raise