Skip to content

Commit

Permalink
Merge pull request #145 from anitagraser/better-format
Browse files Browse the repository at this point in the history
[WIP] pep8
  • Loading branch information
carolinux committed Oct 5, 2015
2 parents 01ca7bd + 951b1d2 commit 7fc8f0a
Show file tree
Hide file tree
Showing 52 changed files with 1,928 additions and 1,576 deletions.
5 changes: 4 additions & 1 deletion .travis.yml
Expand Up @@ -22,6 +22,7 @@ install:
- sudo apt-get install qgis --force-yes
- sudo apt-get install python-qgis
- sudo apt-get install vnc4server # to mock an X Server
- pip install pep8==1.4.6
- pip install mock
- pip install nose
- pip install coverage
Expand All @@ -34,7 +35,9 @@ before_script:
- psql -U postgres mydb -c "create extension postgis"
- psql -U postgres -c "ALTER USER postgres WITH PASSWORD 'postgres'";

script: bash run_tests.sh # this runs tests with coverage
script:
- bash run_tests.sh # this runs tests with coverage
- sh pep8.sh # run pep8 on the python code

after_success:
coveralls
2 changes: 2 additions & 0 deletions __init__.py
@@ -1,5 +1,7 @@
# -*- coding: UTF-8 -*-


def classFactory(iface):
from timemanager import timemanager

return timemanager(iface)
27 changes: 16 additions & 11 deletions animation/animate.py
@@ -1,48 +1,53 @@
import subprocess
import os
import glob
from collections import namedtuple

from ..logging import info, error
from ..os_util import *

IMAGEMAGICK="convert"
FFMPEG="ffmpeg"

IMAGEMAGICK = "convert"
FFMPEG = "ffmpeg"
DEFAULT_ANIMATION_NAME = "animation.gif"
DEFAULT_FRAME_PATTERN = "*.png"


def can_animate():
return is_in_path(IMAGEMAGICK)


def is_in_path(exec_name):
if get_os() == WINDOWS:
return False
try:
ret = subprocess.check_call([exec_name,"-h"])
ret = subprocess.check_call([exec_name, "-h"])
return ret == 0
except:
return False


def make_animation(out_folder, delay_millis, frame_pattern=DEFAULT_FRAME_PATTERN):
if not can_animate():
error("Imagemagick is not in path")
raise Exception("Imagemagick is not in path. Please install ImageMagick!")
out_file = os.path.join(out_folder, DEFAULT_ANIMATION_NAME)
all_frames = glob.glob(os.path.join(out_folder, frame_pattern))
fps = 1000/delay_millis
args = [IMAGEMAGICK,"-delay","1x"+str(fps)] + all_frames + [out_file]
ret = subprocess.check_call(args)
fps = 1000 / delay_millis
args = [IMAGEMAGICK, "-delay", "1x" + str(fps)] + all_frames + [out_file]
ret = subprocess.check_call(args)
if (ret != 0):
msg = "Something went wrong creating the animated gif from frames"
error(msg)
raise Exception(msg)
info("Exported {} frames to gif {} (call :{})".format(len(all_frames),out_file, args))
info("Exported {} frames to gif {} (call :{})".format(len(all_frames), out_file, args))


#ffmpeg -f image2 -r 1 -i frame%02d.png -vcodec libx264 -vf fps=25 -pix_fmt yuv420p out.mp4
# ffmpeg -f image2 -r 1 -i frame%02d.png -vcodec libx264 -vf fps=25 -pix_fmt yuv420p out.mp4
#http://unix.stackexchange.com/questions/68770/converting-png-frames-to-video-at-1-fps

def make_video(out_folder, settings):
# TODO in the future
pass
frames_glob = os.path.join(outFolder,"")
subprocess.check_call(["ffmpeg","-f","image2","-i",frames_glob,out_file])
frames_glob = os.path.join(outFolder, "")
subprocess.check_call(["ffmpeg", "-f", "image2", "-i", frames_glob, out_file])

122 changes: 72 additions & 50 deletions bcdate_util.py
@@ -1,40 +1,49 @@
import re
from datetime import datetime, timedelta

from PyQt4.QtCore import QDateTime
import PyQt4.QtCore as QtCore

from logging import warn
import conf


""" A module to support dates of BC/AD form"""

__author__="Karolina Alexiou"
__email__="karolina.alexiou@teralytics.ch"
__author__ = "Karolina Alexiou"
__email__ = "karolina.alexiou@teralytics.ch"


class CustomDate(object):
pass

