text:
# -*- coding: utf-8 -*-
"""
@author: Junxiao Song
"""

from __future__ import print_function
import numpy as np
import tkinter

class Board(object):
    """board for the game"""

    def __init__(self, **kwargs):
        self.width = int(kwargs.get('width', 8))
        self.height = int(kwargs.get('height', 8))
        # board states stored as a dict,
        # key: move as location on the board,
        # value: player as pieces type
        self.states = {}
        # need how many pieces in a row to win
        self.n_in_row = int(kwargs.get('n_in_row', 5))
        # self.players = [1, 2, 3]  # player1 and player2, add player3
        self.players = [0, 1, 2]

    def init_board(self, start_player=0):
        if self.width < self.n_in_row or self.height < self.n_in_row:
            raise Exception('board width and height can not be '
                            'less than {}'.format(self.n_in_row))
        self.current_player = self.players[start_player]  # start player
        # keep available moves in a list
        self.availables = list(range(self.width * self.height))
        self.states = {}
        self.last_last_move = -1
        self.last_move = -1

    def move_to_location(self, move):
        """
        3*3 board's moves like:
        6 7 8
        3 4 5
        0 1 2
        and move 5's location is (1,2)
        """
        h = move // self.width
        w = move % self.width
        return [h, w]

    def location_to_move(self, location):
        # from 2d loc(board) -> 1d loc(dic), check available
        if len(location) != 2:
            return -1
        h = location[0]
        w = location[1]
        move = h * self.width + w
        if move not in range(self.width * self.height):
            return -1
        return move

    def current_state(self):
        """return the board state from the perspective of the current player.
        2 players state shape: 4*width*height
        3 players state shape: 6*width*height
        """

        square_state = np.zeros((6, self.width, self.height))
        if self.states:
            moves, players = np.array(list(zip(*self.states.items())))
            move_curr = moves[players == self.current_player]
            move_oppo1 = moves[players == (self.current_player+1)%3]
            move_oppo2 = moves[players == (self.current_player+2)%3]
            square_state[0][move_curr // self.width,
                            move_curr % self.height] = 1.0
            square_state[1][move_oppo1 // self.width,
                            move_oppo1 % self.height] = 1.0
            square_state[2][move_oppo2 // self.width,
                            move_oppo2 % self.height] = 1.0
            # indicate the last move location
            square_state[3][self.last_move // self.width,
                            self.last_move % self.height] = 1.0
            square_state[4][self.last_last_move // self.width,
                            self.last_last_move % self.height] = 1.0
        if len(self.states) % 3 == 0:
            square_state[5][:, :] = 1.0  # indicate the colour to play
        return square_state[:, ::-1, :]

    def do_move(self, move):
        # maintain board and history
        self.states[move] = self.current_player
        self.availables.remove(move)
        # update player
        self.current_player = (
            (self.current_player+1) % 3
            # self.players[0] if self.current_player == self.players[1]
            # else self.players[1]
        )
        self.last_last_move = self.last_move
        self.last_move = move

    def has_a_winner(self):
        width = self.width
        height = self.height
        states = self.states
        n = self.n_in_row

        # extract moves history
        moved = list(set(range(width * height)) - set(self.availables))
        if len(moved) < self.n_in_row *2-1:
            return False, -1

        for m in moved:
            h = m // width
            w = m % width
            player = states[m]

            # check if n continue in four directions
            if (w in range(width - n + 1) and
                    len(set(states.get(i, -1) for i in range(m, m + n))) == 1):
                return True, player

            if (h in range(height - n + 1) and
                    len(set(states.get(i, -1) for i in range(m, m + n * width, width))) == 1):
                return True, player

            if (w in range(width - n + 1) and h in range(height - n + 1) and
                    len(set(states.get(i, -1) for i in range(m, m + n * (width + 1), width + 1))) == 1):
                return True, player

            if (w in range(n - 1, width) and h in range(height - n + 1) and
                    len(set(states.get(i, -1) for i in range(m, m + n * (width - 1), width - 1))) == 1):
                return True, player

        return False, -1

    def game_end(self):
        """Check whether the game is ended or not"""
        win, winner = self.has_a_winner()
        if win:
            return True, winner
        elif not len(self.availables):
            return True, -1
        return False, -1

    def get_current_player(self):
        return self.current_player

class Point:

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.pixel_x = 30 + 30 * self.x
        self.pixel_y = 30 + 30 * self.y

class Game(object):
    """game server"""

    def __init__(self, board, **kwargs):
        self.board = board

    def click1(self, event): #click1 because keyword repetition

        current_player = self.board.get_current_player()
        if current_player == 0:
            i = (event.x) // 30
            j = (event.y) // 30
            ri = (event.x) % 30
            rj = (event.y) % 30
            i = i-1 if ri<15 else i
            j = j-1 if rj<15 else j
            move = self.board.location_to_move((i, j))
            if move in self.board.availables:
                self.cv.create_oval(self.chess_board_points[i][j].pixel_x-10, self.chess_board_points[i][j].pixel_y-10, self.chess_board_points[i][j].pixel_x+10, self.chess_board_points[i][j].pixel_y+10, fill='black')
                self.board.do_move(move)

    def run(self):
        current_player = self.board.get_current_player()

        end, winner = self.board.game_end()

        if current_player != 0 and not end:
            player_in_turn = self.players[current_player]
            move = player_in_turn.get_action(self.board)
            self.board.do_move(move)
            i, j = self.board.move_to_location(move)
            if(current_player == 1):
                color='white'
            else:
                color='red'
            self.cv.create_oval(self.chess_board_points[i][j].pixel_x-10, self.chess_board_points[i][j].pixel_y-10, self.chess_board_points[i][j].pixel_x+10, self.chess_board_points[i][j].pixel_y+10, fill=color)

        end, winner = self.board.game_end()

        if end:
            if winner != -1:
                self.cv.create_text(self.board.width*15+15, self.board.height*30+30, text="Game over. Winner is {}".format(self.players[winner]))
                self.cv.unbind('<Button-1>')
            else:
                self.cv.create_text(self.board.width*15+15, self.board.height*30+30, text="Game end. Tie")

            return winner
        else:
            self.cv.after(100, self.run)

    def graphic(self, board, player1, player2, player3, draw=False):
        """Draw the board and show game info"""
        width = board.width
        height = board.height

        if draw:
            window = tkinter.Tk()
            self.cv = tkinter.Canvas(window, height=height*30+60, width=width*30 + 30, bg = 'white')
            self.chess_board_points = [[None for i in range(height)] for j in range(width)]

            for i in range(width):
                for j in range(height):
                    self.chess_board_points[i][j] = Point(i, j)
            for i in range(width):  #vertical line
                self.cv.create_line(self.chess_board_points[i][0].pixel_x, self.chess_board_points[i][0].pixel_y, self.chess_board_points[i][width-1].pixel_x, self.chess_board_points[i][width-1].pixel_y)

            for j in range(height):  #rizontal line
                self.cv.create_line(self.chess_board_points[0][j].pixel_x, self.chess_board_points[0][j].pixel_y, self.chess_board_points[height-1][j].pixel_x, self.chess_board_points[height-1][j].pixel_y)
            print("Player", player1, "with white".rjust(3))

            self.button = tkinter.Button(window, text="start game!", command=self.run)
            self.cv.bind('<Button-1>', self.click1)
            print("Player", player2, "with O".rjust(3))
            self.cv.pack()
            self.button.pack()
            print("Player", player3, "with 8".rjust(3))
            window.mainloop()
        else:
            print("Player", player1, "with X".rjust(3))
            print("Player", player2, "with O".rjust(3))
            print("Player", player3, "with 8".rjust(3))
            print()
            for x in range(width):
                print("{0:8}".format(x), end='')
            print('\r\n')
            for i in range(height - 1, -1, -1):
                print("{0:4d}".format(i), end='')
                for j in range(width):
                    loc = i * width + j
                    p = board.states.get(loc, -1)
                    if p == player1:
                        print('X'.center(8), end='')
                    elif p == player2:
                        print('O'.center(8), end='')
                    elif p == player3:
                        print('8'.center(8), end='')
                    else:
                        print('_'.center(8), end='')
                print('\r\n\r\n')

    def start_play(self, player1, player2, player3, start_player=0, is_shown=0, show_end=1, draw=False):
        """start a game between two players"""
        if start_player not in (0, 1, 2):
            raise Exception('start_player should be either 0 (player1 first) '
                            'or 1 (player2 first)')
        self.board.init_board(start_player)
        p1, p2, p3 = self.board.players
        player1.set_player_ind(p1)
        player2.set_player_ind(p2)
        player3.set_player_ind(p3)
        self.players = {p1: player1, p2: player2, p3: player3}
        if draw:
            self.graphic(self.board, player1.player, player2.player, player3.player, draw)
        else:
            if is_shown:
                self.graphic(self.board, player1.player, player2.player, player3.player)
            while True:
                current_player = self.board.get_current_player()
                player_in_turn = self.players[current_player]
                move = player_in_turn.get_action(self.board)
                self.board.do_move(move)
                if is_shown:
                    self.graphic(self.board, player1.player, player2.player, player3.player)
                end, winner = self.board.game_end()
                if end:
                    if show_end or is_shown:
                        self.graphic(self.board, player1.player, player2.player, player3.player)
                    print("Start player: ", start_player)
                    if winner != -1:
                        print("Game end. Winner is", self.players[winner])
                    else:
                        print("Game end. Tie")
                    return winner

    def start_self_play(self, player, is_shown=0, temp=1e-3):
        """ start a self-play game using a MCTS player, reuse the search tree,
        and store the self-play data: (state, mcts_probs, z) for training
        """
        self.board.init_board()
        p1, p2, p3 = self.board.players
        states, mcts_probs, current_players = [], [], []
        while True:
            move, move_probs = player.get_action(self.board,
                                                 temp=temp,
                                                 return_prob=1)
            # store the data
            states.append(self.board.current_state())
            mcts_probs.append(move_probs)
            current_players.append(self.board.current_player)
            # perform a move
            self.board.do_move(move)
            if is_shown:
                self.graphic(self.board, p1, p2, p3)
            end, winner = self.board.game_end()
            if end:
                # winner from the perspective of the current player of each state
                winners_z = np.zeros(len(current_players))
                if winner != -1:
                    winners_z[np.array(current_players) == winner] = 1.0
                    winners_z[np.array(current_players) != winner] = -1.0
                # reset MCTS root node
                player.reset_player()
                if is_shown:
                    if winner != -1:
                        print("Game end. Winner is player:", winner)
                    else:
                        print("Game end. Tie")
                return winner, zip(states, mcts_probs, winners_z)


text:
import os
import shutil
import zipfile

import numpy as np
from netCDF4 import Dataset

import src.config.filepaths as fp

def planck_radiance(wvl, temp):
    """

    :param wvl:
    :param temp:
    :return:
    """
    c1 = 1.19e-16  # W m-2 sr-1
    c2 = 1.44e-2  # mK
    wt = (wvl * 1.e-6) * temp  # m K
    d = (wvl * 1.e-6) ** 5 * (np.exp(c2 / wt) - 1)
    return c1 / d * 1.e-6  # W m-2 sr-1 um-1

