コード例 #1
0
 def __init__(self,path):
     """
     Initialize my fitness object object
     path: str, path to the directory which contains credentials file
     """
     credentials = pd.read_csv(os.path.join(path,'credentials.csv'))
     self._client_id = credentials['client_id'][0]
     self._client_secret = credentials['client_secret'][0]
     self._access_token = credentials['access_token'][0]
     self.misfit = Misfit(self._client_id, self._client_secret, self._access_token)
コード例 #2
0
class TestMisfitExceptions(unittest.TestCase):
    def setUp(self):
        self.misfit = Misfit('FAKE_ID', 'FAKE_SECRET', 'FAKE_TOKEN')

    def test_not_found(self):
        with HTTMock(not_found):
            self.assertRaises(MisfitNotFoundError, self.misfit.profile, '404')

    def test_invalid_parameters(self):
        with HTTMock(invalid_parameters):
            self.assertRaises(MisfitBadRequest, self.misfit.goal,
                              'BAD_START_DATE', 'BAD_END_DATE')

    def test_bad_gateway(self):
        with HTTMock(bad_gateway):
            self.assertRaises(MisfitBadGateway, self.misfit.profile)

    def test_unauthorized(self):
        with HTTMock(unauthorized):
            self.assertRaises(MisfitUnauthorized, self.misfit.profile)

    def test_forbidden(self):
        with HTTMock(forbidden):
            self.assertRaises(MisfitForbidden, self.misfit.profile)

    @freeze_time("2014-12-12 22:00:01")
    def test_rate_limit(self):
        with HTTMock(rate_limit):
            try:
                self.misfit.profile()
            except MisfitRateLimitError:
                headers = sys.exc_info()[1].response.headers
                self.assertEqual(headers['x-ratelimit-limit'], '150')
                self.assertEqual(headers['x-ratelimit-remaining'], '148')
                reset = arrow.get(headers['x-ratelimit-reset'])
                self.assertEqual((reset - arrow.now()).seconds, 2577)
            else:
                self.assertFail('Should have thrown MisfitRateLimitError')

    def test_unknown_error1(self):
        with HTTMock(unknown_error1):
            self.assertRaises(MisfitUnknownError, self.misfit.profile)

    def test_unknown_error2(self):
        with HTTMock(unknown_error2):
            self.assertRaises(MisfitUnknownError, self.misfit.profile)
コード例 #3
0
ファイル: plot_radiation.py プロジェクト: taotaokai/sem_utils
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Process misfit
"""
import sys
from misfit import Misfit
import numpy as np

# read command line args
#data_dir = "DATA" 
#cmt_file = "DATA/CMTSOLUTION.init"
#channel_file = "DATA/channel.txt"
misfit_file = "misfit/misfit.pkl"

#
print("\n====== initialize\n")
misfit = Misfit()

#print("\n====== setup event\n")
#misfit.setup_event(cmt_file, is_ECEF=True)
#
#print("\n====== setup station\n")
#misfit.setup_station(channel_file)

print("\n====== load data\n")
misfit.load(filename=misfit_file)

print("\n====== plot radiation pattern\n")
misfit.radiation_pattern()
コード例 #4
0
out_figure = str(sys.argv[4])

#------ load parameter file
if sys.version_info < (3, ):
  raise Exception("need python3")
elif sys.version_info < (3, 5):
  spec =importlib.machinery.SourceFileLoader("misfit_par", par_file)
  par = spec.load_module()
else:
  spec = importlib.util.spec_from_file_location("misfit_par", par_file)
  par = importlib.util.module_from_spec(spec)
  spec.loader.exec_module(par)

#------
print("\n====== initialize\n")
misfit = Misfit()

print("\n====== load data\n")
misfit.load(misfit_file)

print("\n====== grid_cc \n")
range_shrink_ratio = 0.618
dtau_range = 2
dt0_range = 5
xs_mt_step_range = 5

dtau_opt = 0.0
dt0_opt = 0.0
xs_mt_step_opt = 0.5

niter = 0
コード例 #5
0
par_file = str(sys.argv[1])
misfit_file = str(sys.argv[2])

# load parameter file
if sys.version_info < (3, ):
    raise Exception("need python3")
elif sys.version_info < (3, 5):
    spec = importlib.machinery.SourceFileLoader("misfit_par", par_file)
    par = spec.load_module()
else:
    spec = importlib.util.spec_from_file_location("misfit_par", par_file)
    par = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(par)

print("\n====== initialize\n")
misfit = Misfit()

print("\n====== load data\n")
misfit.load(misfit_file)

print("\n====== delete all misfit windows\n")
misfit.delete_window()

print("\n====== add P wave windows\n")
evdp_km = misfit.data['event']['depth']
print("evdp_km = %f" % (evdp_km))

window_list_P_wave = par.make_window_list_P_wave(evdp_km)
print(window_list_P_wave)

for win in window_list_P_wave:
コード例 #6
0
ファイル: plot_radiation.py プロジェクト: ziyixi/sem_utils
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Process misfit
"""
import sys
from misfit import Misfit
import numpy as np

