Exemple #1
0
def main(folder, solver, solver_name, dt):

    gb, domain = problem_data.create_grid(from_file=False, generate_network=True)

    data = {"domain": domain, "t_max": 5000}
    data["time_step"] = dt

    problem_data.add_data(gb, data, solver_name)

    solver(gb, folder)

    outflow_upper, outflow_lower = outlet_fluxes(gb)
    mean = mean_inlet_pressure(gb, solver_name)

    # to store the results for the current problem
    results = np.empty(8, dtype=np.object)

    # save basic informations
    results[0] = "UiB-" + solver_name.upper()
    results[1] = np.sum([g.num_cells for g in gb.grids_of_dimension(3)])
    results[2] = np.sum([g.num_cells for g in gb.grids_of_dimension(2)])
    results[3] = np.sum([g.num_cells for g in gb.grids_of_dimension(1)])
    results[4] = np.sum([g.num_cells for g in gb.grids_of_dimension(0)])
    results[5] = outflow_upper
    results[6] = outflow_lower
    results[7] = mean

    file_name = folder + "/info.txt"
    with open(file_name, "w") as f:
        f.write(", ".join(map(str, results)))

    T, outflow, A, b, block_dof, full_dof = solvers.transport(
        gb, data, solver_name, folder, callback=report_concentrations, save_every=1
    )
async def give_xp(ctx, p_id, amount):
    level = int(get_data(p_id, "level", default_val=0))
    current_xp = int(get_data(p_id, "xp", default_val=0))
    new_xp = current_xp + amount
    xp_required = XP_TO_LEVEL_UP + XP_INCREASE_PER_LEVEL * level
    while new_xp >= xp_required:
        new_xp -= xp_required
        level += 1
        xp_required = XP_TO_LEVEL_UP + XP_INCREASE_PER_LEVEL * level
        await show_level_up(ctx, level)

    add_data(p_id, "level", level)
    add_data(p_id, "xp", new_xp)
    def change_stock(self):
        add_data("shop", "last_stock_change", time())
        # Get all possible items
        shop_items = []
        for i in items.items:
            if i.can_be_in_shop():
                shop_items.append(i)

        # Pick a subset
        self.stock = random.sample(shop_items, min(SHOP_SIZE, len(shop_items)))
        self.stock = sorted(self.stock, key=lambda x: x.name)
        stock_names = [item.name for item in self.stock]
        add_data("shop", "items", stock_names)
Exemple #4
0
def main(mesh_size, discr, flow_dir, is_coarse, refine_1d, folder):

    # set the geometrical tolerance
    tol = 1e-6
    # create the gb
    gb, partition = create_grid(mesh_size, is_coarse, refine_1d, tol)
    # set the scheme for each grid
    for g, d in gb:
        d["discr"] = discr(g)
    # add the problem data
    add_data(gb, flow_dir, tol)
    # solve the darcy problem
    run_flow(gb, partition, folder)
Exemple #5
0
def main(file_geo, folder, data):

    mesh_args = {"mesh_size_frac": 10}
    tol = {"geo": 1e-4, "snap": 1e-3}
    data["tol"] = tol["geo"]

    gb, data["domain"] = grid.from_file(file_geo, mesh_args, tol)

    problem_data.add_data(gb, data)
    solvers.solve_rt0(gb, folder)

    advective = solvers.transport(gb, data, folder, problem_data.AdvectiveDataAssigner)
    np.savetxt(folder + "/outflow.csv", advective._solver.outflow)