def extract_zip(input_zip, path_to_temp):
    data_dict = {}
    to_extract = ["S5_radiance_an.nc", "S6_radiance_an.nc",
                  "geodetic_an.nc", "geometry_tn.nc",
                  "cartesian_an.nc", "cartesian_tx.nc",
                  "indices_an.nc", "flags_an.nc", "time_an.nc"]
    with zipfile.ZipFile(input_zip) as nc_file:
        for name in nc_file.namelist():
            split_name = name.split('/')[-1]
            if split_name in to_extract:
                var_name = split_name.split('.')[0]
                source = Dataset(nc_file.extract(name, path_to_temp))
                data_dict[var_name] = source

    # remove the unzip files
    dir_to_remove = os.path.join(path_to_temp, input_zip.split('/')[-1].replace('zip', 'SEN3'))
    if os.path.isdir(dir_to_remove):  # test if the path points to a directory
        shutil.rmtree(dir_to_remove, ignore_errors=True)
    else:  # normal file
        os.remove(dir_to_remove)

    return data_dict

def build_outpath(sensor, f, stage):

    # separate file from path
    fname = f.split('/')[-1]
    ymd = fname[16:24] if sensor == 'sls' else fname[14:22]
    fname = fname.split('.')[0] + ''.join(['_', stage, '.csv'])
    return os.path.join(fp.output_l2, sensor, ymd[0:4], ymd[4:6], ymd[6:8], fname)

ext: py

max_issues_repo_name: dabillox/kcl-globalgasflaring

reason: import numpy


text:
# Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import numpy as np
import phyre.creator as creator_lib

hole_size = 0.2
bar_scale = (1. - hole_size) / 2
top_bar_scale = 0.6
max_balls = 4

@creator_lib.define_task_template(
    step_diff=np.linspace(-0.3, 0.3, 10),
    step_base=np.linspace(0.01, 0.1, 2),
    jar_scale=np.linspace(0.15, 0.3, 3),
    jar_right=np.linspace(0.9, 0.98, 3),
    jar_angle=np.linspace(-10, 10, 13),
    left_side = np.linspace(0.05, 0.2, 5),
    search_params=dict(
        max_search_tasks=1000,
        required_flags=['BALL:GOOD_STABLE'],
        excluded_flags=['BALL:TRIVIAL'],
        diversify_tier='ball'
    ),
    max_tasks=100,
    version='3',
)
def build_task(C, step_diff, step_base, jar_scale, jar_right, jar_angle, left_side):
    if step_diff > 0:
        left_step_height_scale = step_base
        right_step_height_scale = left_step_height_scale + step_diff
    else:
        right_step_height_scale = step_base
        left_step_height_scale = right_step_height_scale - step_diff

    if jar_scale < 0.19:
        if abs(step_diff) > 0.19:
            raise creator_lib.SkipTemplateParams
    if jar_scale > 0.26:
        if abs(step_diff) < 0.19:
            raise creator_lib.SkipTemplateParams
        if step_diff < -0.19:
            raise creator_lib.SkipTemplateParams

    left_step = C.add(
        'static bar',
        scale=0.3,
        bottom=left_step_height_scale * C.scene.height,
        left=left_side * C.scene.width)
    pivot_ball = C.add(
        'dynamic ball', scale=0.15, bottom=left_step.top, left=left_step.left)

    bar = C.add('dynamic bar', scale=0.4, bottom=pivot_ball.top, left=5)
    ball = C.add(
        'dynamic ball', scale=0.05, bottom=bar.top, left=0.02 * C.scene.width)

    # Add popular solution blocker
    C.add('static ball', scale=0.1, top=C.scene.height, center_x=pivot_ball.center_x)
    right_step = C.add(
        'static bar',
        scale=0.3,
        angle=jar_angle,
        bottom=right_step_height_scale * C.scene.height,
        right=C.scene.width)
    jar = C.add(
        'dynamic jar',
        scale=jar_scale,
        bottom=right_step.top,
        right=C.scene.width * jar_right)
    ball_in_jar = C.add(
        'dynamic ball',
        scale=0.05 + jar_scale / 8,
        center_x=jar.center_x,
        bottom=jar.bottom + 10)

    C.update_task(
        body1=ball,
        body2=ball_in_jar,
        relationships=[C.SpatialRelationship.TOUCHING])
    C.set_meta(C.SolutionTier.BALL)


text:
# Copyright 2021 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
# etl.py
#
# Spark-based ETL from Kafka to PostgreSQL.
#
# Accepts arguments on the command line to specify how to talk to Spark, Kafka,
# and Postgres.
#
# Run `python etl.py --help` for a list of available arguments.

########################################
# IMPORTS
import argparse
import functools
import io
import operator
import os
import time
import sys

import numpy as np
import pandas as pd
import psycopg2

import etl_lib

# The convention with PySpark is to import individual classes, Java-style
from pyspark import SparkConf
from pyspark import SparkContext
from pyspark.sql import SparkSession
from pyspark.sql.functions import pandas_udf, PandasUDFType
try:
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse
import pyspark
import confluent_kafka as kafka

########################################
# CONSTANTS

# Number of batches to divide our data into when loading into PostgreSQL.
# Since there's only one server, making this too high is not a good idea.
_NUM_BATCHES = 4

########################################
# ARGUMENTS

parser = argparse.ArgumentParser(description="ETL from Kafka to Spark to Postgres")
parser.add_argument("--spark_master", type=str, default="local[*]",
                    help="Connection string for Spark (default: local[*])")
parser.add_argument("--kafka_bootstrap_servers", type=str, default="localhost:9092",
                    help="Connection string for Kafka (default: localhost:9092)")
parser.add_argument("--kafka_topic", type=str, default="reefer",
                    help="Name of Kafka topic to monitor (default: reefer)")
parser.add_argument("--batch_temp_loc", type=str, default="batch.csv",
                    help="URL/path at which to write the current batch of records "
                         "(default: batch.csv)")
parser.add_argument("--postgres_host", type=str, default=None,
                    help="Address of PostgreSQL server (default: None)")
parser.add_argument("--postgres_port", type=int, default=None,
                    help="Port that Postgres server is listening on (default: None)")
parser.add_argument("--postgres_db", type=str, default="demo",
                    help="Name of PostgreSQL database to load (default: demo)")
parser.add_argument("--postgres_user", type=str, default=None,
                    help="User name to use when connecting to Postgres server "
                         "(default: None)")
parser.add_argument("--postgres_password", type=str, default=None,
                    help="Password to use when connecting to Postgres server "
                         "(default: None)")
parser.add_argument("--table_name", type=str, default="reefer_telemetries",
                    help="Name of target database table for load operation"
                         "(default: reefer_telemetries)")

# Append Postgres Credentials to argument dictionary
def append_postgres_creds(args_as_dict):
    postgresURL=urlparse(os.getenv('POSTGRES_URL').replace("'",""))
    args_as_dict['postgres_host'] = postgresURL.hostname
    args_as_dict['postgres_port'] = int(postgresURL.port)
    args_as_dict['postgres_db'] = postgresURL.path.replace('/', '')
    args_as_dict['postgres_user'] = postgresURL.username
    args_as_dict['postgres_password'] = postgresURL.password
    return args_as_dict

########################################
# SUBROUTINES

from subprocess import check_output
ip = check_output(['hostname', '-i']).decode().rstrip()

########################################
# MAIN

def main():
    args = parser.parse_args()
    args_as_dict = { k: getattr(args, k) for k in args.__dict__.keys() }

    args_as_dict = append_postgres_creds(args_as_dict)

    print("Connecting to Spark.")

    # Fire up PySpark.
    spark = SparkSession.builder \
        .master(args.spark_master) \
        .appName("ReeferETL") \
        .config("spark.driver.host", ip) \
        .config("spark.sql.execution.arrow.enabled", "true") \
        .getOrCreate()

    print("Connected to Spark. Connection object is: {}".format(spark))

    # Drop Postgres/Kafka connection parameters into a broadcast variable so
    # that our UDFs can pick them up.
    params_broadcast = spark.sparkContext.broadcast(args_as_dict)

    # Tell PySpark how to find the module with all our shared application
    # code.
    spark.sparkContext.addPyFile(etl_lib.__file__)

    # Define our UDFs. This must happen AFTER starting Spark.
    fetch_udf = pandas_udf(etl_lib.fetch_udf,
                       "partition_id long, offset long, value string",
                       PandasUDFType.GROUPED_MAP)
    @pandas_udf("partition_id long, offset long", PandasUDFType.GROUPED_MAP)
    def load_udf(records):
        return etl_lib.load_udf(records, params_broadcast.value)

    print("Connecting to Kafka cluster.");

    # Generate a dataframe for job control.
    partition_ids = etl_lib.get_partition_ids(args.kafka_bootstrap_servers,
                                            args.kafka_topic)
    params_df = spark.createDataFrame(
        [(p, args.kafka_bootstrap_servers, args.kafka_topic)
         for p in partition_ids],
        ["partition_id", "bootstrap_servers", "topic_name"])
    params_df.show()

    print("Fetching messages from Kafka.");
    # Fetch all available messages from all partitions in parallel and write
    # the resulting messages to a temp directory on the distributed filesystem.
    # Use CSV format for ease of debugging.
    raw_batch_df = (
        params_df
        # Work around Spark's tendancy to use spark.sql.shuffle.partitions blindly
        .repartition(len(partition_ids), "partition_id")
        .groupby("partition_id")
        .apply(fetch_udf)
    )
    #raw_batch_df.write.csv(path=args.batch_temp_loc, mode="overwrite",
    #                       header=True)
    # Wrap the temp file in a dataframe for all subsequent processing.
    #batch_df = spark.read.csv(args.batch_temp_loc, header=True,
    #                          schema=raw_batch_df.schema)
    raw_batch_df.toPandas().to_csv(args.batch_temp_loc, index=False)
    data = pd.read_csv(args.batch_temp_loc)
    batch_df = spark.createDataFrame(data, schema=raw_batch_df.schema)

    print("DataFrame for batch is {} with count = {}"
          "".format(batch_df, batch_df.count()))

    print("Loading records into database.");
    load_results = (
    batch_df
        # Work around Spark's tendancy to use spark.sql.shuffle.partitions blindly
        .withColumn("partition_id", batch_df.offset % _NUM_BATCHES)
        .repartition(_NUM_BATCHES, "partition_id")
        .groupby("partition_id")
        .apply(load_udf)
        .toPandas()
    )
    print("Records loaded by Kafka offset:\n{}".format(load_results))

    print("Committing offsets to Kafka.");
    offsets_df = batch_df.groupby("partition_id").agg({"offset": "max"})
    offsets_df = offsets_df.select(offsets_df["partition_id"],
                                   (offsets_df["max(offset)"] + 1).alias("to_commit"))
    offsets_pd = offsets_df.toPandas()
    print("Offsets to commit:\n{}".format(offsets_pd))

    etl_lib.commit_offsets(list(offsets_pd.to_records(index=False)),
                           args.kafka_bootstrap_servers,
                           args.kafka_topic)
    print("Done.")

if __name__ == "__main__":
    main()

max_stars_repo_name: mlx-bot/katalog

max_issues_repo_name: mlx-bot/katalog

max_forks_repo_name: mlx-bot/katalog


text:
import numpy as np

from forge.blade.action import action
from forge.blade.systems import skill, droptable

