예제 #1
0
def predict_tides(station, dtg=None):
    """Predict the tide level at a station and date.
    :param station_id: The nearest stations id.
    :type station_id: String
    :param dtg: Date time group.
    :type dtg: String -- "Y-m-d-H-M"
    """

    action = 'Predicting tides for station %s and dtg %s' % (station, dtg)
    app.logger.debug('ACTOR:`%s` ACTION:`%s` DTG:`%s`', 'bf-tidepredicition',
                     action,
                     datetime.utcnow().isoformat() + 'Z')
    if dtg is None:
        dtg = datetime.now()
        dtg = datetime.strftime(dtg, '%Y-%m-%d-%H-%M')
        prediction_t0 = datetime.strptime(dtg, '%Y-%m-%d-%H-%M')
    else:
        prediction_t0 = datetime.strptime(dtg, '%Y-%m-%d-%H-%M')

    hours = 0.1 * np.arange(1 * 24 * 10)
    times = Tide._times(prediction_t0, hours)

    # Predict the tides using the Pytides model.
    try:
        model = TIDE_MODEL[station]
        my_prediction = model.at(times)
        ctide = float(my_prediction[0]) / 1000
        mint = float(min(my_prediction)) / 1000
        maxt = float(max(my_prediction)) / 1000
    except:
        ctide = 'null'
        mint = 'null'
        maxt = 'null'

    return mint, maxt, ctide, str(times[0])
예제 #2
0
def predict_tides(station, dtg=None):
    """Predict the tide level at a station and date.
    :param station_id: The nearest stations id.
    :type station_id: String
    :param dtg: Date time group.
    :type dtg: String -- "Y-m-d-H-M"
    """
    if dtg is None:
        dtg = datetime.now()
        dtg = datetime.strftime(dtg, '%Y-%m-%d-%H-%M')
        prediction_t0 = datetime.strptime(dtg, '%Y-%m-%d-%H-%M')
    else:
        prediction_t0 = datetime.strptime(dtg, '%Y-%m-%d-%H-%M')

    hours = 0.1 * np.arange(1 * 24 * 10)
    times = Tide._times(prediction_t0, hours)

    # Predict the tides using the Pytides model.
    try:
        model = TIDE_MODEL[station]
        my_prediction = model.at(times)
        ctide = float(my_prediction[0]) / 1000
        mint = float(min(my_prediction)) / 1000
        maxt = float(max(my_prediction)) / 1000
    except:
        ctide = 'null'
        mint = 'null'
        maxt = 'null'

    return mint, maxt, ctide, str(times[0])
예제 #3
0
def execute(args):
    times = pyTide._times(datetime.fromordinal(args.start_date.toordinal()), np.arange(args.length * 24., dtype=float))
    tide = Tide().reconstruct_tide(loc=[args.lat, args.lon], times=times, model=args.model, cons=args.cons,
        positive_ph=args.positive_phase)
    out = tide.data.to_csv(args.output, sep='\t', header=True, index=False)
    if args.output is None:
        print(out)
    print('\nComplete.\n')
예제 #4
0
def prediction(tide, tide_station_name, start_date=dt(2016, 10, 23)):
    """ Predicts the tide for a week from the given start date (in GMT) and 
        prints out a plot of the Pytide tide model vs NOAA tide model vs Actual
        Tide.
        
    Inputs:
        tide - Model for the predicted tides from pytides using NOAA's
            Harmonic Constituents
        tide_station_name - Name of the tide station for which we want the 
                    tidal model
        start_date - date that you want the first measurement from
                format: datetime(year,month,day,hour,minute)
    """
    if tide:
        ##Prepare a list of datetimes, each 6 minutes apart, for a week.
        prediction_t0 = start_date
        hours = 0.1 * np.arange(7 * 24 * 10)
        times = Tide._times(prediction_t0, hours)

        ##Prepare NOAA's results
        noaa_verified = []
        noaa_predicted = []

        with open('{}/actual.txt'.format(tide_station_name)) as f:
            for line in f:
                # temp stores the line we can store the first value as a float
                temp = line.split()
                noaa_verified.append(float(temp[0]))

        with open('{}/predict.txt'.format(tide_station_name)) as f1:
            for line in f1:
                # temp stores the line we can store the first value as a float
                temp = line.split()
                noaa_predicted.append(float(temp[0]))

        my_prediction = tide.at(times)
        fig, ax = plt.subplots(nrows=1, ncols=1)  # create figure & 1 axis
        plt.plot(hours, my_prediction, label="Pytides")
        plt.plot(hours, noaa_predicted, label="NOAA Prediction")
        plt.plot(hours, noaa_verified, label="NOAA Verified")
        plt.legend()
        plt.title('Comparison of Pytides and NOAA predictions for {}'.format(
            tide_station_name))
        plt.xlabel('Hours since {} (GMT)'.format(prediction_t0))
        plt.ylabel('Meters')
        plt.savefig('{}/{}_Tides_2016_Oct23.png'.format(
            tide_station_name, tide_station_name))
        return my_prediction, noaa_predicted, noaa_verified, hours

    else:
        print 'ERROR: Invalid Tide Station. Create a new file for {}.'.format(
            tide_station_name)