Exemple #6
0
def main(test_case, file_geo, folder, solver, solver_name, N=None):

    tol = 1e-8
    if N is not None:
        gb, domain = problem_data.make_grid_cart(N)
    else:
        gb, domain = problem_data.import_grid(file_geo, tol)

    # select the permeability depending on the selected test case
    if test_case == 0:
        kf = 1e4
        porosity_f = 0.9
    else:
        kf = 1e-4
        porosity_f = 0.01
    data = {
        "domain": domain,
        "tol": tol,
        "aperture": 1e-4,
        "km_low": 1e-1,
        "km": 1,
        "kf": kf,
        "porosity_m": 1e-1,
        "porosity_f": porosity_f,
        "time_step": 0.25 / 100,
        "t_max": 0.25,
    }

    problem_data.add_data(gb, data, solver_name)
    solver(gb, folder)

    # to store the results for the current problem
    results = np.empty(5, dtype=np.object)

    # save basic informations
    results[0] = "UiB-" + solver_name.upper()
    results[1] = np.sum([g.num_cells for g in gb.grids_of_dimension(3)])
    results[2] = np.sum([g.num_cells for g in gb.grids_of_dimension(2)])
    results[3] = np.sum([g.num_cells for g in gb.grids_of_dimension(1)])
    results[4] = np.sum([g.num_cells for g in gb.grids_of_dimension(0)])

    file_name = folder + "/info.txt"
    with open(file_name, "w") as f:
        f.write(", ".join(map(str, results)))

    T, outflow, A, b, block_dof, full_dof = solvers.transport(gb,
                                                              data,
                                                              solver_name,
                                                              folder,
                                                              save_every=1)
    async def lab(self, ctx):

        labs_subset = get_labs_subset(LABS_OPTIONS)

        output = "Select a lab by typing what is in `this text`:"
        options = {}
        for lab in labs_subset:
            output += "\n\n- `{}` **{}** \n\t\t*{}*".format(
                lab["option"], lab["name"], lab["description"])
            options[lab["option"]] = lab

        def check(m):
            return m.author == ctx.author and (m.content in options)

        await ctx.send('',
                       embed=discord.Embed(description=output,
                                           colour=discord.Color.greyple()))

        msg = await self.bot.wait_for('message', check=check, timeout=120)
        lab = options[msg.content]
        outcome = random.choice(lab["outcomes"])
        output = "*{}*".format(outcome["description"])

        base_sc = SC_LAB
        multiplier = random.uniform(outcome["min_sc"], outcome["max_sc"])
        item_boost = items.get_player_boost(ctx.author.id, "labs")
        sc_add = round(base_sc * multiplier * (1 + item_boost))
        player_sc = get_data(ctx.author.id, "sc", default_val=0)
        add_data(ctx.author.id, "sc", player_sc + sc_add)

        output += "\n\nYour demonstrator gave you {} **{}**.".format(
            SC_EMOJI, sc_add)
        if item_boost:
            output += "\n_**{:.1f}%** boost from_ **Labs** _items in your inventory._".format(
                item_boost * 100)
        output += "\n\nYou get **`{}`<:xp:699934983074349086>**.".format(
            XP_LAB)
        lab_disp = discord.Embed(description=output,
                                 colour=discord.Color.greyple())
        lab_disp.set_author(name=lab["name"],
                            url='',
                            icon_url=ctx.author.avatar_url)
        await ctx.send('', embed=lab_disp)
        await give_xp(ctx, ctx.author.id, XP_LAB)

        await ctx.send(tips.get_random_tip())
Exemple #8
0
def dataloader(batch_size, num_batches, seq_len):
    """
    Generator of random sequences for the add task.
    """
    for batch_num in range(num_batches):
        inp, outp = add_data(seq_len, batch_size)
        inp = Variable(torch.from_numpy(inp))
        outp = Variable(torch.from_numpy(outp))
        yield batch_num + 1, inp.float().permute(1, 0, 2), outp.float()