class Entity():
   def __init__(self, pos):
      self.pos = pos
      self.alive = True
      self.skills = skill.Skills()
      self.entityIndex=0
      self.health = -1
      self.lastAttacker = None

   def act(self, world):
      pass

   def decide(self, stimuli):
      pass

   def death(self):
      pass

   def registerHit(self, attacker, dmg):
      self.lastAttacker = attacker
      self.health -= dmg

   def remove(self, ent):
      r, c = self.pos
      ent[r, c] = 0

   def isAlive(self):
      return self.health > 0

   @property
   def isPC(self):
      return False

max_stars_repo_name: wwxFromTju/neural-mmo

max_issues_repo_name: wwxFromTju/neural-mmo


text:
"""Accessor to `pandas.Series` for historical series of financial prices.
"""

import numpy as np
import pandas as pd

@pd.api.extensions.register_series_accessor('prices')
class PricesSeriesAccessor:
    """Accessor for historical series of financial prices.

    Examples:
    >>> s.prices.set_frequency()
    >>> s.prices.rebase()
    >>> s.prices.log_returns()
    >>> s.prices.pct_returns()
    >>> s.prices.abs_return()
    >>> s.prices.annualized_return()
    >>> s.prices.cagr()
    >>> s.prices.drawdown()
    >>> s.prices.max_drawdown()
    """

    def __init__(self, series: pd.Series) -> None:
        self._validate(series)
        self._series = series.sort_index()

    @staticmethod
    def _validate(series: pd.Series) -> None:
        # Validates the price series.
        if series.index.inferred_type != 'datetime64':
            raise TypeError('The series index must be a DateTimeIndex.')
        if not series.index.is_unique:
            raise ValueError('The series index cannot have duplicates.')
        if not (series > 0).all():
            raise ValueError('The series cannot have negative prices.')

    def set_frequency(self, freq: str = 'B', method: str = 'pad') -> pd.Series:
        """Modifies / sets the frequency of the series.

        Args:
            freq: The frequency of the new series. Typical values could be 'B' (Business Day), 'BW' (alias for 'W-FRI', Business Week), 'BM' (Business Month), 'BQ' (Business Quarter), 'BY' (Business Year), Defaults to 'B' (Business Day).
            method: Method fo filling the holes in the reindexed series. Can assume values `None` (fills with NaN), 'pad'/'ffill' (fills with previous value), 'backfill'/'bfill' (fills with next value). Defaults to 'pad'.

        Returns:
            pd.Series: A series with a modified frequency.
        """
        if freq == 'BW':
            freq = 'W-FRI'
        return self._series.asfreq(freq, method)

    def rebase(self, base: int = 100) -> pd.Series:
        """Rebases the series.

        Args:
            base: The base for the new series. Defaults to 100.

        Returns:
            pd.Series: The rebased series.
        """
        return self._series.divide(self._series.iloc[0]).multiply(base)

    def log_returns(self, period: int = 1, dropna: bool = False) -> pd.Series:
        """Calculates logarithmic returns.

        Args:
            period: The calculation period. Defaults to 1.
            dropna: If True, NAs are dropped. Defaults to False.

        Returns:
            pd.Series: The series of returns.
        """
        if dropna:
            return self._series.apply(np.log).diff(period).dropna()
        else:
            return self._series.apply(np.log).diff(period)

    def pct_returns(self, period: int = 1, dropna: bool = False) -> pd.Series:
        """Calculates percentage returns.

        Args:
            period: The calculation period. Defaults to 1.
            dropna: If True, NAs are dropped. Defaults to False.

        Returns:
            pd.Series: The series of returns.
        """
        if dropna:
            return self._series.pct_change(period).dropna()
        else:
            return self._series.pct_change(period)

    def abs_return(self) -> float:
        """Calculates the absolute return over the series.

        Returns:
            float: The absolute return over the series.
        """
        return self._series.iat[-1] / self._series.iat[0] - 1

    def annualized_return(self, base: int = 365) -> float:
        """Calculates an annualized return over the series.

        Args:
            base: Number of periods in a year. Defaults to 365.

        Returns:
            float: The annualized return over the series.
        """
        return self.abs_return() * base /\
            (self._series.index[-1] - self._series.index[0]).days

    def cagr(self, base: int = 365) -> float:
        """Calculates a compounded annual growth rate (CAGR).

        Args:
            base: Number of periods in a year. Defaults to 365.

        Returns:
            float: The compounded annual growth rate.
        """
        return (1 + self.abs_return()) ** (base / (self._series.index[-1] -\
            self._series.index[0]).days) - 1

    def drawdown(self, negative: bool = False) -> pd.Series:
        """Calculates the drawdown of the series.

        Args:
            negative: If True, returns a negative series. Defaults to False.

        Returns:
            pd.Series: The drawdown series.
        """
        if negative:
            return self._series.cummax().sub(self._series).\
                div(self._series.cummax()).mul(-1)
        else:
            return self._series.cummax().sub(self._series).\
                div(self._series.cummax())

    def max_drawdown(self, negative=False) -> float:
        """Calculates the max drawdown.

        Args:
            negative: If True, uses a negative series. Defaults to False.

        Returns:
            float: The max drawdown.
        """
        if negative:
            return self.drawdown(negative=True).min()
        else:
            return self.drawdown().max()

max_stars_repo_name: mbonix/fintopy

max_issues_repo_name: mbonix/fintopy

max_forks_repo_name: mbonix/fintopy


text:
"""
script generating an interactive plot with both classical Micahelis-Menten kinetics and  plot with Linweaver-Burk
kinetics on a side-by-side, interactive visualization
"""
# import libraries
import numpy as np

from bokeh.layouts import row, column
from bokeh.models import CustomJS, Slider, Label, Span
from bokeh.plotting import figure, output_file, show, ColumnDataSource

from pharmaplot import mm
from pharmaplot.config import html_output_dir

# -------------------------------------------------
# create baseline michaelis-menten plot
# -------------------------------------------------
# set plot parameters
pw = 500
ph = 400

# set data values
log_start = -2
log_end = 3
vmax = 10
km = 1

# -------------------------------------------------
# create baseline michaelis-menten plot
# -------------------------------------------------
# set up starting values
x_line = np.logspace(log_start, log_end, num=100)
y_line = mm.michaelis_menten(x_line, vmax, km)

x_points = np.logspace(log_start, log_end, num=20)
y_points = mm.michaelis_menten(x_points, vmax, km)

# set up source data and plot lines that will vary
mm_line_source = ColumnDataSource(data=dict(x=x_line, y=y_line))
mm_point_source = ColumnDataSource(data=dict(x=x_points, y=y_points))

mm_plot = figure(y_range=(-0.5, 20), x_range=(-0.5, 10), plot_width=pw, plot_height=ph,
                 x_axis_label='[S]: substrate concentration (μM)',
                 y_axis_label='initial velocity (μM/s)',
                 title='Michaelis-Menten Kinetics')

mm_plot.line('x', 'y', source=mm_line_source, line_width=3, line_alpha=0.6, color='black')
mm_plot.circle('x', 'y', source=mm_point_source, size=10, color='black')

# set up static line and annotations
mm_plot.line(x_line, y_line, line_width=5, color='blue', line_alpha=0.3)
mm_plot.circle(x_points, y_points, size=10, color='blue', line_alpha=0.3)

mytext = Label(x=3.8, y=10, text='Km = 1 (μM), Vmax = 10 (μM/s)',
               text_color="blue", text_alpha=0.5)
mm_plot.add_layout(mytext)

# add axes lines
vline = Span(location=0, dimension='height', line_color='black', line_width=1, line_alpha=0.3)
hline = Span(location=0, dimension='width', line_color='black', line_width=1, line_alpha=0.3)
mm_plot.renderers.extend([vline, hline])

# -------------------------------------------------
# create baseline lineweaver-burk plot
# -------------------------------------------------
x_line = np.linspace(-3, np.max(x_points))
y_line = mm.lineweaver_burk(x_line, vmax, km)

x_points = 1 / np.geomspace(0.1, 10, num=8)
y_points = mm.lineweaver_burk(x_points, vmax, km)

# set up source data and plot lines that will vary
lb_line_source = ColumnDataSource(data=dict(x=x_line, y=y_line))
lb_point_source = ColumnDataSource(data=dict(x=x_points, y=y_points))

lb_plot = figure(y_range=(-0.05, 0.8), x_range=(-1.5, 4), plot_width=pw, plot_height=ph,
                 x_axis_label='1/[S]: substrate concentration (1/μM)',
                 y_axis_label='1/initial velocity (s/μM)',
                 title='Lineweaver-Burk Kinetics')

lb_plot.line('x', 'y', source=lb_line_source, line_width=3, line_alpha=0.6, color='black')
lb_plot.circle('x', 'y', source=lb_point_source, size=10, color='black')

# add axes lines
vline = Span(location=0, dimension='height', line_color='black', line_width=1, line_alpha=0.3)
hline = Span(location=0, dimension='width', line_color='black', line_width=1, line_alpha=0.3)
lb_plot.renderers.extend([vline, hline])

# set up static line and annotations
lb_plot.line(x_line, y_line, line_width=5, color='blue', line_alpha=0.3)
lb_plot.circle(x_points, y_points, size=10, color='blue', line_alpha=0.3)

mytext = Label(x=-0.1, y=0.4, text='Km = 1 (μM), Vmax = 10 (μM/s)',
               text_color="blue", text_alpha=0.5)
lb_plot.add_layout(mytext)

# -------------------------------------------------
# make plot interactive
# -------------------------------------------------
# set up java script callback function to make plot interactive
vmax_slider = Slider(start=1, end=20, value=10, step=0.1, title="Vmax (μM/s)")
km_slider = Slider(start=0.1, end=10, value=1, step=0.1, title="Km (μM)")

callback = CustomJS(args=dict(mmLineSource=mm_line_source,
                              mmPointSource=mm_point_source,
                              lbLineSource=lb_line_source,
                              lbPointSource=lb_point_source,
                              vmax=vmax_slider,
                              km=km_slider),
                    code="""
    const mmLineData = mmLineSource.data;
    const mmPointData = mmPointSource.data;
    const lbLineData = lbLineSource.data;
    const lbPointData = lbPointSource.data;
    const VMAX = vmax.value;
    const KM = km.value;
    const mmlx = mmLineData['x'];
    const mmly = mmLineData['y'];
    const mmpx = mmPointData['x'];
    const mmpy = mmPointData['y'];
    const lblx = lbLineData['x'];
    const lbly = lbLineData['y'];
    const lbpx = lbPointData['x'];
    const lbpy = lbPointData['y'];

    // define functions for plotting data
    function mm(x, VMAX, KM){
        return (VMAX*x)/(KM+x);
    }

    function lb(x, VMAX, KM){
        return ((KM/VMAX)*x) + (1/VMAX);
    }

    // loop over data to edit
    for (var i = 0; i < mmlx.length; i++) {
        mmly[i] = mm(mmlx[i], VMAX, KM);
    }
    for (var i = 0; i < mmpx.length; i++) {
        mmpy[i] = mm(mmpx[i], VMAX, KM);
    }
    for (var i = 0; i < lblx.length; i++) {
        lbly[i] = lb(lblx[i], VMAX, KM);
    }
    for (var i = 0; i < lbpx.length; i++) {
        lbpy[i] = lb(lbpx[i], VMAX, KM);
    }

    // change data sources
    mmLineSource.change.emit();
    mmPointSource.change.emit();
    lbLineSource.change.emit();
    lbPointSource.change.emit();
""")

