Esempio n. 1
0
    def test_multiple_attr_calls(self):
        x = 3
        y = 5
        self.assertEqual([
            spells.dict_of(x),
            spells.dict_of(y),
        ], [dict(x=x), dict(y=y)])

        with self.assertRaises(ValueError):
            print([spells.dict_of(x), spells.dict_of(y)])
Esempio n. 2
0
    def test_multiple_attr_calls(self):
        x = 3
        y = 5
        self.assertEqual([
            spells.dict_of(x),
            spells.dict_of(y),
        ], [dict(x=x), dict(y=y)])

        self.assertEqual(
            [spells.dict_of(x), spells.dict_of(y)],
            [dict(x=x), dict(y=y)])
Esempio n. 3
0
def fully_adapted_adaptive_sampling(y,prop_fun,obs_lik,N,):
    T = len(y)
    N_eff = np.zeros((T,))
    x = np.zeros((T, N)) * 0.0
    w_curl = np.zeros((T, N)) * 0.0
    w = np.zeros((T, N)) * 0.0
    a = np.zeros((T, N), dtype="int")
    w[0, ] = 1 / N
    w_curl[0, ] = 1 / N

    # Init x0
    x[0, ] = norm.rvs(size=N, loc=0, scale=1.0)
    for t in range(1, T):
        # Resample
        N_eff[t] = 1/np.sum(w[t-1]**2)
        if N_eff[t] < 50:
            a[t, ] = np.random.choice(np.arange(N), size=N, p=w[t - 1])
        else:
            a[t, ] = np.arange(0,100)

        # Propagate
        x[t, ] = prop_fun(x_prev=x[t - 1, a[t, ]], y_t=y[t,], N=N)

        # Weights
        # w_t  = p(y_i | x_i)
        w_curl[t, ] = obs_lik(y_t=y[t, ], x_prev=x[t-1, ], N=N)
        w[t, ] = w_curl[t, ] / w_curl[t, ].sum()

    loglik = (np.log(w_curl.sum(1)) - np.log(N)).sum()
    return dict_of(loglik, x, a, w, w_curl, N_eff)
Esempio n. 4
0
def bootstrap(
    y,
    prop_fun,
    obs_lik,
    N,
):
    T = len(y)
    x = np.zeros((T, N)) * 0.0
    w_curl = np.zeros((T, N)) * 0.0
    w = np.zeros((T, N)) * 0.0
    a = np.zeros((T, N), dtype="int")
    w[0, ] = 1 / N
    w_curl[0, ] = 1 / N

    # Init x0
    x[0, ] = norm.rvs(size=N, loc=0, scale=1.0)  # same as prior
    for t in range(1, T):
        # Resample
        a[t, ] = np.random.choice(np.arange(N), size=N, p=w[t - 1])

        # Propagate
        x[t, ] = prop_fun(x_prev=x[t - 1, a[t, ]])

        # Weights
        # w_t  = p(y_i | x_i)
        w_curl[t, ] = obs_lik(y_t=y[t, ], x=x[t, ])
        w[t, ] = w_curl[t, ] / w_curl[t, ].sum()

    loglik = (np.log(w_curl.sum(1)) - np.log(N)).sum()
    return dict_of(loglik, x, a, w, w_curl)
Esempio n. 5
0
def fully_adapted_systematic_sampling(y,prop_fun, obs_lik, N,):
    T = len(y)
    x = np.zeros((T, N)) * 0.0
    w_curl = np.zeros((T, N)) * 0.0
    w = np.zeros((T, N)) * 0.0
    a = np.zeros((T, N), dtype="int")
    w[0, ] = 1 / N
    w_curl[0, ] = 1 / N

    # Init x0
    x[0, ] = norm.rvs(size=N, loc=0, scale=1.0)
    for t in range(1, T):
        # Resample
        offset = np.random.rand()
        idx = np.sort( (np.linspace(0,0.99,100)+offset) %  1 )
        cum = w[t-1].cumsum()
        for i in range(99):
            a[t,i] = (idx[i] < cum).argmax()

        # Propagate
        x[t, ] = prop_fun(x_prev=x[t - 1, a[t, ]], y_t=y[t,], N=N)

        # Weights
        # w_t  = p(y_i | x_i)
        w_curl[t, ] = obs_lik(y_t=y[t, ], x_prev=x[t-1, ], N=N)
        w[t, ] = w_curl[t, ] / w_curl[t, ].sum()

    loglik = (np.log(w_curl.sum(1)) - np.log(N)).sum()
    return dict_of(loglik, x, a, w, w_curl)