# read command line args
#data_dir = "DATA"
#cmt_file = "DATA/CMTSOLUTION.init"
#channel_file = "DATA/channel.txt"
misfit_file = "misfit/misfit.pkl"

#
print("\n====== initialize\n")
misfit = Misfit()

#print("\n====== setup event\n")
#misfit.setup_event(cmt_file, is_ECEF=True)
#
#print("\n====== setup station\n")
#misfit.setup_station(channel_file)

print("\n====== load data\n")
misfit.load(filename=misfit_file)

print("\n====== plot radiation pattern\n")
misfit.radiation_pattern()
コード例 #7
0
ファイル: output_adj.py プロジェクト: taotaokai/sem_utils
import importlib
from misfit import Misfit

# read command line args
par_file = str(sys.argv[1])
misfit_file = str(sys.argv[2])
adj_dir = str(sys.argv[3])

# load parameter file
if sys.version_info < (3, ):
  raise Exception("need python3")
elif sys.version_info < (3, 5):
  spec =importlib.machinery.SourceFileLoader("misfit_par", par_file)
  par = spec.load_module()
else:
  spec = importlib.util.spec_from_file_location("misfit_par", par_file)
  par = importlib.util.module_from_spec(spec)
  spec.loader.exec_module(par)


print("\n====== initialize\n")
misfit = Misfit()

print("\n====== load data\n")
misfit.load(misfit_file)

print("\n====== output adjoint source\n")
misfit.output_adj(
    out_dir=adj_dir,
    syn_band_code=par.syn_band_code)
コード例 #8
0
"""Process misfit
"""
import sys
import importlib
from misfit import Misfit

# read command line args
par_file = str(sys.argv[1])
misfit_file = str(sys.argv[2])
adj_dir = str(sys.argv[3])

# load parameter file
if sys.version_info < (3, ):
    raise Exception("need python3")
elif sys.version_info < (3, 5):
    spec = importlib.machinery.SourceFileLoader("misfit_par", par_file)
    par = spec.load_module()
else:
    spec = importlib.util.spec_from_file_location("misfit_par", par_file)
    par = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(par)

print("\n====== initialize\n")
misfit = Misfit()

print("\n====== load data\n")
misfit.load(misfit_file)