# add sliders to plot and display
vmax_slider.js_on_change('value', callback)
km_slider.js_on_change('value', callback)

# -------------------------------------------------
# create baseline michaelis-menten plot
# -------------------------------------------------
layout = row(
    mm_plot,
    lb_plot,
    column(vmax_slider, km_slider),
)

output_file(html_output_dir + "04-dual-lb-mm-plot.html", title="Michaelis-Menten Kinetics")
show(layout)

max_stars_repo_name: praelfj/pharm-interactive-plotting

max_issues_repo_name: praelfj/pharm-interactive-plotting

max_forks_repo_name: praelfj/pharm-interactive-plotting


text:
import tempfile
import shutil
import os

import numpy as np
from numpy import pi
from numpy.testing import (assert_array_almost_equal,
                           assert_equal, assert_warns)
import pytest
from pytest import raises as assert_raises

from scipy.odr import (Data, Model, ODR, RealData, OdrStop, OdrWarning,
                       multilinear, exponential, unilinear, quadratic,
                       polynomial)

class TestODR:

    # Bad Data for 'x'

    def test_bad_data(self):
        assert_raises(ValueError, Data, 2, 1)
        assert_raises(ValueError, RealData, 2, 1)

    # Empty Data for 'x'
    def empty_data_func(self, B, x):
        return B[0]*x + B[1]

    def test_empty_data(self):
        beta0 = [0.02, 0.0]
        linear = Model(self.empty_data_func)

        empty_dat = Data([], [])
        assert_warns(OdrWarning, ODR,
                     empty_dat, linear, beta0=beta0)

        empty_dat = RealData([], [])
        assert_warns(OdrWarning, ODR,
                     empty_dat, linear, beta0=beta0)

    # Explicit Example

    def explicit_fcn(self, B, x):
        ret = B[0] + B[1] * np.power(np.exp(B[2]*x) - 1.0, 2)
        return ret

    def explicit_fjd(self, B, x):
        eBx = np.exp(B[2]*x)
        ret = B[1] * 2.0 * (eBx-1.0) * B[2] * eBx
        return ret

    def explicit_fjb(self, B, x):
        eBx = np.exp(B[2]*x)
        res = np.vstack([np.ones(x.shape[-1]),
                         np.power(eBx-1.0, 2),
                         B[1]*2.0*(eBx-1.0)*eBx*x])
        return res

    def test_explicit(self):
        explicit_mod = Model(
            self.explicit_fcn,
            fjacb=self.explicit_fjb,
            fjacd=self.explicit_fjd,
            meta=dict(name='Sample Explicit Model',
                      ref='ODRPACK UG, pg. 39'),
        )
        explicit_dat = Data([0.,0.,5.,7.,7.5,10.,16.,26.,30.,34.,34.5,100.],
                        [1265.,1263.6,1258.,1254.,1253.,1249.8,1237.,1218.,1220.6,
                         1213.8,1215.5,1212.])
        explicit_odr = ODR(explicit_dat, explicit_mod, beta0=[1500.0, -50.0, -0.1],
                       ifixx=[0,0,1,1,1,1,1,1,1,1,1,0])
        explicit_odr.set_job(deriv=2)
        explicit_odr.set_iprint(init=0, iter=0, final=0)

        out = explicit_odr.run()
        assert_array_almost_equal(
            out.beta,
            np.array([1.2646548050648876e+03, -5.4018409956678255e+01,
                -8.7849712165253724e-02]),
        )
        assert_array_almost_equal(
            out.sd_beta,
            np.array([1.0349270280543437, 1.583997785262061, 0.0063321988657267]),
        )
        assert_array_almost_equal(
            out.cov_beta,
            np.array([[4.4949592379003039e-01, -3.7421976890364739e-01,
                 -8.0978217468468912e-04],
               [-3.7421976890364739e-01, 1.0529686462751804e+00,
                 -1.9453521827942002e-03],
               [-8.0978217468468912e-04, -1.9453521827942002e-03,
                  1.6827336938454476e-05]]),
        )

    # Implicit Example

    def implicit_fcn(self, B, x):
        return (B[2]*np.power(x[0]-B[0], 2) +
                2.0*B[3]*(x[0]-B[0])*(x[1]-B[1]) +
                B[4]*np.power(x[1]-B[1], 2) - 1.0)

    def test_implicit(self):
        implicit_mod = Model(
            self.implicit_fcn,
            implicit=1,
            meta=dict(name='Sample Implicit Model',
                      ref='ODRPACK UG, pg. 49'),
        )
        implicit_dat = Data([
            [0.5,1.2,1.6,1.86,2.12,2.36,2.44,2.36,2.06,1.74,1.34,0.9,-0.28,
             -0.78,-1.36,-1.9,-2.5,-2.88,-3.18,-3.44],
            [-0.12,-0.6,-1.,-1.4,-2.54,-3.36,-4.,-4.75,-5.25,-5.64,-5.97,-6.32,
             -6.44,-6.44,-6.41,-6.25,-5.88,-5.5,-5.24,-4.86]],
            1,
        )
        implicit_odr = ODR(implicit_dat, implicit_mod,
            beta0=[-1.0, -3.0, 0.09, 0.02, 0.08])

        out = implicit_odr.run()
        assert_array_almost_equal(
            out.beta,
            np.array([-0.9993809167281279, -2.9310484652026476, 0.0875730502693354,
                0.0162299708984738, 0.0797537982976416]),
        )
        assert_array_almost_equal(
            out.sd_beta,
            np.array([0.1113840353364371, 0.1097673310686467, 0.0041060738314314,
                0.0027500347539902, 0.0034962501532468]),
        )
        assert_array_almost_equal(
            out.cov_beta,
            np.array([[2.1089274602333052e+00, -1.9437686411979040e+00,
                  7.0263550868344446e-02, -4.7175267373474862e-02,
                  5.2515575927380355e-02],
               [-1.9437686411979040e+00, 2.0481509222414456e+00,
                 -6.1600515853057307e-02, 4.6268827806232933e-02,
                 -5.8822307501391467e-02],
               [7.0263550868344446e-02, -6.1600515853057307e-02,
                  2.8659542561579308e-03, -1.4628662260014491e-03,
                  1.4528860663055824e-03],
               [-4.7175267373474862e-02, 4.6268827806232933e-02,
                 -1.4628662260014491e-03, 1.2855592885514335e-03,
                 -1.2692942951415293e-03],
               [5.2515575927380355e-02, -5.8822307501391467e-02,
                  1.4528860663055824e-03, -1.2692942951415293e-03,
                  2.0778813389755596e-03]]),
        )

    # Multi-variable Example

    def multi_fcn(self, B, x):
        if (x < 0.0).any():
            raise OdrStop
        theta = pi*B[3]/2.
        ctheta = np.cos(theta)
        stheta = np.sin(theta)
        omega = np.power(2.*pi*x*np.exp(-B[2]), B[3])
        phi = np.arctan2((omega*stheta), (1.0 + omega*ctheta))
        r = (B[0] - B[1]) * np.power(np.sqrt(np.power(1.0 + omega*ctheta, 2) +
             np.power(omega*stheta, 2)), -B[4])
        ret = np.vstack([B[1] + r*np.cos(B[4]*phi),
                         r*np.sin(B[4]*phi)])
        return ret

    def test_multi(self):
        multi_mod = Model(
            self.multi_fcn,
            meta=dict(name='Sample Multi-Response Model',
                      ref='ODRPACK UG, pg. 56'),
        )

        multi_x = np.array([30.0, 50.0, 70.0, 100.0, 150.0, 200.0, 300.0, 500.0,
            700.0, 1000.0, 1500.0, 2000.0, 3000.0, 5000.0, 7000.0, 10000.0,
            15000.0, 20000.0, 30000.0, 50000.0, 70000.0, 100000.0, 150000.0])
        multi_y = np.array([
            [4.22, 4.167, 4.132, 4.038, 4.019, 3.956, 3.884, 3.784, 3.713,
             3.633, 3.54, 3.433, 3.358, 3.258, 3.193, 3.128, 3.059, 2.984,
             2.934, 2.876, 2.838, 2.798, 2.759],
            [0.136, 0.167, 0.188, 0.212, 0.236, 0.257, 0.276, 0.297, 0.309,
             0.311, 0.314, 0.311, 0.305, 0.289, 0.277, 0.255, 0.24, 0.218,
             0.202, 0.182, 0.168, 0.153, 0.139],
        ])
        n = len(multi_x)
        multi_we = np.zeros((2, 2, n), dtype=float)
        multi_ifixx = np.ones(n, dtype=int)
        multi_delta = np.zeros(n, dtype=float)

        multi_we[0,0,:] = 559.6
        multi_we[1,0,:] = multi_we[0,1,:] = -1634.0
        multi_we[1,1,:] = 8397.0

        for i in range(n):
            if multi_x[i] < 100.0:
                multi_ifixx[i] = 0
            elif multi_x[i] <= 150.0:
                pass  # defaults are fine
            elif multi_x[i] <= 1000.0:
                multi_delta[i] = 25.0
            elif multi_x[i] <= 10000.0:
                multi_delta[i] = 560.0
            elif multi_x[i] <= 100000.0:
                multi_delta[i] = 9500.0
            else:
                multi_delta[i] = 144000.0
            if multi_x[i] == 100.0 or multi_x[i] == 150.0:
                multi_we[:,:,i] = 0.0

        multi_dat = Data(multi_x, multi_y, wd=1e-4/np.power(multi_x, 2),
            we=multi_we)
        multi_odr = ODR(multi_dat, multi_mod, beta0=[4.,2.,7.,.4,.5],
            delta0=multi_delta, ifixx=multi_ifixx)
        multi_odr.set_job(deriv=1, del_init=1)

        out = multi_odr.run()
        assert_array_almost_equal(
            out.beta,
            np.array([4.3799880305938963, 2.4333057577497703, 8.0028845899503978,
                0.5101147161764654, 0.5173902330489161]),
        )
        assert_array_almost_equal(
            out.sd_beta,
            np.array([0.0130625231081944, 0.0130499785273277, 0.1167085962217757,
                0.0132642749596149, 0.0288529201353984]),
        )
        assert_array_almost_equal(
            out.cov_beta,
            np.array([[0.0064918418231375, 0.0036159705923791, 0.0438637051470406,
                -0.0058700836512467, 0.011281212888768],
               [0.0036159705923791, 0.0064793789429006, 0.0517610978353126,
                -0.0051181304940204, 0.0130726943624117],
               [0.0438637051470406, 0.0517610978353126, 0.5182263323095322,
                -0.0563083340093696, 0.1269490939468611],
               [-0.0058700836512467, -0.0051181304940204, -0.0563083340093696,
                 0.0066939246261263, -0.0140184391377962],
               [0.011281212888768, 0.0130726943624117, 0.1269490939468611,
                -0.0140184391377962, 0.0316733013820852]]),
        )

    # Pearson's Data
    # K. Pearson, Philosophical Magazine, 2, 559 (1901)

    def pearson_fcn(self, B, x):
        return B[0] + B[1]*x

    def test_pearson(self):
        p_x = np.array([0.,.9,1.8,2.6,3.3,4.4,5.2,6.1,6.5,7.4])
        p_y = np.array([5.9,5.4,4.4,4.6,3.5,3.7,2.8,2.8,2.4,1.5])
        p_sx = np.array([.03,.03,.04,.035,.07,.11,.13,.22,.74,1.])
        p_sy = np.array([1.,.74,.5,.35,.22,.22,.12,.12,.1,.04])

        p_dat = RealData(p_x, p_y, sx=p_sx, sy=p_sy)

        # Reverse the data to test invariance of results
        pr_dat = RealData(p_y, p_x, sx=p_sy, sy=p_sx)

        p_mod = Model(self.pearson_fcn, meta=dict(name='Uni-linear Fit'))

        p_odr = ODR(p_dat, p_mod, beta0=[1.,1.])
        pr_odr = ODR(pr_dat, p_mod, beta0=[1.,1.])

        out = p_odr.run()
        assert_array_almost_equal(
            out.beta,
            np.array([5.4767400299231674, -0.4796082367610305]),
        )
        assert_array_almost_equal(
            out.sd_beta,
            np.array([0.3590121690702467, 0.0706291186037444]),
        )
        assert_array_almost_equal(
            out.cov_beta,
            np.array([[0.0854275622946333, -0.0161807025443155],
               [-0.0161807025443155, 0.003306337993922]]),
        )

        rout = pr_odr.run()
        assert_array_almost_equal(
            rout.beta,
            np.array([11.4192022410781231, -2.0850374506165474]),
        )
        assert_array_almost_equal(
            rout.sd_beta,
            np.array([0.9820231665657161, 0.3070515616198911]),
        )
        assert_array_almost_equal(
            rout.cov_beta,
            np.array([[0.6391799462548782, -0.1955657291119177],
               [-0.1955657291119177, 0.0624888159223392]]),
        )

    # Lorentz Peak
    # The data is taken from one of the undergraduate physics labs I performed.

    def lorentz(self, beta, x):
        return (beta[0]*beta[1]*beta[2] / np.sqrt(np.power(x*x -
            beta[2]*beta[2], 2.0) + np.power(beta[1]*x, 2.0)))

    def test_lorentz(self):
        l_sy = np.array([.29]*18)
        l_sx = np.array([.000972971,.000948268,.000707632,.000706679,
            .000706074, .000703918,.000698955,.000456856,
            .000455207,.000662717,.000654619,.000652694,
            .000000859202,.00106589,.00106378,.00125483, .00140818,.00241839])

        l_dat = RealData(
            [3.9094, 3.85945, 3.84976, 3.84716, 3.84551, 3.83964, 3.82608,
             3.78847, 3.78163, 3.72558, 3.70274, 3.6973, 3.67373, 3.65982,
             3.6562, 3.62498, 3.55525, 3.41886],
            [652, 910.5, 984, 1000, 1007.5, 1053, 1160.5, 1409.5, 1430, 1122,
             957.5, 920, 777.5, 709.5, 698, 578.5, 418.5, 275.5],
            sx=l_sx,
            sy=l_sy,
        )
        l_mod = Model(self.lorentz, meta=dict(name='Lorentz Peak'))
        l_odr = ODR(l_dat, l_mod, beta0=(1000., .1, 3.8))

        out = l_odr.run()
        assert_array_almost_equal(
            out.beta,
            np.array([1.4306780846149925e+03, 1.3390509034538309e-01,
                 3.7798193600109009e+00]),
        )
        assert_array_almost_equal(
            out.sd_beta,
            np.array([7.3621186811330963e-01, 3.5068899941471650e-04,
                 2.4451209281408992e-04]),
        )
        assert_array_almost_equal(
            out.cov_beta,
            np.array([[2.4714409064597873e-01, -6.9067261911110836e-05,
                 -3.1236953270424990e-05],
               [-6.9067261911110836e-05, 5.6077531517333009e-08,
                  3.6133261832722601e-08],
               [-3.1236953270424990e-05, 3.6133261832722601e-08,
                  2.7261220025171730e-08]]),
        )

    def test_ticket_1253(self):
        def linear(c, x):
            return c[0]*x+c[1]

        c = [2.0, 3.0]
        x = np.linspace(0, 10)
        y = linear(c, x)

        model = Model(linear)
        data = Data(x, y, wd=1.0, we=1.0)
        job = ODR(data, model, beta0=[1.0, 1.0])
        result = job.run()
        assert_equal(result.info, 2)

    # Verify fix for gh-9140

    def test_ifixx(self):
        x1 = [-2.01, -0.99, -0.001, 1.02, 1.98]
        x2 = [3.98, 1.01, 0.001, 0.998, 4.01]
        fix = np.vstack((np.zeros_like(x1, dtype=int), np.ones_like(x2, dtype=int)))
        data = Data(np.vstack((x1, x2)), y=1, fix=fix)
        model = Model(lambda beta, x: x[1, :] - beta[0] * x[0, :]**2., implicit=True)

        odr1 = ODR(data, model, beta0=np.array([1.]))
        sol1 = odr1.run()
        odr2 = ODR(data, model, beta0=np.array([1.]), ifixx=fix)
        sol2 = odr2.run()
        assert_equal(sol1.beta, sol2.beta)

    # verify bugfix for #11800 in #11802
    def test_ticket_11800(self):
        # parameters
        beta_true = np.array([1.0, 2.3, 1.1, -1.0, 1.3, 0.5])
        nr_measurements = 10

        std_dev_x = 0.01
        x_error = np.array([[0.00063445, 0.00515731, 0.00162719, 0.01022866,
            -0.01624845, 0.00482652, 0.00275988, -0.00714734, -0.00929201, -0.00687301],
            [-0.00831623, -0.00821211, -0.00203459, 0.00938266, -0.00701829,
            0.0032169, 0.00259194, -0.00581017, -0.0030283, 0.01014164]])

        std_dev_y = 0.05
        y_error = np.array([[0.05275304, 0.04519563, -0.07524086, 0.03575642,
            0.04745194, 0.03806645, 0.07061601, -0.00753604, -0.02592543, -0.02394929],
            [0.03632366, 0.06642266, 0.08373122, 0.03988822, -0.0092536,
            -0.03750469, -0.03198903, 0.01642066, 0.01293648, -0.05627085]])

        beta_solution = np.array([
            2.62920235756665876536e+00, -1.26608484996299608838e+02, 1.29703572775403074502e+02,
            -1.88560985401185465804e+00, 7.83834160771274923718e+01, -7.64124076838087091801e+01])

        # model's function and Jacobians
        def func(beta, x):
            y0 = beta[0] + beta[1] * x[0, :] + beta[2] * x[1, :]
            y1 = beta[3] + beta[4] * x[0, :] + beta[5] * x[1, :]

            return np.vstack((y0, y1))

        def df_dbeta_odr(beta, x):
            nr_meas = np.shape(x)[1]
            zeros = np.zeros(nr_meas)
            ones = np.ones(nr_meas)

            dy0 = np.array([ones, x[0, :], x[1, :], zeros, zeros, zeros])
            dy1 = np.array([zeros, zeros, zeros, ones, x[0, :], x[1, :]])

            return np.stack((dy0, dy1))

        def df_dx_odr(beta, x):
            nr_meas = np.shape(x)[1]
            ones = np.ones(nr_meas)

            dy0 = np.array([beta[1] * ones, beta[2] * ones])
            dy1 = np.array([beta[4] * ones, beta[5] * ones])
            return np.stack((dy0, dy1))

        # do measurements with errors in independent and dependent variables
        x0_true = np.linspace(1, 10, nr_measurements)
        x1_true = np.linspace(1, 10, nr_measurements)
        x_true = np.array([x0_true, x1_true])

        y_true = func(beta_true, x_true)

        x_meas = x_true + x_error
        y_meas = y_true + y_error

        # estimate model's parameters
        model_f = Model(func, fjacb=df_dbeta_odr, fjacd=df_dx_odr)

        data = RealData(x_meas, y_meas, sx=std_dev_x, sy=std_dev_y)

        odr_obj = ODR(data, model_f, beta0=0.9 * beta_true, maxit=100)
        #odr_obj.set_iprint(init=2, iter=0, iter_step=1, final=1)
        odr_obj.set_job(deriv=3)

        odr_out = odr_obj.run()

        # check results
        assert_equal(odr_out.info, 1)
        assert_array_almost_equal(odr_out.beta, beta_solution)

    def test_multilinear_model(self):
        x = np.linspace(0.0, 5.0)
        y = 10.0 + 5.0 * x
        data = Data(x, y)
        odr_obj = ODR(data, multilinear)
        output = odr_obj.run()
        assert_array_almost_equal(output.beta, [10.0, 5.0])

    def test_exponential_model(self):
        x = np.linspace(0.0, 5.0)
        y = -10.0 + np.exp(0.5*x)
        data = Data(x, y)
        odr_obj = ODR(data, exponential)
        output = odr_obj.run()
        assert_array_almost_equal(output.beta, [-10.0, 0.5])

    def test_polynomial_model(self):
        x = np.linspace(0.0, 5.0)
        y = 1.0 + 2.0 * x + 3.0 * x ** 2 + 4.0 * x ** 3
        poly_model = polynomial(3)
        data = Data(x, y)
        odr_obj = ODR(data, poly_model)
        output = odr_obj.run()
        assert_array_almost_equal(output.beta, [1.0, 2.0, 3.0, 4.0])

    def test_unilinear_model(self):
        x = np.linspace(0.0, 5.0)
        y = 1.0 * x + 2.0
        data = Data(x, y)
        odr_obj = ODR(data, unilinear)
        output = odr_obj.run()
        assert_array_almost_equal(output.beta, [1.0, 2.0])

    def test_quadratic_model(self):
        x = np.linspace(0.0, 5.0)
        y = 1.0 * x ** 2 + 2.0 * x + 3.0
        data = Data(x, y)
        odr_obj = ODR(data, quadratic)
        output = odr_obj.run()
        assert_array_almost_equal(output.beta, [1.0, 2.0, 3.0])

    def test_work_ind(self):

        def func(par, x):
            b0, b1 = par
            return b0 + b1 * x

        # generate some data
        n_data = 4
        x = np.arange(n_data)
        y = np.where(x % 2, x + 0.1, x - 0.1)
        x_err = np.full(n_data, 0.1)
        y_err = np.full(n_data, 0.1)

        # do the fitting
        linear_model = Model(func)
        real_data = RealData(x, y, sx=x_err, sy=y_err)
        odr_obj = ODR(real_data, linear_model, beta0=[0.4, 0.4])
        odr_obj.set_job(fit_type=0)
        out = odr_obj.run()

        sd_ind = out.work_ind['sd']
        assert_array_almost_equal(out.sd_beta,
                                  out.work[sd_ind:sd_ind + len(out.sd_beta)])

    @pytest.mark.skipif(True, reason="Fortran I/O prone to crashing so better "
                                     "not to run this test, see gh-13127")
    def test_output_file_overwrite(self):
        """
        Verify fix for gh-1892
        """
        def func(b, x):
            return b[0] + b[1] * x

        p = Model(func)
        data = Data(np.arange(10), 12 * np.arange(10))
        tmp_dir = tempfile.mkdtemp()
        error_file_path = os.path.join(tmp_dir, "error.dat")
        report_file_path = os.path.join(tmp_dir, "report.dat")
        try:
            ODR(data, p, beta0=[0.1, 13], errfile=error_file_path,
                rptfile=report_file_path).run()
            ODR(data, p, beta0=[0.1, 13], errfile=error_file_path,
                rptfile=report_file_path, overwrite=True).run()
        finally:
            # remove output files for clean up
            shutil.rmtree(tmp_dir)