Esempio n. 6
0
 def test_dict_of(self):
     a = 1
     obj = SimpleNamespace(b=2)
     self.assertEqual(spells.dict_of(
         a, obj.b,
         c=3, d=4
     ), dict(
         a=a, b=obj.b,
         c=3, d=4))
Esempio n. 7
0
def test_sorcery():
    from sorcery import dict_of

    def ret1():
        """ """
        return 1

    arg1 = ret1()
    columns = dict_of(arg1)
    assert columns["arg1"] == arg1
Esempio n. 8
0
def payout():
    rewards = db.select('rewards', ['account', 'sp'], '1=1', 'account', 9999)
    for reward in rewards:
        recipient = reward["account"]
        balance = float(cycler.hive.get_account(bot)['balance'][:-5])
        print('Current balance: ' + str(balance))
        amount = math.floor(reward['sp'] * 1000) / 1000
        print('Next: ' + str(amount) + ' for ' + reward['account'])
        if amount >= 0.001 and balance >= amount:
            try:
                cycler.hive.transfer(
                    reward['account'], amount, 'HIVE',
                    'Thank you for being a part of @curangel!', bot)
                print('Sending transfer of ' + str(amount) + ' HIVE to ' +
                      reward['account'])
            except:
                logger.warning(
                    f"missed payment of {amount} to {recipient}: transaction error"
                )
                notify("payout-tx-error", dict_of(amount, recipient))
            else:
                while float(cycler.hive.get_account(bot)['balance']
                            [:-5]) == balance:
                    print('Waiting for transfer...')
                    sleep(3)
                db.update('rewards', {'sp': reward['sp'] - amount},
                          {'account': reward['account']})
                db.insert('reward_payouts', {
                    'account': reward['account'],
                    'amount': amount
                })
        elif balance < amount:
            logger.error(
                f"missed payment of {amount} to {recipient}: low balance")
            notify("payout-low-balance", dict_of(amount, recipient))
        elif amount < 0.001:
            logger.info(
                f"skipped payment of {amount} to {recipient}: below precision threshold"
            )
Esempio n. 9
0
 def sendVote(self,uri,weight,id):
   last_vote_time = self._get_account()["last_vote_time"]
   try:
     self.client.commit.vote(uri, weight, self.account)
   except:
     time.sleep(3)
     self.sendVote(uri,weight,id)
   else:
     self.db.update('upvotes',{'status':'voted with '+str(weight)+'%','vote_time':datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')},{'id':id})
     while last_vote_time == self._get_account()["last_vote_time"]:
       # Block until the vote is reflected on the remote node.
       # This prevents double vote attempts.
       time.sleep(1)
     notify("upvote-execute", dict_of(
       uri,
       weight,
       id
     ))
Esempio n. 10
0
 def sorcery_return() -> None:
     """
     :rtype: None
     """
     return sorcery.dict_of(a, b, c)
Esempio n. 11
0
 def test_no_starargs_in_dict_of(self):
     args = [1, 2]
     with self.assertRaises(TypeError):
         spells.dict_of(*args)
Esempio n. 12
0
def package(*args):
    return AttrDict(dict_of(args))
Esempio n. 13
0
        self.ci.calc_fields(self.date)
        self.pr[:] = self.ci.pr[:]
        self.rf[:] = self.ci.rf[:]
        self.sf[:] = self.ci.sf[:]
        self.tas[:] = self.ci.tas[:]
        self.pet[:] = self.ci.pet[:]

# -----------------------------------------------------------------------------
# Set up and run model

# Make a dictionary of required variables
# - i.e. {'dt': dt, 'start_date': start_date, ...}
setup_dict = dict_of(
    # Timestep, simulation period, grid details, fixed input arrays
    dt, start_date, end_date, nx, ny, dx, mask, elev, flen, cell_order,
    # Parameters
    icf, lpf, fc, ttm, cfmax, cfr, whc, beta, perc, cflux, k, alpha, k1, tau,
    ssm, ssc, ssa, sshdm,
)

m = Model(**setup_dict)
m.run_model()

output_path = 'Z:/DP/Work/HBV/Tests/out_y1.csv'
m.df_cat.to_csv(output_path)

# =============================================================================
# Miscellaneous

# -----------------------------------------------------------------------------
# Examples of parameter bounds
Esempio n. 14
0
 def sorcery_return():
     """ """
     return sorcery.dict_of(a, b, c)