print("\n====== output adjoint source\n")
misfit.output_adj(out_dir=adj_dir, syn_band_code=par.syn_band_code)
コード例 #9
0
class TestMisfitAPI(unittest.TestCase):
    def setUp(self):
        self.misfit = Misfit('FAKE_ID', 'FAKE_SECRET', 'FAKE_TOKEN')

    def test_goal(self):
        """ Test retrieving a goal by date range """
        goal_dict = {
            "id": "51a4189acf12e53f81000001",
            "date": "2014-10-05",
            "points": 500,
            "targetPoints": 1000,
            "timeZoneOffset": -8
        }
        end_date = '2014-10-07'
        with HTTMock(MisfitHttMock('goal').json_http):
            goal_list = self.misfit.goal(start_date=goal_dict['date'],
                                         end_date=end_date)
        eq_(len(goal_list), 3)
        goal = goal_list[0]
        eq_(type(goal), MisfitGoal)
        self.assert_misfit_string(goal, goal_dict)
        eq_(goal_list[2].date, arrow.get(end_date))
        eq_(goal.id, goal_dict['id'])
        eq_(goal.date, arrow.get(goal_dict['date']))
        eq_(goal.points, goal_dict['points'])
        eq_(goal.targetPoints, goal_dict['targetPoints'])
        eq_(goal.timeZoneOffset, goal_dict['timeZoneOffset'])
        self.assertAlmostEqual(goal.percent_complete(), 50)

        # Check that percent_complete is None if targetPoints is 0
        goal.targetPoints = 0
        assert goal.percent_complete() is None

    def test_goal_single(self):
        """ Test retrieving a goal by object_id """
        goal_dict = {
            "id": "51a4189acf12e53f81000001",
            "date": "2014-10-05",
            "points": 500,
            "targetPoints": 1000,
            "timeZoneOffset": -8
        }
        with HTTMock(MisfitHttMock('goal_single').json_http):
            goal = self.misfit.goal(object_id=goal_dict['id'])
        eq_(type(goal), MisfitGoal)
        self.assert_misfit_string(goal, goal_dict)
        eq_(goal.id, goal_dict['id'])
        eq_(goal.date, arrow.get(goal_dict['date']))
        eq_(goal.points, goal_dict['points'])
        eq_(goal.targetPoints, goal_dict['targetPoints'])
        eq_(goal.timeZoneOffset, goal_dict['timeZoneOffset'])
        self.assertAlmostEqual(goal.percent_complete(), 50)

        # Check that percent_complete is None if targetPoints is 0
        goal.targetPoints = 0
        assert goal.percent_complete() is None

    def test_goal_object_date_exception(self):
        """
        Check that an exception is raised when no date range or object id is
        supplied to goal
        """
        self.assertRaises(MisfitException, self.misfit.goal)

    def test_summary(self):
        """ Test retrieving a non-detail summary """
        date_range = {'start_date': '2014-12-10', 'end_date': '2014-12-17'}
        with HTTMock(MisfitHttMock('summary').json_http):
            summary = self.misfit.summary(start_date='2014-12-10',
                                          end_date='2014-12-17')

        summ_dict = {
            'activityCalories': 1449.2,
            'calories': 16310.24,
            'distance': 13.5227,
            'points': 3550,
            'steps': 34030
        }
        eq_(type(summary), MisfitSummary)
        self.assert_misfit_string(summary, summ_dict)
        eq_(summary.data, summ_dict)
        eq_(summary.activityCalories, summ_dict['activityCalories'])
        eq_(summary.calories, summ_dict['calories'])
        eq_(summary.distance, summ_dict['distance'])
        eq_(summary.points, summ_dict['points'])
        eq_(summary.steps, summ_dict['steps'])

    def test_summary_detail(self):
        summ_dict = {
            "date": "2014-10-05",
            "points": 394.4,
            "steps": 3650,
            "calories": 1687.4735,
            "activityCalories": 412.3124,
            "distance": 1.18
        }
        end_date = "2014-10-07"
        with HTTMock(MisfitHttMock('summary_detail').json_http):
            summary_list = self.misfit.summary(
                start_date=summ_dict['date'], end_date=end_date, detail=True)
        eq_(len(summary_list), 3)
        summary = summary_list[0]
        eq_(type(summary), MisfitSummary)
        self.assert_misfit_string(summary, summ_dict)
        eq_(summary_list[2].date, arrow.get(end_date))
        eq_(summary.data, summ_dict)
        eq_(summary.date, arrow.get(summ_dict['date']))
        eq_(summary.points, summ_dict['points'])
        eq_(summary.steps, summ_dict['steps'])
        eq_(summary.calories, summ_dict['calories'])
        eq_(summary.activityCalories, summ_dict['activityCalories'])
        eq_(summary.distance, summ_dict['distance'])

    def assert_misfit_string(self, obj, data):
        """
        The string representing the misfit object should be the classname,
        followed by a ":", followed by the json data
        """
        parts = ('%s' % obj).split(': ', 1)
        eq_(parts[0], '%s' % type(obj))
        eq_(json.loads(parts[1]), data)