max_stars_repo_name: Ennosigaeon/scipy

max_issues_repo_name: Ennosigaeon/scipy

max_forks_repo_name: Ennosigaeon/scipy

reason: import numpy,from numpy,from scipy


text:
# two-dimensional indicator
# By Fang Wan

import tensorflow as tf
import math
import os
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
tf.set_random_seed(0)
import numpy as np
import pandas as pd

# Download images and labels into mnist.test (10K images+labels) and mnist.train (60K images+labels)
mnist = read_data_sets("data", one_hot=True, reshape=False, validation_size=0)

# input X: 28x28 grayscale images, the first dimension (None) will index the images in the mini-batch
X = tf.placeholder(tf.float32, [None, 28, 28, 1])
X2 = tf.placeholder(tf.float32, [None, 2])
# correct answers will go here
Y_ = tf.placeholder(tf.float32, [None, 11])
# variable learning rate
lr = tf.placeholder(tf.float32)

# three convolutional layers with their channel counts, and a
# fully connected layer (tha last layer has 10 softmax neurons)
K = 4  # first convolutional layer output depth
L = 8  # second convolutional layer output depth
M = 12  # third convolutional layer
N = 200  # fully connected layer

W1 = tf.Variable(tf.truncated_normal([5, 5, 1, K], stddev=0.1))  # 5x5 patch, 1 input channel, K output channels
B1 = tf.Variable(tf.ones([K])/10)
W2 = tf.Variable(tf.truncated_normal([5, 5, K, L], stddev=0.1))
B2 = tf.Variable(tf.ones([L])/10)
W3 = tf.Variable(tf.truncated_normal([4, 4, L, M], stddev=0.1))
B3 = tf.Variable(tf.ones([M])/10)