Exemple #9
0
def main(file_geo, folder, solver, solver_name):

    tol = 1e-8
    gb, domain = problem_data.import_grid(file_geo, tol)

    # select the permeability depending on the selected test case
    data = {
        "domain": domain,
        "tol": tol,
        "aperture": 1e-2,
        "km_low": 1e-6,
        "km_high": 1e-5,
        "kf": 1e-1,
        "porosity_low": 0.2,
        "porosity_high": 0.25,
        "porosity_f": 0.4,
        "time_step": 1e7,
        "t_max": 1e9,
    }

    problem_data.add_data(gb, data, solver_name)
    solver(gb, folder)

    # to store the results for the current problem
    results = np.empty(5, dtype=np.object)

    # save basic informations
    results[0] = "UiB-" + solver_name.upper()
    results[1] = np.sum([g.num_cells for g in gb.grids_of_dimension(3)])
    results[2] = np.sum([g.num_cells for g in gb.grids_of_dimension(2)])
    results[3] = np.sum([g.num_cells for g in gb.grids_of_dimension(1)])
    results[4] = np.sum([g.num_cells for g in gb.grids_of_dimension(0)])

    file_name = folder + "/info.txt"
    with open(file_name, "w") as f:
        f.write(", ".join(map(str, results)))

    T, outflow, A, b, block_dof, full_dof = solvers.transport(gb,
                                                              data,
                                                              solver_name,
                                                              folder,
                                                              save_every=1)

    np.savetxt(folder + "/outflow.csv", outflow)
    async def buy_item(self, ctx, item, amt):
        if item is not None:
            if item.can_be_in_shop():
                if item in self.stock:
                    sc = get_data(ctx.author.id, "sc", default_val=0)
                    if sc >= item.cost * amt:
                        sale_disp = discord.Embed(colour=discord.Color.gold())
                        sale_disp.set_author(name='Successful purchase',
                                             url='',
                                             icon_url=ctx.author.avatar_url)
                        sale_disp.add_field(
                            name='\u200b',
                            value='You bought {} **{}**(s) and paid {}`{}`'.
                            format(amt, item.name, SC_EMOJI, item.cost * amt),
                            inline=False)
                        await ctx.send('', embed=sale_disp)

                        add_data(
                            ctx.author.id, "inv", item.name,
                            get_data(
                                ctx.author.id, "inv", item.name, default_val=0)
                            + amt)
                        add_data(ctx.author.id, "sc", sc - item.cost * amt)

                    else:
                        await ctx.send(
                            "You don't have enough money for this son, go do your work for {} **Standard Credits**."
                            .format(SC_EMOJI))
                else:
                    await ctx.send(
                        "Kid that's not in stock right now... and I say you shouldn't be wasting your money on random pidge-podge like this son."
                    )
            else:
                await ctx.send(
                    "Kid, the Dyson Centre store doesn't even sell this. Is that even legal?"
                )
        else:
            await ctx.send(
                "That item doesn't exist... have you been smoking the devil's lettuce again son?!"
            )