コード例 #10
0
model_name = str(sys.argv[4])

# load parameter file
if sys.version_info < (3, ):
  raise Exception("need python3")
elif sys.version_info < (3, 5):
  spec =importlib.machinery.SourceFileLoader("misfit_par", par_file)
  par = spec.load_module()
else:
  spec = importlib.util.spec_from_file_location("misfit_par", par_file)
  par = importlib.util.module_from_spec(spec)
  spec.loader.exec_module(par)

#------
print("\n====== initialize\n")
misfit = Misfit()

print("\n====== load data\n")
misfit.load(misfit_file)

print("\n====== waveform_der_source\n")
misfit.waveform_der_source(
    syn_dir=syn_dir,
    syn_band_code=par.syn_band_code, 
    syn_suffix=par.syn_suffix,
    model_name=model_name,
    )
 
print("\n====== save data\n")
misfit.save(misfit_file)
コード例 #11
0
ファイル: measure_hdur.py プロジェクト: ziyixi/sem_utils
import numpy as np

# read command line args
data_dir = str(sys.argv[1])
obs_dir = str(sys.argv[2])
syn_dir = str(sys.argv[3])
freqmin = float(sys.argv[4])
freqmax = float(sys.argv[5])

#------ input files
CMTSOLUTION_file = '%s/CMTSOLUTION.obs' % (data_dir)
station_file = '%s/station.txt' % (data_dir)

#------
print "\ninitialize\n"
misfit = Misfit()

#------
print "\n====== setup event\n"
misfit.setup_event_from_CMTSOLUTION(CMTSOLUTION_file)
event_id = [ key for key in misfit.data['events'] ][0]

#------
print "\n====== setup stations\n"
misfit.setup_stations_from_metafile(station_file)

#------
print "\n====== setup windows\n"
window_list = [ 
        ('F','p,P',[-30,50]), 
        ('F','s,S',[-40,70]) ]
コード例 #12
0
syn_dir = str(sys.argv[5])
obs_dir = str(sys.argv[6])

# load parameter file
if sys.version_info < (3, ):
  raise Exception("need python3")
elif sys.version_info < (3, 5):
  spec =importlib.machinery.SourceFileLoader("misfit_par", par_file)
  par = spec.load_module()
else:
  spec = importlib.util.spec_from_file_location("misfit_par", par_file)
  par = importlib.util.module_from_spec(spec)
  spec.loader.exec_module(par)

print("\n====== initialize\n")
misfit = Misfit()

print("\n====== setup event\n")
misfit.setup_event(cmt_file, ECEF=par.cmt_is_ECEF, GPS_ELLPS=par.GPS_ELLPS)

print(misfit.data['event'])

print("\n====== setup station\n")
misfit.setup_station(channel_file, band_code=par.obs_band_code,three_channels=True, GPS_ELLPS=par.GPS_ELLPS)