W21 = tf.Variable(tf.truncated_normal([2, 12], stddev=0.1))
B21 = tf.Variable(tf.ones([12])/10)

W4 = tf.Variable(tf.truncated_normal([7 * 7 * M, N], stddev=0.1))
B4 = tf.Variable(tf.ones([N])/10)
W5 = tf.Variable(tf.truncated_normal([N, 11], stddev=0.1))
B5 = tf.Variable(tf.ones([11])/10)

# The model
stride = 1  # output is 28x28
Y1 = tf.nn.relu(tf.nn.conv2d(X, W1, strides=[1, stride, stride, 1], padding='SAME') + B1)
stride = 2  # output is 14x14
Y2 = tf.nn.relu(tf.nn.conv2d(Y1, W2, strides=[1, stride, stride, 1], padding='SAME') + B2)
stride = 2  # output is 7x7
Y3 = tf.nn.relu(tf.nn.conv2d(Y2, W3, strides=[1, stride, stride, 1], padding='SAME') + B3)

Y21 = tf.nn.relu(tf.matmul(X2, W21) + B21)
Y21 = tf.reshape(Y21,[-1, 1, 1, 12])
Y21 = tf.tile(Y21, [1, 7, 7, 1])
Y3 = Y3 + Y21

# reshape the output from the third convolution for the fully connected layer
YY = tf.reshape(Y3, shape=[-1, 7 * 7 * M])

Y4 = tf.nn.relu(tf.matmul(YY, W4) + B4)
Ylogits = tf.matmul(Y4, W5) + B5
Y = tf.nn.softmax(Ylogits)

# cross-entropy loss function (= -sum(Y_i * log(Yi)) ), normalised for batches of 100  images
# TensorFlow provides the softmax_cross_entropy_with_logits function to avoid numerical stability
# problems with log(0) which is NaN
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=Ylogits, labels=Y_)
cross_entropy = tf.reduce_mean(cross_entropy)*100

# accuracy of the trained model, between 0 (worst) and 1 (best)
correct_prediction = tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# training step, the learning rate is a placeholder
train_step = tf.train.AdamOptimizer(lr).minimize(cross_entropy)

# init
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
saver = tf.train.Saver()

# Setting up the indicators
checkpoint_path = './checkpoint_31'
if not os.path.isdir(checkpoint_path):
    os.mkdir(checkpoint_path)

indicators_0 = {0:[0,1,2,3,4], 1:[5,6,7,8,9]} #1
indicators_1 = {0:[0,2,4,6,8], 1:[1,3,5,7,9]} #2
l1 = len(indicators_0)
l2 = len(indicators_1)
n = l1 * l2

np.savez(checkpoint_path+'/indicators', indicators_0 = indicators_0, indicators_1 = indicators_1)

# traverse all indicators and generate new labels
def generate_data(batch_X, batch_Y):
    l = len(batch_X)
    batch_X_rep = np.tile(batch_X, [n,1,1,1])
    # [0,0],...,[0,0],[1,0],...,[1,0],[0,1],...,[0,1],[1,1],...,[1,1]
    batch_X2_rep = np.tile( np.array([[i,j] for j in range(2) for i in range(2)]).reshape([1, n, 2]), [l,1,1] ).reshape([l*n,2], order='F')

    batch_id = np.argmax( batch_Y, axis=1 ).reshape([l,1])
    batch_id_rep = np.tile(batch_id, [n,1])

    # find the true indicator of each image
    batch_X2_rep_true = np.tile(
        np.array(list(map(lambda x: [[k0,k1] for k0, v0 in indicators_0.items() for k1, v1 in indicators_1.items() if x in v0 and x in v1], batch_id))).squeeze() ,
        [n,1])

    # generate the new labels including the conflict class
    batch_Y_rep = np.zeros((l*n,10+1))
    for i, match in zip(np.arange(l*n),batch_X2_rep_true==batch_X2_rep):
        if match.all():
            batch_Y_rep[i][batch_id_rep[i]] = 1
        else:
            batch_Y_rep[i][10] = 1
    return batch_X_rep, batch_X2_rep, batch_Y_rep