Exemple #11
0
def main(grid_file, folder, solver, solver_name, dt):

    gb, domain = problem_data.create_grid(grid_file)

    data = {"domain": domain, "t_max": 1}
    data["dt"] = dt

    problem_data.add_data(gb, data, solver_name)

    solver(gb, folder)

    outflow_upper, outflow_lower = outlet_fluxes(gb)
    mean = mean_inlet_pressure(gb, solver_name)

    # to store the results for the current problem
    results = np.empty(8, dtype=np.object)

    # save basic informations
    results[0] = "UiB-" + solver_name.upper()
    results[1] = np.sum([g.num_cells for g in gb.grids_of_dimension(3)])
    results[2] = np.sum([g.num_cells for g in gb.grids_of_dimension(2)])
    results[3] = np.sum([g.num_cells for g in gb.grids_of_dimension(1)])
    results[4] = np.sum([g.num_cells for g in gb.grids_of_dimension(0)])
    results[5] = outflow_upper
    results[6] = outflow_lower
    results[7] = mean

    file_name = folder + "/info.txt"
    with open(file_name, "w") as f:
        f.write(", ".join(map(str, results)))

    solvers.transport(
        gb,
        data,
        solver_name,
        folder,
        problem_data.AdvectiveDataAssigner,
        callback=report_concentrations,
    )
    async def lecture(self, ctx):
        tip = tips.get_random_tip()
        if tip:
            await ctx.send(tip)

        player_level = get_data(ctx.author.id, "level", default_val=0)
        lec = lecturers.get_by_level(player_level)

        message = "Your current lecture series is **{}** by **{}**.".format(
            lec.subject, lec.name)

        base_sc = SC_LECTURE + SC_LECTURE_INCREASE_PER_LEVEL * player_level
        boost = items.get_player_boost(ctx.author.id, lec.category)

        sc = ceil(base_sc * (1 + boost))
        player_sc = get_data(ctx.author.id, "sc", default_val=0)
        add_data(ctx.author.id, "sc", player_sc + sc)
        message += "\n\nYou went to the lecture and earned {} **{}**.".format(
            SC_EMOJI, sc)
        if boost > 0:
            message += "\n_**{:.1f}%** boost from_ **{}** _items in your inventory._".format(
                boost * 100, lec.category.title())
        else:
            message += "\n\n> _Get items that boost **{}** in order to increase earnings._".format(
                lec.category.title())

        message += "\n\nYou get **`{}`<:xp:699934983074349086>**.".format(
            XP_LECTURE)

        file = discord.File(DATA_PATH + "lecturer_img/" + lec.image,
                            filename=lec.image)
        lecture_disp = discord.Embed(description=message,
                                     colour=discord.Color.greyple())
        lecture_disp.set_thumbnail(url="attachment://" + lec.image)
        await ctx.send(file=file, embed=lecture_disp)

        if player_level == 2 and get_data(
                ctx.author.id, "inv", "Pills", default_val=0) > 0:
            # 'Tucker looks especially depressed today. After the lecture, you went to him and gave him an anti-depressant.'
            # '"What is this, bah humbug" said Tucker as he took the pill. But soon after it entered his mouth, something lit up in his eyes as he gazed longingly into the middle distance.'
            # '"Where has this been all my life", a tear rolled down Tucker's cheek as he turned to you. "Thank you, friend."'
            # '"I just had a revelation that I shouldn't be here, I'm gonna retire. You get a pass."'
            add_data(ctx.author.id, "xp", 0)
            add_data(ctx.author.id, "level", player_level + 1)
            pills = get_data(ctx.author.id, "inv", "Pills", default_val=0)
            add_data(ctx.author.id, "inv", "Pills", pills - 1)
            await show_level_up(ctx, player_level + 1)
            return
        await give_xp(ctx, ctx.author.id, XP_LECTURE)
    async def trivia(self, ctx):
        user_level = get_data(ctx.author.id, "level", default_val=0)

        # -- Picking question
        questions = get_trivia_questions()
        questions_todo = get_data(ctx.author.id,
                                  "questions_todo",
                                  default_val=[])

        if not questions_todo or max(questions_todo) >= len(questions):
            questions_todo = list(range(len(questions)))
            random.shuffle(questions_todo)
            add_data(ctx.author.id, "questions_todo", questions_todo)

        question_index = questions_todo[0]
        question = questions[question_index]

        # -- Getting answers
        if question.is_multiple_choice:
            answers = random.sample(question.answers, len(question.answers))
        else:
            answers = question.answers

        # -- Outputting question
        lec = lecturers.get_by_level(user_level)
        output = lecturers.get_by_level(
            user_level).get_trivia_message() + "\n\n"
        source = question.source
        if source:
            output += "> Source: *{}*\n{}\n".format(source,
                                                    question.question_text)
        else:
            output += "{}\n".format(question.question_text)

        if question.is_multiple_choice:
            for i in range(len(answers)):
                output += "\n*{}) {}*".format(ascii_lowercase[i], answers[i])

            output += "\n\n**Type in the character of the answer you think is correct!**"

            def check(m):
                return m.author == ctx.author and (
                    m.content in ascii_lowercase[:len(answers)]) and len(
                        m.content) == 1
        else:
            output += "\n**Type in `answer` followed by what you think the answer is!**"

            def check(m):
                return m.author == ctx.author and len(
                    m.content.split(maxsplit=1)) == 2 and (m.content.split(
                        maxsplit=1)[0].lower() == "answer")

        thumbnail_file = discord.File(DATA_PATH + "lecturer_img/" + lec.image,
                                      filename=lec.image)
        trivia_disp = discord.Embed(description=output,
                                    colour=discord.Color.greyple())
        trivia_disp.set_thumbnail(url="attachment://" + lec.image)
        trivia_disp.set_author(name="Supervision with {}".format(lec.name),
                               url='',
                               icon_url=ctx.author.avatar_url)

        image_name = question.image
        if image_name:
            image_file = discord.File(DATA_PATH + "trivia_img/" + image_name,
                                      filename=image_name)
            trivia_disp.set_image(url="attachment://" + image_name)
            await ctx.send(files=(thumbnail_file, image_file),
                           embed=trivia_disp)
        else:
            await ctx.send(file=thumbnail_file, embed=trivia_disp)

        try:
            msg = await self.bot.wait_for('message', check=check, timeout=1800)
        except asyncio.TimeoutError:
            await ctx.send("{}, your trivia question timed out.".format(
                ctx.author.mention))
        else:
            if question.is_multiple_choice:
                letter = msg.content
                pos = ascii_lowercase.index(letter, 0, len(answers))
                answer = answers[pos]
            else:
                answer = msg.content.split(maxsplit=1)[1]

            # Remove question_index from questions_todo
            questions_todo.remove(question_index)

            # -- Acting depending on if answer is correct or not
            if question.is_correct(answer):
                xp = XP_TRIVIA_CORRECT
                # Get boosts and give
                base_sc = question.sc_reward
                category_boost = items.get_player_boost(
                    ctx.author.id, question.category)
                supo_boost = items.get_player_boost(ctx.author.id,
                                                    "supervisions")
                boost = category_boost + supo_boost
                sc_add = ceil(base_sc * (1 + boost))
                player_sc = get_data(ctx.author.id, "sc", default_val=0)
                add_data(ctx.author.id, "sc", player_sc + sc_add)
                # Output message
                output = "{}, **Correct!**\n{}\nYou earned {} **{}**.".format(
                    ctx.author.mention, question.answer_message, SC_EMOJI,
                    sc_add)
                if boost > 0:
                    if category_boost and supo_boost:
                        boost_s = "{} and Supervisions".format(
                            question.category.title())
                    elif category_boost:
                        boost_s = "{}".format(question.category.title())
                    elif supo_boost:
                        boost_s = "Supervisions"
                    output += "\n_**{:.1f}%** boost from_ **{}** _items in your inventory._".format(
                        boost * 100, boost_s)
            else:
                xp = XP_TRIVIA_INCORRECT
                if question.is_multiple_choice:
                    correct_letter = ascii_lowercase[answers.index(
                        question.correct_answer)]
                    output = "{}, **Incorrect.**\n\nThe correct answer was **{}) {}**\n{}".format(
                        ctx.author.mention, correct_letter,
                        question.correct_answer, question.answer_message)
                else:
                    output = "{}, **Incorrect.**\n\nA correct answer was **{}**\n{}".format(
                        ctx.author.mention, question.answers[0],
                        question.answer_message)
                # Add the question back in so you do it again
                questions_todo.insert(4, question_index)

            add_data(ctx.author.id, "questions_todo", questions_todo)

            output += "\n\nYou get **`{}`<:xp:699934983074349086>**.".format(
                xp)

            file = discord.File(DATA_PATH + "lecturer_img/" + lec.image,
                                filename=lec.image)
            trivia_disp = discord.Embed(description=output,
                                        colour=discord.Color.greyple())
            trivia_disp.set_thumbnail(url="attachment://" + lec.image)
            trivia_disp.set_footer(
                text=
                "Got an issue with this question, or want to add your own? \nMessage @Chen or go to https://forms.gle/dnxpaXPVUxEqoNpk9"
            )
            await ctx.send(file=file, embed=trivia_disp)

            await give_xp(ctx, ctx.author.id, xp)
    async def give(self,
                   ctx,
                   member: discord.Member = None,
                   *,
                   in_string=None):

        inv = get_data(ctx.author.id, "inv", default_val={})

        if member == None:
            await ctx.send(
                "Kid, it goes like this:\n`dad give <@user> <amount> <item name>`"
            )

        elif member == ctx.author:
            await ctx.send(
                "Lmao when you try to give yourself a present because you have no friends..."
            )

        elif in_string.isdigit():  # Giving sc...
            amt = int(in_string)
            if get_data(ctx.author.id, "sc", default_val=0) < amt:
                await ctx.send(
                    "You don't have enough {} **Standard Credits** to give away!"
                    .format(SC_EMOJI))
            else:
                giver_after = get_data(ctx.author.id, "sc",
                                       default_val=0) - amt
                add_data(ctx.author.id, "sc", giver_after)
                reciever_after = get_data(member.id, "sc", default_val=0) + amt
                add_data(member.id, "sc", reciever_after)

                await ctx.send(
                    "You gave {} {} {}**Standard Credit(s)**, now you have {} and they've got {}."
                    .format(member.display_name, amt, SC_EMOJI, giver_after,
                            reciever_after))

        else:
            name, amt = get_name_and_amount(in_string)

            i = items.get_by_name(name)

            if i is not None:
                giver_before = inv.get(i.name, 0)
                if giver_before > 0:
                    if giver_before >= amt:
                        giver_after = get_data(
                            ctx.author.id, "inv", i.name, default_val=0) - amt
                        add_data(ctx.author.id, "inv", i.name, giver_after)
                        reciever_after = get_data(
                            member.id, "inv", i.name, default_val=0) + amt
                        add_data(member.id, "inv", i.name, reciever_after)
                        await ctx.send(
                            "You gave {} {} {}**{}**(s), now you have {} and they've got {}."
                            .format(member.display_name, amt, i.emoji, i.name,
                                    giver_after, reciever_after))

                    else:
                        await ctx.send(
                            "You don't have enough {}**{}**(s)!".format(
                                i.emoji, i.name))

                else:
                    await ctx.send("Son, you don't own this item!")

            else:
                await ctx.send("The heck... that item doesn't exist!")
def test():
    data = get_data()
    if data:
        add_data(data)
        print('hiya')
def job():
    rates = get_rates()
    if rates:
        add_data(rates)
        print("I'm working...")
def test():
    data = get_rates()
    if data:
        add_data(data)
        print('got data')