print("\n====== read seismogram: obs, syn\n")
misfit.read_obs_syn(
  obs_dir=obs_dir,
  syn_dir=syn_dir, 
  syn_band_code=par.syn_band_code, 
  syn_suffix=par.syn_suffix,
コード例 #13
0
model_name = str(sys.argv[4])

# load parameter file
if sys.version_info < (3, ):
    raise Exception("need python3")
elif sys.version_info < (3, 5):
    spec = importlib.machinery.SourceFileLoader("misfit_par", par_file)
    par = spec.load_module()
else:
    spec = importlib.util.spec_from_file_location("misfit_par", par_file)
    par = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(par)

#------
print("\n====== initialize\n")
misfit = Misfit()

print("\n====== load data\n")
misfit.load(misfit_file)

print("\n====== waveform_der_source\n")
misfit.waveform_der_source(
    syn_dir=syn_dir,
    syn_band_code=par.syn_band_code,
    syn_suffix=par.syn_suffix,
    model_name=model_name,
)

print("\n====== save data\n")
misfit.save(misfit_file)
コード例 #14
0
ファイル: plot_misfit.py プロジェクト: taotaokai/sem_utils
figure_dir = str(sys.argv[3])

# load parameter file
if sys.version_info < (3, ):
  raise Exception("need python3")
elif sys.version_info < (3, 5):
  spec =importlib.machinery.SourceFileLoader("misfit_par", par_file)
  par = spec.load_module()
else:
  spec = importlib.util.spec_from_file_location("misfit_par", par_file)
  par = importlib.util.module_from_spec(spec)
  spec.loader.exec_module(par)

#------
print("\n====== initialize\n")
misfit = Misfit()

print("\n====== load data\n")
misfit.load(misfit_file)

print("\n====== plot seismograms\n")

evdp_km = misfit.data['event']['depth']
print("evdp_km = %f" % (evdp_km))

window_list_P_wave = par.make_window_list_P_wave(evdp_km)
print(window_list_P_wave)

for win in window_list_P_wave:
  window_id = "%s_%s" % (win['phase'], win['component'])
  print("\n------ %s\n" % (window_id))
コード例 #15
0
ファイル: measure_misfit.py プロジェクト: taotaokai/sem_utils
par_file = str(sys.argv[1])
misfit_file = str(sys.argv[2])

# load parameter file
if sys.version_info < (3, ):
  raise Exception("need python3")
elif sys.version_info < (3, 5):
  spec =importlib.machinery.SourceFileLoader("misfit_par", par_file)
  par = spec.load_module()
else:
  spec = importlib.util.spec_from_file_location("misfit_par", par_file)
  par = importlib.util.module_from_spec(spec)
  spec.loader.exec_module(par)

print("\n====== initialize\n")
misfit = Misfit()

print("\n====== load data\n")
misfit.load(misfit_file)

print("\n====== delete all misfit windows\n")
misfit.delete_window()

print("\n====== add P wave windows\n")
evdp_km = misfit.data['event']['depth']
print("evdp_km = %f" % (evdp_km))

window_list_P_wave = par.make_window_list_P_wave(evdp_km)
print(window_list_P_wave)

for win in window_list_P_wave:
コード例 #16
0
out_file = str(sys.argv[3])

#------ load parameter file
if sys.version_info < (3, ):
    raise Exception("need python3")
elif sys.version_info < (3, 5):
    spec = importlib.machinery.SourceFileLoader("misfit_par", par_file)
    par = spec.load_module()
else:
    spec = importlib.util.spec_from_file_location("misfit_par", par_file)
    par = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(par)

#------
print("\n====== initialize\n")
misfit = Misfit()

print("\n====== load data\n")
misfit.load(misfit_file)

print("\n====== grid_cc \n")
wcc_sum, weight_sum = \
    misfit.cc_linearized_seismogram_for_dmodel(
        dm=par.dm_model,
        plot=False)

with open(out_file, 'w') as f:
    f.write("#weight_sum = {:12.5e}\n".format(weight_sum))
    f.write("#step_size wcc_sum/weight_sum\n")
    for idx in range(len(wcc_sum)):
        f.write("{:12.5e}  {:15.8e}\n".format(par.dm_model['model'][idx],
コード例 #17
0
 def setUp(self):
     self.misfit = Misfit('FAKE_ID', 'FAKE_SECRET', 'FAKE_TOKEN')
コード例 #18
0
ファイル: plot_misfit.py プロジェクト: ziyixi/sem_utils
figure_dir = str(sys.argv[3])

# load parameter file
if sys.version_info < (3, ):
    raise Exception("need python3")
elif sys.version_info < (3, 5):
    spec = importlib.machinery.SourceFileLoader("misfit_par", par_file)
    par = spec.load_module()
else:
    spec = importlib.util.spec_from_file_location("misfit_par", par_file)
    par = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(par)

#------
print("\n====== initialize\n")
misfit = Misfit()

print("\n====== load data\n")
misfit.load(misfit_file)

print("\n====== plot seismograms\n")

evdp_km = misfit.data['event']['depth']
print("evdp_km = %f" % (evdp_km))

window_list_P_wave = par.make_window_list_P_wave(evdp_km)
print(window_list_P_wave)

for win in window_list_P_wave:
    window_id = "%s_%s" % (win['phase'], win['component'])
    print("\n------ %s\n" % (window_id))
コード例 #19
0
 def setUp(self):
     self.misfit = Misfit('FAKE_ID', 'FAKE_SECRET', 'FAKE_TOKEN')
コード例 #20
0
class MyFitness():
    """
    This class creates a misfit object which can be used by the user
    to access his/her profile, retrieve historical data on his/her goals,
    daity activity, performance and analysis.
    Later, the class will be extended to allow the user to look at his/her
    friends' data
    """
    def __init__(self,path):
        """
        Initialize my fitness object object
        path: str, path to the directory which contains credentials file
        """
        credentials = pd.read_csv(os.path.join(path,'credentials.csv'))
        self._client_id = credentials['client_id'][0]
        self._client_secret = credentials['client_secret'][0]
        self._access_token = credentials['access_token'][0]
        self.misfit = Misfit(self._client_id, self._client_secret, self._access_token)

    def getProfile(self):
        """
        This method returns data on the user's profile
        """
        print "Fetching user's profile ... ",
        profile = self.misfit.profile().data
        print "Done!"
        return profile

    def getGoals(self,start_date = '2015-10-1', end_date = time.strftime("%Y-%m-%d")):
        """
        This method return goals between
        start_date: str, starting date
        end_date: str, end date
        dates should be given in string  format as yyyy-mm-d or format("%Y-%m-%d") 
        """
        goals = self.misfit.goal(start_date,end_date)
        goals_dict = {'date':[],'targetPoints':[],'points':[]}

        print "Fetching user's goals ... "
        for i in range(0,len(goals)):
            goal = goals[i]
            goals_dict['date'].append(str(goal.date.date()))
            goals_dict['targetPoints'].append(goal.targetPoints)
            goals_dict['points'].append(goal.points)

        print len(goals), " goals found :-)"

        return pd.DataFrame(goals_dict)

    def deviceInfo(self):
        """Use this method to get information on the user's device"""
        deviceInfo = self.misfit.device().data
        return deviceInfo

    def activityDetails(self,start_date = '2015-10-1', end_date = time.strftime("%Y-%m-%d")):
        """
        Use this method to get information on the user's sessions
        """
        sessions = self.misfit.session(start_date, end_date)
        sessionDetails = {'activityType':[], 'distance':[],'steps':[], 'startTime':[],
                          'duration':[], 'calories':[],'points':[]}
        for i in range(0,len(sessions)):
            sdata = sessions[i].data
            sessionDetails['activityType'].append(sdata['activityType'])
            sessionDetails['distance'].append(sdata['distance'])
            sessionDetails['steps'].append(sdata['steps'])
            sessionDetails['startTime'].append(sdata['startTime'])
            sessionDetails['duration'].append(sdata['duration'])
            sessionDetails['calories'].append(sdata['calories'])
            sessionDetails['points'].append(sdata['points'])
        return pd.DataFrame(sessionDetails)

    def getSummary(self, start_date = '2015-10-01', end_date = time.strftime("%Y-%m-%d")):
        """Use this method to get summary of the user's activity"""
        summary = self.misfit.summary(start_date, end_date)
        return summary

    
    def analyzePerformance(self):
        pass
コード例 #21
0
ファイル: print_misfit.py プロジェクト: ziyixi/sem_utils
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Process misfit
"""
import sys
from misfit import Misfit
import json
import numpy as np

#------
# read command line args
misfit_file = str(sys.argv[1])

#------
#print "\ninitialize\n"
misfit = Misfit()

#------
#print "\nload data\n"
misfit.load(filename=misfit_file)

#------
#print "\nprint misfit\n"

events = misfit.data['events']
for event_id, event in events.iteritems():
    #    print "# %s" % event_id
    stations = event['stations']
    reloc = event['relocate']
    dm = reloc['dm']
    print "#RELOC %-16s dNorth %12.5e dEast %12.5e dDepth %12.5e dT %12.5e" % (
コード例 #22
0
class TestMisfitAPI(unittest.TestCase):
    def setUp(self):
        self.misfit = Misfit('FAKE_ID', 'FAKE_SECRET', 'FAKE_TOKEN')

    def test_goal(self):
        """ Test retrieving a goal by date range """
        goal_dict = {
            "id": "51a4189acf12e53f81000001",
            "date": "2014-10-05",
            "points": 500,
            "targetPoints": 1000,
            "timeZoneOffset": -8
        }
        end_date = '2014-10-07'
        with HTTMock(MisfitHttMock('goal').json_http):
            goal_list = self.misfit.goal(start_date=goal_dict['date'],
                                         end_date=end_date)
        eq_(len(goal_list), 3)
        goal = goal_list[0]
        eq_(type(goal), MisfitGoal)
        self.assert_misfit_string(goal, goal_dict)
        eq_(goal_list[2].date, arrow.get(end_date))
        eq_(goal.id, goal_dict['id'])
        eq_(goal.date, arrow.get(goal_dict['date']))
        eq_(goal.points, goal_dict['points'])
        eq_(goal.targetPoints, goal_dict['targetPoints'])
        eq_(goal.timeZoneOffset, goal_dict['timeZoneOffset'])
        self.assertAlmostEqual(goal.percent_complete(), 50)

        # Check that percent_complete is None if targetPoints is 0
        goal.targetPoints = 0
        assert goal.percent_complete() is None

    def test_goal_single(self):
        """ Test retrieving a goal by object_id """
        goal_dict = {
            "id": "51a4189acf12e53f81000001",
            "date": "2014-10-05",
            "points": 500,
            "targetPoints": 1000,
            "timeZoneOffset": -8
        }
        with HTTMock(MisfitHttMock('goal_single').json_http):
            goal = self.misfit.goal(object_id=goal_dict['id'])
        eq_(type(goal), MisfitGoal)
        self.assert_misfit_string(goal, goal_dict)
        eq_(goal.id, goal_dict['id'])
        eq_(goal.date, arrow.get(goal_dict['date']))
        eq_(goal.points, goal_dict['points'])
        eq_(goal.targetPoints, goal_dict['targetPoints'])
        eq_(goal.timeZoneOffset, goal_dict['timeZoneOffset'])
        self.assertAlmostEqual(goal.percent_complete(), 50)

        # Check that percent_complete is None if targetPoints is 0
        goal.targetPoints = 0
        assert goal.percent_complete() is None

    def test_goal_object_date_exception(self):
        """
        Check that an exception is raised when no date range or object id is
        supplied to goal
        """
        self.assertRaises(MisfitException, self.misfit.goal)

    def test_summary(self):
        """ Test retrieving a non-detail summary """
        date_range = {'start_date': '2014-12-10', 'end_date': '2014-12-17'}
        with HTTMock(MisfitHttMock('summary').json_http):
            summary = self.misfit.summary(start_date='2014-12-10',
                                          end_date='2014-12-17')

        summ_dict = {
            'activityCalories': 1449.2,
            'calories': 16310.24,
            'distance': 13.5227,
            'points': 3550,
            'steps': 34030
        }
        eq_(type(summary), MisfitSummary)
        self.assert_misfit_string(summary, summ_dict)
        eq_(summary.data, summ_dict)
        eq_(summary.activityCalories, summ_dict['activityCalories'])
        eq_(summary.calories, summ_dict['calories'])
        eq_(summary.distance, summ_dict['distance'])
        eq_(summary.points, summ_dict['points'])
        eq_(summary.steps, summ_dict['steps'])

    def test_summary_detail(self):
        summ_dict = {
            "date": "2014-10-05",
            "points": 394.4,
            "steps": 3650,
            "calories": 1687.4735,
            "activityCalories": 412.3124,
            "distance": 1.18
        }
        end_date = "2014-10-07"
        with HTTMock(MisfitHttMock('summary_detail').json_http):
            summary_list = self.misfit.summary(start_date=summ_dict['date'],
                                               end_date=end_date,
                                               detail=True)
        eq_(len(summary_list), 3)
        summary = summary_list[0]
        eq_(type(summary), MisfitSummary)
        self.assert_misfit_string(summary, summ_dict)
        eq_(summary_list[2].date, arrow.get(end_date))
        eq_(summary.data, summ_dict)
        eq_(summary.date, arrow.get(summ_dict['date']))
        eq_(summary.points, summ_dict['points'])
        eq_(summary.steps, summ_dict['steps'])
        eq_(summary.calories, summ_dict['calories'])
        eq_(summary.activityCalories, summ_dict['activityCalories'])
        eq_(summary.distance, summ_dict['distance'])

    def assert_misfit_string(self, obj, data):
        """
        The string representing the misfit object should be the classname,
        followed by a ":", followed by the json data
        """
        parts = ('%s' % obj).split(': ', 1)
        eq_(parts[0], '%s' % type(obj))
        eq_(json.loads(parts[1]), data)
コード例 #23
0
out_file = str(sys.argv[3])

#------ load parameter file
if sys.version_info < (3, ):
  raise Exception("need python3")
elif sys.version_info < (3, 5):
  spec =importlib.machinery.SourceFileLoader("misfit_par", par_file)
  par = spec.load_module()
else:
  spec = importlib.util.spec_from_file_location("misfit_par", par_file)
  par = importlib.util.module_from_spec(spec)
  spec.loader.exec_module(par)

#------
print("\n====== initialize\n")
misfit = Misfit()

print("\n====== load data\n")
misfit.load(misfit_file)

print("\n====== grid_cc \n")
wcc_sum, weight_sum = \
    misfit.cc_linearized_seismogram_for_dmodel(
        dm=par.dm_model,
        plot=False)

with open(out_file, 'w') as f:
  f.write("#weight_sum = {:12.5e}\n".format(weight_sum))
  f.write("#step_size wcc_sum/weight_sum\n")
  for idx in range(len(wcc_sum)):
    f.write("{:12.5e}  {:15.8e}\n".format(
コード例 #24
0
ファイル: print_misfit.py プロジェクト: taotaokai/sem_utils
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Process misfit
"""
import sys
from misfit import Misfit
import json
import numpy as np

#------
# read command line args
misfit_file = str(sys.argv[1])

#------
#print "\ninitialize\n"
misfit = Misfit()

#------
#print "\nload data\n"
misfit.load(filename=misfit_file)

#------
#print "\nprint misfit\n"

events = misfit.data['events']
for event_id, event in events.iteritems():
    #    print "# %s" % event_id
    stations = event['stations']
    reloc = event['relocate']
    dm = reloc['dm']
    print "#RELOC %-16s dNorth %12.5e dEast %12.5e dDepth %12.5e dT %12.5e" % (
コード例 #25
0
ファイル: output_misfit.py プロジェクト: ziyixi/sem_utils
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Process misfit
"""
import sys
from misfit import Misfit

# read command line args
misfit_file = str(sys.argv[1])
out_file = str(sys.argv[2])

print("\n====== initialize\n")
misfit = Misfit()

print("\n====== load data\n")
misfit.load(misfit_file)

print("\n====== output misfit measurments\n")
misfit.output_misfit(out_file)
コード例 #26
0
adj_dir = str(sys.argv[4])

# load parameter file
if sys.version_info < (3, ):
  raise Exception("need python3")
elif sys.version_info < (3, 5):
  spec =importlib.machinery.SourceFileLoader("misfit_par", par_file)
  par = spec.load_module()
else:
  spec = importlib.util.spec_from_file_location("misfit_par", par_file)
  par = importlib.util.module_from_spec(spec)
  spec.loader.exec_module(par)


print("\n====== initialize\n")
misfit = Misfit()

print("\n====== load data\n")
misfit.load(misfit_file)

print("\n====== read in perturbed waveform\n")
misfit.read_perturbed_waveform(
  syn_dir=syn_dir,
  syn_band_code=par.syn_band_code,
  )

print("\n====== output adjoint source\n")
misfit.output_adj_for_perturbed_waveform(
  out_dir=adj_dir,
  syn_band_code=par.syn_band_code,
  )