_DIGITS = conf.DEFAULT_DIGITS # default digits for archaeology mode

_DIGITS = conf.DEFAULT_DIGITS # default digits for archaeology mode


def getGlobalDigitSetting():
return _DIGITS


def setGlobalDigitSetting(digits):
global _DIGITS
_DIGITS = digits


class ZeroFormatException(Exception):
pass


def get_max_dt():
return BCDate((10**getGlobalDigitSetting())-1)
return BCDate((10 ** getGlobalDigitSetting()) - 1)


def get_min_dt():
return BCDate(-1*((10**getGlobalDigitSetting())-1))
return BCDate(-1 * ((10 ** getGlobalDigitSetting()) - 1))


class BCDate(CustomDate):
def __init__(self, y,m=1,d=1):
def __init__(self, y, m=1, d=1):
self.digits = getGlobalDigitSetting()
self.y = y
self.m = m
Expand All @@ -44,161 +53,174 @@ def setDigits(self, d):
self.d = d

def isBC(self):
return self.y<0
return self.y < 0

def __cmp__(self, other):
if not isinstance(other, self.__class__):
return -1
if self.__lt__(other):
return -1
if self.__eq__(other):
if self.__eq__(other):
return 0
return 1

def __lt__(self, other):
if not isinstance(other, self.__class__):
return True
if (self.y< other.y or (self.y==other.y and self.m < other.m) or(self.y==other.y and self.d == other.d and self.d < other.d)):
if (self.y < other.y or (self.y == other.y and self.m < other.m) or (
self.y == other.y and self.d == other.d and self.d < other.d)):
return True
return False

def __str__(self):
year = self.y
if year>=0:
return str(year).zfill(self.digits)+" AD"
if year >= 0:
return str(year).zfill(self.digits) + " AD"
else:
return str(-year).zfill(self.digits) +" BC"
return str(-year).zfill(self.digits) + " BC"

def __repr__(self):
return self.__str__()

def as_datetime(self):
return datetime(self.y,self.m,self.d)
return datetime(self.y, self.m, self.d)

@classmethod
def from_str(cls, bc, strict_zeros = True):
def from_str(cls, bc, strict_zeros=True):
try:
m = re.match("(\d*)\s(AD|BC)",bc)
m = re.match("(\d*)\s(AD|BC)", bc)
year_str = m.group(1)
if strict_zeros and len(year_str)!= getGlobalDigitSetting():
raise ZeroFormatException("{} is an invalid date. Need a date string with exactly {} digits, for example {}"\
.format(bc, getGlobalDigitSetting() , "22".zfill(getGlobalDigitSetting())+" BC"))
if strict_zeros and len(year_str) != getGlobalDigitSetting():
raise ZeroFormatException(
"{} is an invalid date. Need a date string with exactly {} digits, for example {}"
.format(bc, getGlobalDigitSetting(),
"22".zfill(getGlobalDigitSetting()) + " BC"))
y = int(year_str)
bc = m.group(2)
if bc =="BC":
if bc == "BC":
y = -y
if bc not in ("BC","AD") or y==0:
if bc not in ("BC", "AD") or y == 0:
raise Exception
return BCDate(y)
except ZeroFormatException, z:
raise z
except Exception,e:
raise Exception("{} is an invalid archaelogical date, should be 'number AD' or 'number BC'".format(bc)+\
"and year 0 (use {} AD or BC instead) doesn't exist.".format("1".zfill(getGlobalDigitSetting())))
except Exception, e:
raise Exception(
"{} is an invalid archaelogical date, should be 'number AD' or 'number BC'".format(
bc) +
"and year 0 (use {} AD or BC instead) doesn't exist.".format(
"1".zfill(getGlobalDigitSetting())))

def __eq__(self, other):
if isinstance(other, self.__class__):
return self.y == other.y and self.m == other.m and self.d == other.d
else:
return False

def _get_years_from_timedelta(self,td):
def _get_years_from_timedelta(self, td):
try:
return td.years
except Exception,e:
#FIXME v.1.7 what about offset?
except Exception, e:
# FIXME v.1.7 what about offset?
msg = "BC dates can only be used with year intervals, found {}".format(td)
warn(msg)
return 0

@classmethod
def dist(cls, bc1, bc2):
if (bc1.y * bc2.y >0):
if (bc1.y * bc2.y > 0):
return bc1.y - bc2.y
else:
return bc1.y -bc2.y - 1
return bc1.y - bc2.y - 1

def __isub__(self,td):
def __isub__(self, td):
return self._iadd__(td * -1)