# You can call this function in a loop to train the model, 100 images at a time
a_train = []
a_test = []
test_prediction = []
for i in range(10001):
    # training on batches of 100 images with 100 labels
    batch_X, batch_Y = mnist.train.next_batch(100)
    batch_X_rep, batch_X2_rep, batch_Y_rep = generate_data(batch_X, batch_Y)
    # learning rate decay
    max_learning_rate = 0.003
    min_learning_rate = 0.0001
    decay_speed = 2000.0
    learning_rate = min_learning_rate + (max_learning_rate - min_learning_rate) * math.exp(-i/decay_speed)
    sess.run(train_step, {X: batch_X_rep, X2: batch_X2_rep, Y_: batch_Y_rep, lr: learning_rate})
    # compute training values for visualisation
    if i%10==0:
        a = sess.run(accuracy, {X: batch_X_rep, X2: batch_X2_rep, Y_: batch_Y_rep})
        print(str(i) + ": accuracy:" + str(a) + " (lr:" + str(learning_rate) + ")")
        a_train.append(a)
    # compute test values for visualisation
    if i%100==0:
        test_X_rep, test_X2_rep, test_Y_rep = generate_data(mnist.test.images, mnist.test.labels)
        a = sess.run(accuracy, {X: test_X_rep, X2: test_X2_rep, Y_: test_Y_rep})
        a_test.append(a)
        y = sess.run(Y, {X: test_X_rep, X2: test_X2_rep})
        test_prediction.append(y)
        print(str(i) + ": ********* epoch " + str(i*100//mnist.train.images.shape[0]+1) + " ********* test accuracy:" + str(a))

saver.save(sess, checkpoint_path + '/Network')

print("max test accuracy: " + str(max(a_test)))
np.savez(checkpoint_path+'/accuracy', a_test=a_test, a_train=a_train, test_prediction=test_prediction)

# best 0.994525 after 10000 iterations

# calculate prediction accuracy
y = np.argmax(mnist.test.labels, 1)

y_ = test_prediction[np.argmax(a_test)] #[10000*n,11]

# 0 = [0,0], 1=[1,0], 2=[0,1], 3=[1,1]
indicators = {0:[0,2,4], 1:[6,8], 2:[1,3], 3:[5,7,9]}
cols = [ "Indicator_"+str(i) for i in range(n)]
y_prediction = pd.DataFrame(np.zeros([10000, n]), columns=cols)
for i in range(n):
    y_prediction['Indicator_'+str(i)] = np.argmax( y_[i*10000:(i+1)*10000,:],1)

true_count = 0.0
pass_logic_check_count = 0.0
for i in range(10000):
    critirier = y_prediction.loc[i] == 10
    if sum(critirier) != n-1:
        continue
    if y_prediction.loc[i,np.argmin(critirier)] not in indicators[int(np.argmin(critirier).split('_')[1])]:
        continue
# 99.48% pass the logic check in case #1
    pass_logic_check_count += 1
    if y_prediction.loc[i,np.argmin(critirier)] == y[i]:
        true_count += 1

print('The accuracy without logic is %s'%(max(a_test)))
print('The rate of passing logic check is %s'%(pass_logic_check_count/10000))
print('The accuracy with logic check is %s'%(true_count/10000))
print('The accuracy after passing logic check is %s'%(true_count/pass_logic_check_count))


text:
import numpy as np
from munch import Munch
from plaster.tools.utils.utils import np_safe_divide
from plaster.tools.zplots.zplots import ZPlots
from plaster.tools.ipynb_helpers.displays import hd
from IPython.core.display import display
from plaster.tools.plots import plots

"""
This contain contains reporting functionality in development used by jupyter notebooks directly
or by more than one of the more specialized dev plotting modules, such as plots_dev_mhc and
plots_dev_ptm.  The stuff that ends up in here is probably used by *both* of those, or
is called directly by a notebook but is too "in development" to be included in plots.py
"""

def _run_labels(run_name):
    return "_".join(run_name.split("_")[:-1])

def _run_iz_count_pep_iz(df):
    """
    Given a df that has many pep_i that each belong to some run_i,
    return a list of run_i reverse-sorted for the number of pep_i.
    I.e. the first elem of this list is the run_i that has
    the most pep_i.

    Several parallel lists are returned, each as values in a Munch:

    run_iz: the run_i sorted by who has the most peptides
    run_labels: the run_name, with hash suffix removed
    pep_counts: the peptide count for each run
    peps: a list of pep_i for each run
    """

    grp = df.groupby("run_i")
    run_iz = np.array(list(grp.indices.keys()))
    peps = np.array([g.pep_i.values for r, g in grp])
    pep_counts = grp.pep_i.count().values
    run_labels = np.array([_run_labels(g.run_name.iloc[0]) for r, g in grp])
    pep_counts_reverse_sort_i = np.argsort(pep_counts)[::-1]
    return Munch(
        run_iz=run_iz[pep_counts_reverse_sort_i],
        run_labels=run_labels[pep_counts_reverse_sort_i],
        pep_counts=pep_counts[pep_counts_reverse_sort_i],
        peps=peps[pep_counts_reverse_sort_i],
    )

def peps_prec_at_min_recall_df(peps_prs_df, min_recall=0.1):
    """
    Given a df containing prs for one or more peptides, find the best precision
    for each peptide that meets the min_recall requirement.  If it cannot be
    met (for a given peptide), return None.

    Though the information here all deals in precision-recall, it
    seems strange to place this in CallBag whose business is computing PR curves.
    If this code were placed there, it would be @staticmethod.

    peps_prs_df: a df containing a set of prec,recall scores for each pep_i
    min_recall: the recall threshold to apply in filtering results

    returns: a df containing one row for each pep_i, which also includes
             the best precision available at the requested min_recall, or
             fallback values as stipulated above in the case this threshold
             cannot be met for some peptide(s).
    """

    def best_prec_at_recall(df):
        df = df.sort_values("recall", ascending=False).reset_index(drop=True)
        precs = df[df.recall >= min_recall].prec
        # Returning best precision that meets requested recall threshold.
        if len(precs) > 0:
            return df.loc[precs.idxmax()]

        # There is no entry in which recall > min_recall.
        # Return the best recall available, which may get discarded later.
        return df.loc[0]

    df = peps_prs_df.groupby("pep_i").apply(best_prec_at_recall)
    df = df[df.recall >= min_recall]
    return df.sort_values(by=["prec", "recall"], ascending=[False, False]).reset_index(
        drop=True
    )

def plot_confusion_matrix_compare(
    run, pep_i, score_threshold, classifier=None,
):
    """
    Plot two confusion matrices - one with all calls, and one with calls culled
    according to score_threshold.  Display precision and recall for pep_i
    in the title of the comparison plots.

    classifier: None to use any available preferred classifier, or one of the
                supported classifiers in RunResult::get_available_classifiers(),
                e.g. 'rf', 'nn'

    """
    cb = run.test_call_bag(classifier=classifier)
    z = ZPlots()
    with z(_cols=2, f_x_axis_label="true pep_i"):

        def pr(cm, p_i):
            prec = np_safe_divide(cm[p_i, p_i], np.sum(cm[p_i, :]))
            recall = np_safe_divide(cm[p_i, p_i], np.sum(cm[:, p_i]))
            return prec, recall

        conf_mat = cb.conf_mat()
        prec, recall = pr(conf_mat, pep_i)
        z.im(
            np.array(conf_mat),
            _size=500,
            f_title=f"{run.run_name}: pep_i={pep_i} precision={prec:.2f} recall={recall:.2f} {cb.classifier_name}",
            f_y_axis_label="pep_i   predicted by classifier",
        )

        conf_mat = cb.conf_mat_at_score_threshold(score_threshold)
        prec, recall = pr(conf_mat, pep_i)
        z.im(
            np.array(conf_mat),
            _size=500,
            f_title=f"precision={prec:.2f} recall={recall:.2f} score={score_threshold:.2f} {cb.classifier_name}",
        )

def plot_flu_info(run, flu, peps_prs_df, min_recall=0.005, classifier=None):
    """

    flu: string fluorosequence e.g. '..1......;0,0,0'

    peps_prs_df: the DataFrame from a notebook containing precision,recall,score
                 for the peptides you're interested in.

    classifier: None to use any available preferred classifier, or one of the
                supported classifiers in RunResult::get_available_classifiers(),
                e.g. 'rf', 'nn'
    """
    hd("h2", f"flu_info for: {flu}")

    cb = run.test_call_bag(classifier=classifier)
    pf2 = cb.peps__pepstrs__flustrs__p2()
    pf2 = pf2[pf2.flustr == flu]
    pep_iz = pf2.pep_i.values
    print(f"Peptides: {pep_iz}")

    if peps_prs_df.empty:
        # The peps_prs_df that is passed to us is typically the large
        # DataFrame with PRS information for ALL peptides across ALL
        # runs, but if this is a PTM notebook, it is often the case
        # that PRS info is only loaded for peptides with PTM locations.
        # This DataFrame has lots of other information, which is what
        # we actually want to display, otherwise we'd just recompute
        # the PRS for these peptides here.
        print("No PR info found for peps. (No PTM peps with this flu?)")
    else:
        df_pr = peps_prec_at_min_recall_df(peps_prs_df, min_recall=min_recall)
        display(df_pr)

    # See the fn in plots_dev_mhc which calls the lower-level _plot_pr_curve using the
    # prs info we already have in the df.  The following call recomputes the PR all over
    # again for these peps!
    plots.plot_pr_breakout(
        run,
        pep_iz=pep_iz,
        _size=500,
        f_title=f"PR for peptides with flu {flu} ({cb.classifier_name})",
    )

max_stars_repo_name: pymc-labs/plaster

max_issues_repo_name: pymc-labs/plaster

max_forks_repo_name: pymc-labs/plaster


text:
import networkx as nx

def parse_line(i, line, G):
  split_line = line.split(' ')
  instruction = split_line[0]
  if instruction == 'acc':
    dest = i+1
    weight = int(split_line[1])
  elif instruction == 'nop':
    dest = i+1
    weight = 0
  elif instruction == 'jmp':
    dest = i+int(split_line[1])
    weight = 0
  G.add_edge(i, dest, weight=weight)

def get_acc_count(G, s, acc, visited):
  if s in visited:
    visited.remove(s)
    return acc
  elif list(G.successors(s)) == []:
    return acc
  else:
    visited.add(s)
    for v in G.successors(s):
      return get_acc_count(G, v, acc + G.get_edge_data(s,v)['weight'], visited)

def read_graph(input_string):
  all_lines = input_string.split('\n')
  G = nx.DiGraph()
  for i, line in enumerate(all_lines):
    parse_line(i, line, G)
  return G

def switch_statement(i , input_string):
  all_lines = input_string.split('\n')
  line = all_lines[i]
  stmt, num = line.split(' ')[0], line.split(' ')[1]
  if stmt == 'acc':
    return False, input_string
  elif stmt == 'jmp':
    new_line = 'nop {}'.format(num)
  elif stmt == 'nop':
    new_line = 'jmp {}'.format(num)
  return True, '\n'.join(all_lines[:i] + [new_line] + all_lines[i+1:])

def main():
  input_filename = 'input.txt'
  with open(input_filename, 'r') as input:
    G = read_graph(input.read())
  acc = get_acc_count(G, s=0, acc=0, visited=set([]))

  print('Star 1 -- acc-count until cycle: {}'.format(acc))

  lines = G.size()
  input = open(input_filename, 'r')
  input_string = input.read()
  for i in range(lines-1):
    b, stream = switch_statement(i, input_string)
    if b:
      G = read_graph(stream)
      try:
        nx.find_cycle(G, source=0)
      except nx.exception.NetworkXNoCycle:
        acc = get_acc_count(G, s=0, acc=0, visited=set([]))
        print('Star 2 -- acc-count for modified cycle-free-program: {}'.format(acc))

if __name__ == "__main__":
  main()

input_filename = 'input.txt'
input = open(input_filename, 'r')
G = nx.DiGraph()
for i, line in enumerate(input):
  parse_line(i, line, G)

reason: import networkx


text:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date    : Jan-20-22 16:05
# @Author  : Kelley Kan HUANG (kan.huang@connect.ust.hk)
# @RefLink : https://karpathy.github.io/2015/05/21/rnn-effectiveness/

import numpy as np
import torch
import torch.nn as nn

class RNN(object):
    """

    The RNN receives input vectors of size D, has a vocab size of V, works on
    sequences of length T, has an RNN hidden dimension of H, uses word vectors
    of dimension W, and operates on minibatches of size N.

    """

    def __init__(self, word_to_idx, wordvec_dim=128,
                 hidden_dim=128, cell_type='rnn', dtype=np.float32):
        self.word_to_idx = word_to_idx
        self.wordvec_dim = wordvec_dim
        self.hidden_dim = hidden_dim
        self.cell_type = cell_type
        self.dtype = dtype

        self.h = None
        self.params = {}
        self.reset_parameters()

        # Cast parameters to correct dtype
        for k, v in self.params.items():
            self.params[k] = v.astype(self.dtype)

    def reset_parameters(self):
        wordvec_dim = self.wordvec_dim
        hidden_dim = self.hidden_dim
        cell_type = self.cell_type

        # Initialize parameters for the RNN
        dim_mul = {'lstm': 4, 'rnn': 1}[cell_type]
        self.params["W_xh"] = np.random.randn(
            wordvec_dim, dim_mul * hidden_dim)
        self.params["W_xh"] /= np.sqrt(wordvec_dim)
        self.params["b_xh"] = np.zeros(dim_mul * hidden_dim)

        self.params["W_hh"] = np.random.randn(hidden_dim, dim_mul * hidden_dim)
        self.params["W_hh"] /= np.sqrt(hidden_dim)
        self.params["b_hh"] = np.zeros(dim_mul * hidden_dim)

    def set_parameter(self, name, value):
        """
        Input:
            name: e.g.: "W_xh"
        """
        if name not in self.params:
            raise ValueError("There is no parameter name: {name}.")
        param = self.params[name]
        if value.shape != param.shape:
            raise ValueError(
                "Value's shape  {value.shape} does NOT equal to parameter's shape {param.shape}.")
        param = value

    def step(self, x, hidden_state=None):
        """
        x: should only have one timestep
        """
        W_xh = self.params["W_xh"]
        b_xh = self.params["b_xh"]
        W_hh = self.params["W_hh"]
        b_hh = self.params["b_hh"]

        # W_hy = self.params["W_hy"]
        # b_hy = self.params["b_hy"]

        # update the hidden state
        if hidden_state is not None:
            self.h = hidden_state

        self.h = np.tanh(x.dot(W_xh) + b_xh +
                         self.h.dot(W_hh) + b_hh)

        # compute the output vector
        # y = np.dot(W_hy, self.h) + b_hy
        y = None

        # and return the hidden state after this time step

        return y, self.h

    def forward(self, x, hidden_state=None, transpose=False):
        """
        Inputs:
            - x: Input data for the entire timeseries, of shape (T, N, D).
        """
        if hidden_state is not None:
            self.h = hidden_state

        if transpose:
            x = x.transpose(1, 0, 2)  # (N, T, D) -> (T, N, D)
        T, N, D = x.shape

        output = np.empty((T, N, self.hidden_dim))

        seq_len = T
        for i in range(seq_len):
            y, hn = self.step(x[i], self.h)
            output[i] = hn

        return output, hn

def main():
    # input_size = 10
    # hidden_size = 20

    N, D, W, H = 16, 20, 30, 40
    word_to_idx = {'<NULL>': 0, 'cat': 2, 'dog': 3}
    V = len(word_to_idx)
    T = 13
    wordvec_dim = W  # 30
    input_size = wordvec_dim
    hidden_size = H  # 40

    # N: number of samples
    rnn = RNN(word_to_idx, wordvec_dim=wordvec_dim, hidden_dim=hidden_size)

    # Store init weights
    params = {}
    params["weight_ih_l0"] = rnn.params["W_xh"]
    params["weight_hh_l0"] = rnn.params["W_hh"]
    params["bias_ih_l0"] = rnn.params["b_xh"]
    params["bias_hh_l0"] = rnn.params["b_hh"]

    # Forward
    _input = np.random.randn(5, N, input_size)  # (L, N, H_in)
    h0 = np.random.randn(1, N, hidden_size)  # (S, N, H_out)
    output, hn = rnn.forward(_input, h0[0])  # (N, H_out)

    print(f"hn.shape: {hn.shape}")
    print(f"hn.sum: {hn.sum()}")

    print(f"output.shape: {output.shape}")  # (L, N, H_out)
    print(f"output.sum: {output.sum()}")

    # Compare with PyTorch nn.RNN
    rnn_torch = nn.RNN(input_size=input_size, hidden_size=hidden_size)
    state_dict = rnn_torch.state_dict()
    state_dict.keys()

    # Cast parameters to correct dtype
    for k, v in params.items():
        params[k] = torch.from_numpy(v.astype(np.float32))

    # Load parameters to state_dict
    for k, v in params.items():
        state_dict[k] = params[k].T
    rnn_torch.load_state_dict(state_dict)

    _input = torch.from_numpy(_input.astype(np.float32))  # (L, N, H_in)
    h0 = torch.from_numpy(h0.astype(np.float32))  # (S, N, H_out)
    output, hn = rnn_torch(_input, h0)
    print(f"hn.shape: {hn.shape}")
    print(f"hn.sum: {hn.sum()}")

    print(f"output.shape: {output.shape}")  # (L, N, H_out)
    print(f"output.sum: {output.sum()}")

if __name__ == "__main__":
    main()


text:
import setuptools
from setuptools.extension import Extension
import numpy as np

extensions = [
    Extension(
        'keras_retinanet.utils.compute_overlap',
        ['keras_retinanet/utils/compute_overlap.pyx'],
        include_dirs=[np.get_include()]
    ),
]

setuptools.setup(
    name='keras-retinanet',
    version='0.4.1',
    description='Keras implementation of RetinaNet object detection.',
    url='https://github.com/fizyr/keras-retinanet',
    author='Hans Gaiser',
    author_email='h.gaiser@fizyr.com',
    maintainer='Hans Gaiser',
    maintainer_email='h.gaiser@fizyr.com',
    packages=setuptools.find_packages(),
    install_requires=['keras', 'keras-resnet', 'six', 'scipy', 'cython'],
    entry_points={
        'console_scripts': [
            'retinanet-train=keras_retinanet.bin.train:main',
            'retinanet-evaluate=keras_retinanet.bin.evaluate:main',
            'retinanet-debug=keras_retinanet.bin.debug:main',
            'retinanet-convert-model=keras_retinanet.bin.convert_model:main',
        ],
    },
    ext_modules=extensions,
    setup_requires=["cython>=0.28"]
)


text:
#!/usr/bin/env python
# coding: utf-8

'''Run often used Machine Learning Algorithms.

Classes:

    analysis()

Functions:

    linear_regression
    decision_tree()
    decision_tree_balanced(int)
'''

# used to store and manipulate data
import pandas as pd
import numpy as np

# used to plot data
import seaborn as sns
import matplotlib.pyplot as plt

#https://machinelearningmastery.com/smote-oversampling-for-imbalanced-classification/
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
from imblearn.under_sampling import RandomUnderSampler

#used to create training and testing sets
from sklearn.model_selection import train_test_split

#for creating word clouds
import random
from collections import Counter
from PIL import Image
from wordcloud import WordCloud, ImageColorGenerator

#used to create decision tree models
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier

# used to determine accuracy of models
from sklearn.metrics import accuracy_score
from sklearn import metrics
from sklearn.model_selection import cross_val_score

# files needed for linear regression
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

# for association rules mining
from mlxtend.frequent_patterns import apriori, association_rules, fpgrowth

class analysis():
    ''' This is a class for running machine learning algorithms.

    Attributes:
        x_vals (object): The name of the host where the database is located.
        y_vals (object): Username to access the database.'''

    def __init__(self, x_vals = None, y_vals = None):
        ''' Initialized analysis object

        Attributes:
            x_vals (object): The dataframe columns that will be used for test and training values.
            y_vals (object): The dataframe column that will be used for test and training values.'''

        self.x_values = x_vals
        self.y_values = y_vals

    def linear_regression(self):
        '''runs linear regression algorithm on x and y values.'''

        #Look at the correlation between scores and engagement
        X = self.x_values
        y = self.y_values.values.reshape(-1,1)

        #divide data into training and testing sets
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

        #create the model and run it with the training sets
        model = LinearRegression()
        model.fit(X_train, y_train)

        # evaluate the model
        y_pred = model.predict(X_test)

        # evaluate predictions
        mean_absolute_error = metrics.mean_absolute_error(y_test, y_pred)
        squared_error = np.sqrt(metrics.mean_squared_error(y_test, y_pred))
        coefficient = model.score(X, y)

        #print the results
        print('Mean Absolute Error: %.3f' % mean_absolute_error)
        print('Squared Error: %.3f' % squared_error)
        print('Coefficient of determination: %.3f' % coefficient)

        #plot the results
        for col in X.columns:
            plt.scatter(X[col], y, s=10)

    def decision_tree(self, depth):
        '''runs decision tree algorithm on x and y values.

        Parameters:
        depth(int): depth of decision tree'''

        #select features to compare
        X = self.x_values
        y = self.y_values

        #divide data into testing and training sets
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)

        # Create Decision Tree classifer object
        clf = DecisionTreeClassifier(max_depth= depth)

        # Train Decision Tree Classifer
        clf = clf.fit(X_train,y_train)

        #Predict the response for test dataset
        y_pred = clf.predict(X_test)

        # Model Accuracy, how often is the classifier correct?
        print("Accuracy:",metrics.accuracy_score(y_test, y_pred))

        #print confusion matrix
        unique_label = np.unique([y_test, y_pred])
        print()
        print("Confusion Matrix")
        print()
        cmtx = pd.DataFrame(
            metrics.confusion_matrix(y_test, y_pred, labels=unique_label),
            index=['true:{:}'.format(x) for x in unique_label],
            columns=['pred:{:}'.format(x) for x in unique_label])
        print(cmtx)

    def decision_tree_balanced(self, depth, over_vals, over_nums, under_vals, under_nums):
        '''used for creating a decision tree. Balances unbalanded data first.

        Parameters:
        depth(num): depth of decision tree
        over_vals(list): list containing names of columns to be oversampled
        over_nums(list): list containing number of samples for each value in over_vals
        under_vals(list): list containing names of columns to be undersampled
        under_nums(list): list containing number of samples for each value in under_vals'''

        #select features
        X = self.x_values
        y = self.y_values

        #divide data into testing and training sets
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)

        #over and undersample to even-out imbalanced dataset, pipeline code taken from here:
        #https://machinelearningmastery.com/combine-oversampling-and-undersampling-for-imbalanced-classification/
        over_strategy = dict(zip(over_vals, over_nums))
        under_strategy = dict(zip(under_vals, under_nums))

        over = SMOTE(sampling_strategy = over_strategy)
        under = RandomUnderSampler(sampling_strategy = under_strategy)
        steps = [('o', over), ('u', under)]
        pipeline = Pipeline(steps=steps)

        # transform the dataset
        X_train, y_train = pipeline.fit_resample(X_train, y_train)

        # Create Decision Tree classifer object
        clf = DecisionTreeClassifier(max_depth= 7)

        # Train Decision Tree Classifer
        clf = clf.fit(X_train,y_train)

        #Predict the response for test dataset
        y_pred = clf.predict(X_test)

        # Model Accuracy, how often is the classifier correct?
        print("Accuracy:",metrics.accuracy_score(y_test, y_pred))

        #print confusion matrix
        unique_label = np.unique([y_test, y_pred])
        print()
        print("Confusion Matrix")
        print()
        cmtx = pd.DataFrame(
            metrics.confusion_matrix(y_test, y_pred, labels=unique_label),
            index=['true:{:}'.format(x) for x in unique_label],
            columns=['pred:{:}'.format(x) for x in unique_label])
        print(cmtx)

    def association_apriori(self, data_frame, support = 0.5, length = 3, metric = 'lift', threshold = 2):

        '''used for association rules mining with the Apriori algorithm.

        Parameters:
        data_frame(object): data frame that has been one-hot encoded
        support(float): list containing names of columns to be oversampled
        length(int): list containing number of samples for each value in over_vals
        metric(str): list containing names of columns to be undersampled
        threshold(float): list containing number of samples for each value in under_vals'''

        # use the apriori algorithm to mine association rules. Lower support finds more rules.
        associations = apriori(data_frame, min_support = support, use_colnames=True, max_len=length)

        # get a database of the rules that meet the mininmum threshold you select.
        apriori_df = association_rules(associations, metric=metric, min_threshold=threshold,  support_only=False)

        # change frozen sets into strings
        apriori_df["antecedents"] = apriori_df["antecedents"].apply(lambda x: ', '.join(list(x))).astype("unicode")
        apriori_df["consequents"] = apriori_df["consequents"].apply(lambda x: ', '.join(list(x))).astype("unicode")

        return apriori_df

    def association_fpgrowth(self, data_frame, support = 0.5, metric = 'lift', threshold = 2):

        '''used for association rules mining with the fpGrowth algorithm.

        Parameters:
        data_frame(object): data frame that has been one-hot encoded
        support(float): list containing names of columns to be oversampled
        metric(str): list containing names of columns to be undersampled
        threshold(float): list containing number of samples for each value in under_vals'''

        # use the apriori algorithm to mine association rules. Lower support finds more rules.
        associations = fpgrowth(data_frame, min_support = support, use_colnames=True)

        # get a database of the rules that meet the mininmum threshold you select.
        growth_df = association_rules(associations, metric=metric, min_threshold=threshold,  support_only=False)

        # change frozen sets into strings
        growth_df["antecedents"] = growth_df["antecedents"].apply(lambda x: ', '.join(list(x))).astype("unicode")
        growth_df["consequents"] = growth_df["consequents"].apply(lambda x: ', '.join(list(x))).astype("unicode")

        return growth_df

    def word_cloud(self, dictionary = None, lst= None, image = None, background = 'black', contour = 'pink', name = "cloud"):
        '''used for creating word clouds.

        Parameters:
        lst(object): list object
        image(object): image to use as a mask to shape word cloud
        background(str): string for background color
        contour(str): string for contour color
        '''

        # assign either the list or dictionary to words variable for the word cloud
        words = ['you', 'forgot' 'the' 'word' 'list']

        if list != None:
            words = Counter(lst)

        if dictionary != None:
            words = dictionary

        # create the WordCloud object
        wordcloud = WordCloud(min_word_length =3,
                                  background_color=background,
                                  random_state = 42,
                                  contour_width = 1,
                                  width=800,
                                  height=400,
                                  contour_color = contour)

        # create new WordCloud object with mask if one provided
        if image != None:
            mask = np.array(Image.open(image))
            wordcloud = WordCloud(min_word_length =3,
                                  mask=mask,
                                  background_color=background,
                                  width=mask.shape[1],
                                  height=mask.shape[0],
                                  random_state = 42,
                                  contour_width = 1,
                                  contour_color = contour)

        # generate the word cloud

        cloud =  wordcloud.generate_from_frequencies(words)

        return cloud

if __name__ == "__main__":
    analysis()