예제 #5
0
def execute(args):
    """Execute the reconstruct CLI command.

    Args:
        args (...): Variable length positional arguments
    """
    times = pyTide._times(datetime.fromordinal(args.start_date.toordinal()),
                          np.arange(args.length * 24., dtype=float))
    tide = Tide(model=args.model).reconstruct_tide(
        loc=[args.lat, args.lon],
        times=times,
        cons=args.cons,
        positive_ph=args.positive_phase)
    out = tide.data.to_csv(args.output, sep='\t', header=True, index=False)
    if args.output is None:
        print(out)
    print('\nComplete.\n')
예제 #6
0
def get_WaterLevelForecast(foredate, place):

    historyFileNm = "/megdata/data_meg-logic/real_data.txt"

    # カラム名のサンプル #######################
    # date,obsrPoint,waterLevel,precip,temp,odor
    #############################################

    df0 = pd.read_csv(historyFileNm, index_col=0, parse_dates=True)
    water_level = df0['waterLevel']
    demeaned = water_level.values - water_level.values.mean()

    tide = Tide.decompose(demeaned, water_level.index.to_datetime())

    constituent = [c.name for c in tide.model['constituent']]
    df = DataFrame(tide.model, index=constituent).drop('constituent', axis=1)
    df.sort_values('amplitude', ascending=False).head(10)
    # df.sort_values('phase', 0, ascending=False).head(20)

    # 今日の日付を取得
    today = datetime.datetime.today()
    # 翌日を取得
    # ※テスト用に5日後
    next_day = today + datetime.timedelta(days=5)

    dates = date_range(start=today.strftime('%Y-%m-%d'),
                       end=next_day.strftime('%Y-%m-%d'),
                       freq='10T')

    hours = np.cumsum(np.r_[
        0,
        [t.total_seconds() / 3600.0 for t in np.diff(dates.to_pydatetime())]])

    times = Tide._times(dates[0], hours)

    prediction = Series(tide.at(times) + water_level.values.mean(),
                        index=dates)

    return prediction
예제 #7
0
    def _compute(self):

        self.tidedata = {}
        self.predictiondata = {}
        self.last_time = np.max(self.epochlist)
        for name, const in self.constituent.items():
            t0 = self.time.tolist()[0]
            hours = self.prediction_interval * np.arange(self.days * 24 * 10)
            self.times = Tide._times(t0, hours)
            data = Tide.decompose(self.xmag, self.time.tolist(), None, None,
                                  self.constituent[name])
            try:

                self.tidedata[name] = data
                pred = self.tidedata[name].at(self.times)
                self.predictiondata[name] = pred * self.scale
            except:
                print "RECOMPUTE DEBUG\n Constutuent: {}".format(
                    self.constituent)
                print " Value of self.tidedata {}\n Value of self.time {}\n".format(
                    self.tidedata, self.time)
                return
        return self.predictiondata
예제 #8
0
        t.append(datetime_object)

for y in data.data:
    if (y != 'data'):
        heights.append(float(y))
#print heights
#print t

#For a quicker decomposition, we'll only use hourly readings rather than 6-minutely readings.
# heights = np.array(heights[::10])
# t = np.array(t[::10])

##Prepare a list of datetimes, each 6 minutes apart, for a week.
prediction_t0 = datetime(2016,10,4)
hours = np.arange(6 * 24)
times = Tide._times(prediction_t0, hours)
# print times

##Fit the tidal data to the harmonic model using Pytides
my_tide = Tide.decompose(heights, t)
##Predict the tides using the Pytides model.
my_prediction = my_tide.at(times)

##Prepare NOAA's results
noaa_verified = []
noaa_predicted = []

column = ['time', 'prediction', 'verified']
result = pd.read_csv('/Users/anonymous/clawpack_src/clawpack-v5.4.1rc-beta/geoclaw/examples/storm-surge/matthew/detide/data/FernandinaBeach_noaa.csv', header=None, names=column)
for x in result.prediction:
    if (x != 'prediction'):
예제 #9
0
ax.plot(t[:, 0], t[:, 1], linewidth=2)
ax.plot(de_tide[:, 0], de_tide[:, 1], linewidth=0.75, color="red")
set_monthsFmt(ax)
ylabel("Elevation, m")
# show()

# <markdowncell>

# ####Prepare a list of datetimes, each 6 minutes apart, for a the period of the dataset.

# <codecell>

total_hours = float((time_all[-1] - time_all[0]).total_seconds()) / (60.0 * 60.0)
nsamples = time_all.shape[0]
hours = linspace(0.0, float(total_hours), nsamples)
times = Tide._times(time_all[0], hours)
print times

# <codecell>

##Fit the tidal data to the harmonic model using Pytides
current_data = tide[2][:, 1].astype(float)
current_date = tide[2][:, 0]
print len(current_date), current_date
print len(current_data), current_data
my_tide = Tide.decompose(current_data, t=current_date)
print my_tide.model["amplitude"]
print my_tide.model["phase"]
for c in my_tide.model["constituent"]:
    print c.name
##Predict the tides using the Pytides model.