def __sub__(self,td):
def __sub__(self, td):
return self.__add__(td * -1)

def __iadd__(self, td):
if isinstance(td, BCDate):
to_add = td.y
else: # some sort of timedelta/relativedelta
else: # some sort of timedelta/relativedelta
to_add = self._get_years_from_timedelta(td)
self.y = self._get_new_year_value(self.y, to_add)
return self

def _get_new_year_value(self, old_y, to_add):
"""Adjust for absence of year zero"""
new_y = old_y + to_add
if ( new_y == 0 or new_y * old_y <0 ) and new_y<old_y:
if (new_y == 0 or new_y * old_y < 0) and new_y < old_y:
# if we went from AD to BC substract one for non-existant year 0
new_y-=1
elif ( new_y ==0 or new_y * old_y <0) and new_y>old_y:
new_y -= 1
elif (new_y == 0 or new_y * old_y < 0) and new_y > old_y:
# if we went from BC to AD add one for non-existant year 0
new_y+=1
new_y += 1
return new_y

def __add__(self, td):
if isinstance(td, BCDate):
to_add = td.y
else: # some sort of timedelta/relativedelta
else: # some sort of timedelta/relativedelta
to_add = self._get_years_from_timedelta(td)
return BCDate(self._get_new_year_value(self.y, to_add ))
return BCDate(self._get_new_year_value(self.y, to_add))

def __hash__(self):
return (self.y<<10) + (self.m<<4) + self.d
return (self.y << 10) + (self.m << 4) + self.d


BC_FORMAT = "Y with BC/AD"
SECONDS_IN_YEAR = 60 * 60 * 24 * 365

BC_FORMAT="Y with BC/AD"
SECONDS_IN_YEAR = 60 * 60 *24 *365

def _year(fdate):
return int(fdate.y)


def timeval_to_epoch(val):
if isinstance(val,str) or isinstance(val,unicode):
if isinstance(val, str) or isinstance(val, unicode):
return bcdate_to_epoch(str_to_bcdate(val))
if isinstance(val, BCDate):
return bcdate_to_epoch(val)


def timeval_to_bcdate(val):
epoch = timeval_to_epoch(val)
return epoch_to_bcdate(epoch)


def epoch_to_bcdate(seconds_from_epoch):
"""Convert seconds since 1970-1-1 (UNIX epoch) to a FlexiDate object"""
if seconds_from_epoch >= YEAR_ONE_EPOCH :
if seconds_from_epoch >= YEAR_ONE_EPOCH:
dt = datetime(1970, 1, 1) + timedelta(seconds=seconds_from_epoch)
return BCDate(dt.year, dt.month, dt.day)
else:
seconds_bc = abs(seconds_from_epoch - YEAR_ONE_EPOCH)
years_bc = seconds_bc/SECONDS_IN_YEAR
years_bc+=1 # for year 0
return BCDate.from_str(str(years_bc).zfill(getGlobalDigitSetting())+" BC")
years_bc = seconds_bc / SECONDS_IN_YEAR
years_bc += 1 # for year 0
return BCDate.from_str(str(years_bc).zfill(getGlobalDigitSetting()) + " BC")


def bcdate_to_epoch(fd):
""" convert a FlexiDate to seconds after (or possibly before) 1970-1-1 """
if _year(fd)>0:
res = (fd.as_datetime() - datetime(1970,1,1)).total_seconds()
if _year(fd) > 0:
res = (fd.as_datetime() - datetime(1970, 1, 1)).total_seconds()
else:
part1 = (datetime(1,1,1) - datetime(1970,1,1)).total_seconds()
part1 = (datetime(1, 1, 1) - datetime(1970, 1, 1)).total_seconds()
# coarsely get the epoch time for time BC, people didn't have a normal
# calendar back then anyway
part2 = - (abs(_year(fd)) -1) * SECONDS_IN_YEAR # -1 because year 0 doesn't exist
part2 = - (abs(_year(fd)) - 1) * SECONDS_IN_YEAR # -1 because year 0 doesn't exist
res = part1 + part2
return int(res)


YEAR_ONE_EPOCH = bcdate_to_epoch(BCDate(1))


def str_to_bcdate(datetimeString):
"""convert a date/time string into a FlexiDate object"""
return BCDate.from_str(datetimeString)


def epoch_to_str(seconds_from_epoch):
return datetime_to_str(epoch_to_datetime(seconds_from_epoch))

0 comments on commit 7fc8f0a

Please sign in to comment.