text:
# --------------
# Importing header files
import numpy as np
import warnings

warnings.filterwarnings('ignore')

#New record
new_record=[[50,  9,  4,  1,  0,  0, 40,  0]]

#Reading file
data = np.genfromtxt(path, delimiter=",", skip_header=1)

#Code starts here

census = np.concatenate((new_record,data),axis = 0)

print(census.shape)

age = census[:,0]
max_age = np.max(age)
print(max_age)
min_age = np.min(age)
print(min_age)
age_mean = round(np.mean(age),2)
print(age_mean)
age_std = round(np.std(age),2)
print(age_std)

race_0 = census[census[:,2]==0]
race_1 = census[census[:,2]==1]
race_2 = census[census[:,2]==2]
race_3 = census[census[:,2]==3]
race_4 = census[census[:,2]==4]

len_0 = len(race_0)
len_1 = len(race_1)
len_2 = len(race_2)
len_3 = len(race_3)
len_4 = len(race_4)

race_list=[len_0, len_1,len_2, len_3, len_4]

minority_race=race_list.index(min(race_list))
print(minority_race)

senior_citizens = census[census[:,0] > 60]
working_hours_sum = np.sum(senior_citizens[:,6])
senior_citizen_len = len(senior_citizens)
avg_working_hours = round(working_hours_sum/senior_citizen_len,2)
print(avg_working_hours)

high = census[census[:,1] >10]
low = census[census[:,1] <=10]

avg_pay_high = np.mean(high[:,7])
avg_pay_low = np.mean(low[:,7])

print(round(avg_pay_high,2))
print(round(avg_pay_low,2))

max_stars_repo_name: dhawalchaudhari/ga-learner-dst-repo

max_issues_repo_name: dhawalchaudhari/ga-learner-dst-repo

max_forks_repo_name: dhawalchaudhari/ga-learner-dst-repo


text:
import matplotlib.pyplot as plt
import numpy as np
from scale_split import scalesplit

class GridSearch:
  """
  Class that represents the grid search over parameters of ML models.
  """

  def __init__(self) -> None:
    pass

  def compare_losses(self, model_class, X, y, parameter):
    X_sets, y_sets, n_features, n_labels = scalesplit(X, y, test_size=0.2, seed=42)

    model = model_class(n_features=n_features, n_labels=n_labels, **parameter)
    loss = model.fit(X_sets[0], y_sets[0], X_sets[1], y_sets[1], return_loss=True, save_every_epoch=None)
    return loss

  def plot_losses(self, ax, model, parameter, loss, limits=[20,45]):
    ax.plot(
      loss['training_set'], label="Training set loss")
    ax.plot(
      loss['validation_set'], label="Validation set loss")
    if not(limits is None):
      ax.set_yticks(np.arange(limits[0], limits[1], step=5))
      ax.set_ylim(limits)
    ax.set(xlabel=f"p={parameter}\nl={round(loss['validation_set'][-1], 2)}", ylabel=model.__name__)
    ax.label_outer()

  def __call__(self, models, parameters, X, y):
    self.parameters = parameters
    self.models = models

    # Plots the batch loss vs Validation loss
    fig, axs = plt.subplots(len(models), len(parameters), figsize=[10, 5])
    loss = {}
    for m_idx, model in enumerate(models):
      loss[model.__name__] = {}
      for p_idx, parameter in enumerate(parameters):
        p = [p for p in parameter.values()][0]
        loss[model.__name__][p] = self.compare_losses(model, X, y, parameter)

        if len(models) > 1:
          self.plot_losses(axs[m_idx, p_idx], model, p, loss[model.__name__][p])
        else:
          self.plot_losses(axs[p_idx], model, p, loss[model.__name__][p])

ext: py

max_stars_repo_name: eddymarts/Linear-Regression

max_issues_repo_name: eddymarts/Linear-Regression

max_forks_repo_name: eddymarts/Linear-Regression

reason: import numpy


text:
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html

from joblib import load
import numpy as np
import pandas as pd

from app import app

batters = ['Manny Machado', 'Paul Goldschmidt', 'Nick Markakis',
       'Charlie Blackmon', 'Brian Dozier', 'Anthony Rizzo', 'Mookie Betts',
       'Carlos Santana', 'Joey Votto', 'Nolan Arenado', 'Andrew McCutchen',
       'Eric Hosmer', 'Jose Altuve', 'Kyle Seager', 'Xander Bogaerts',
       'Jose Abreu', 'Brett Gardner', 'Edwin Encarnacion', 'Kole Calhoun',
       'Nelson Cruz', 'Francisco Lindor', 'Christian Yelich', 'Freddy Galvis',
       'Evan Longoria', 'Matt Carpenter', 'Ian Kinsler', 'Ender Inciarte',
       'DJ LeMahieu', 'Justin Upton', 'Adam Jones', 'Jean Segura',
       'Mike Trout', 'Kris Bryant', 'Alcides Escobar', 'Bryce Harper',
       'George Springer', 'Albert Pujols', 'Marcell Ozuna', 'Freddie Freeman',
       'Robinson Cano', 'Chris Davis', 'Todd Frazier', 'Nicholas Castellanos',
       'Joe Mauer', 'Kevin Pillar', 'Odubel Herrera', 'Cesar Hernandez',
       'Khris Davis', 'Kendrys Morales', 'Brandon Crawford', 'Elvis Andrus',
       'Lorenzo Cain', 'J.D. Martinez', 'Marcus Semien', 'Andrelton Simmons',
       'Jose Ramirez', 'Starlin Castro', 'Ian Desmond', 'Didi Gregorius',
       'Jason Kipnis', 'Rougned Odor', 'Matt Kemp', 'Carlos Gonzalez',
       'Dee Gordon', 'Jose Bautista', 'Eugenio Suarez', 'Melky Cabrera',
       'Asdrubal Cabrera', 'Curtis Granderson', 'Buster Posey', 'Jay Bruce',
       'Anthony Rendon', 'Mark Trumbo', 'Gregory Polanco', 'Giancarlo Stanton',
       'Ben Zobrist', 'Jason Heyward', 'Shin-Soo Choo', 'Yadier Molina',
       'Salvador Perez', 'Jonathan Schoop', 'Brandon Belt', 'J.T. Realmuto',
       'Adrian Beltre', 'Josh Donaldson', 'Starling Marte', 'Billy Hamilton',
       'Scooter Gennett', 'Dexter Fowler', 'Maikel Franco', 'Daniel Murphy',
       'Mitch Moreland', 'Josh Reddick', 'Alex Gordon', 'Logan Forsythe',
       'Carlos Correa', 'Victor Martinez', 'Yangervis Solarte',
       'Yonder Alonso', 'Justin Turner']
pitchers = ['Justin Verlander', 'Chris Archer', 'Kyle Gibson', 'Rick Porcello',
       'Jose Quintana', 'Corey Kluber', 'Cole Hamels', 'Max Scherzer',
       'Zack Greinke', 'Mike Leake', 'James Shields', 'Mike Fiers',
       'Dallas Keuchel', 'Jake Odorizzi', 'Chris Sale', 'Gerrit Cole',
       'Marco Estrada', 'Gio Gonzalez', 'Masahiro Tanaka', 'Julio Teheran',
       'Tanner Roark', 'Trevor Bauer', 'Carlos Carrasco', 'David Price',
       'Jacob deGrom', 'Carlos Martinez', 'CC Sabathia', 'J.A. Happ',
       'Kevin Gausman', 'Andrew Cashner', 'Ian Kennedy', 'Bartolo Colon',
       'Jon Lester', 'Sonny Gray', 'Felix Hernandez', 'Jason Hammel',
       'Wade Miley', 'Jake Arrieta', 'Kyle Hendricks', 'Jeff Samardzija',
       'Danny Duffy', 'Ervin Santana', 'Hector Santiago', 'Martin Perez',
       'Ivan Nova', 'Patrick Corbin', 'Anibal Sanchez', 'Clayton Kershaw',
       'Johnny Cueto', 'Jeremy Hellickson', 'Yovani Gallardo',
       'Chase Anderson', 'Jordan Zimmermann', 'Stephen Strasburg',
       'Eduardo Rodriguez', 'Robbie Ray', 'Michael Wacha', 'Mike Foltynewicz',
       'Francisco Liriano', 'John Lackey', 'R.A. Dickey', 'Collin McHugh',
       'Carlos Rodon', 'Jimmy Nelson', 'Marcus Stroman', 'Luis Severino',
       'Madison Bumgarner', 'Noah Syndergaard', 'Lance McCullers',
       'Derek Holland', 'Kendall Graveman', 'Drew Pomeranz', 'Doug Fister',
       'Lance Lynn', 'Chris Tillman', 'Taijuan Walker', 'Alex Wood',
       'Matt Harvey', 'Matt Moore', 'Mike Pelfrey', 'Jhoulys Chacin',
       'Jaime Garcia', 'Miguel Gonzalez', 'Aaron Nola', 'Sean Manaea',
       'Josh Tomlin', 'Ubaldo Jimenez', 'James Paxton', 'Michael Pineda',
       'Edinson Volquez', 'Ricky Nolasco', 'Matthew Boyd', 'Charlie Morton',
       'Aaron Sanchez', 'Danny Salazar', 'Jesse Chavez', 'Dan Straily',
       'Erasmo Ramirez', 'Michael Fulmer', 'Clayton Richard']

wind_directions = ['R to L', 'L to R', 'None', 'Out to CF', 'Out to RF', 'Out to LF',
       'In from RF', 'In from LF', 'In from CF', 'Varies', 'Calm']

style = {'padding': '1.5em'}

layout = html.Div([
    dcc.Markdown("""
        ## Create an at bat scenario!
    """),
    html.Div([
        dcc.Markdown('###### Inning'),
        dcc.Slider(
            id='inning',
            min=1,
            max=19,
            step=1,
            value=5,
            marks={n: str(n) for n in range(0,20,2)}
        ),
    ], style=style),

    html.Div([
        dcc.Markdown('###### Wind Speed'),
        dcc.Slider(
            id='wind_speed',
            min=0,
            max=30,
            step=5,
            value=10,
            marks={n: str(n) for n in range(0,31,5)}
        ),
    ], style=style),

    html.Div([
        dcc.Markdown('###### Batter'),
        dcc.Dropdown(
            id='batter',
            options=[{'label': batter, 'value': batter} for batter in batters],
            value=batters[0]
        ),
    ], style=style),

    html.Div([
        dcc.Markdown('###### Pitcher'),
        dcc.Dropdown(
            id='pitcher',
            options=[{'label': pitcher, 'value': pitcher} for pitcher in pitchers],
            value=pitchers[0]
        ),
    ], style=style),

    html.Div([
        dcc.Markdown('###### Wind Direction'),
        dcc.Dropdown(
            id='wind_direction',
            options=[{'label': wd, 'value': wd} for wd in wind_directions],
            value=wind_directions[0]
        ),
    ], style=style),
    html.Div([
        dcc.Markdown('###### Attendance'),
        dcc.Slider(
            id='attendance',
            min=0,
            max=60000,
            step=5000,
            value=15000,
            marks={n: str(n) for n in range(0,61000,5000)}
        )
    ], style=style),

    dcc.Markdown('## Prediction:'),
    html.Div(id='prediction-content', style={'marginBottom': '5em'}),

])

@app.callback(
    Output('prediction-content', 'children'),
    [Input('inning', 'value'),
     Input('wind_speed', 'value'),
     Input('batter', 'value'),
     Input('pitcher', 'value'),
     Input('wind_direction', 'value'),
     Input('attendance', 'value')
    ])

def predict(inning, wind_speed, batter, pitcher, wind_direction, attendance):

    df = pd.DataFrame(
        columns = ['inning', 'pitcher_team_score', 'p_throws', 'stand', 'top',
       'attendance', 'away_team', 'elapsed_time', 'home_team', 'venue_name',
       'weather', 'delay', 'year', 'wind_speed', 'wind_direction',
       'temperature', 'batter', 'pitcher'],
        data = [[inning, 0, 'L', 'L', True, attendance, 'sln', 10, 'chn', 'Wrigley Field',
                 'clear', 0, 2015, wind_speed, wind_direction, 44, batter, pitcher]]
    )

    pipeline = load('model/logreg_pickle.joblib')
    y_pred = pipeline.predict(df)[0]
    #y_pred_log = pipeline.predict(df)
    #y_pred = np.expm1(y_pred_log)[0]

    if y_pred == 'Out':
        message = dcc.Markdown('# Batter is out!')
    else:
        message = dcc.Markdown('# Batter got on base!')
    return message


text:
import pandas as pd
import numpy as np
import seaborn as sns
import datetime as dt
import matplotlib.pyplot as plt
import os
from tqdm import tqdm

def read_csv(file_path):
    return pd.read_csv(file_path, low_memory=False)

def scalable_histogram(data, verbose=False, bins=31):
    hist, binedges = np.histogram(data, bins=bins)
    if verbose:
        plt.plot(binedges[:-1], hist)
        plt.show()
        plt.grid()
    return hist, binedges

def preprocess_on_columns(df, col_name, func, new_col=False, new_col_name=None):
    prep_series = df[col_name].apply(lambda x: func(x))
    if new_col:
        df[new_col_name] = prep_series
    else:
        df[col_name] = prep_series

    return df

def str_to_datetime(str_dt):
    temp = str_dt.split(" ")
    date_str , time_str = temp[0], temp[1]
    temp_date = list(map(float, date_str.split("-")))
    temp_time = list(map(float, time_str.split(":")))
    temp_date = [int(i) for i in temp_date]
    temp_time = [int(i) for i in temp_time]
    year , month, day = temp_date[0], temp_date[1], temp_date[2]
    hour, minute, second = temp_time[0], temp_time[1], temp_time[2]
    return dt.datetime(year, month, day, hour, minute, second)

def time_to_second(dt_i):
    return (dt_i.hour + dt_i.minute/60 + dt_i.second/3600)

def execute_on_dataset(csvs_path, func):
    results = []
    for csv_path in tqdm(csvs_path):
        res = func(csv_path)
        results.append(res)
    return results

def get_csvs_path(dataset_path):
    csvs_name = sorted(os.listdir(dataset_path), key=str.lower)
    # sorting the files will ensure that the cronological order of resutls are saved
    csvs_path = [os.path.join(dataset_path, i) for i in csvs_name]
    return csvs_path

max_stars_repo_name: SajjadPSavoji/CitiBikeNYC

max_issues_repo_name: SajjadPSavoji/CitiBikeNYC

max_forks_repo_name: SajjadPSavoji/CitiBikeNYC


text:
# Copyright (c) 2020 The Plankton Authors.
# All rights reserved.
#
# This source code is derived from UUV Simulator
# (https://github.com/uuvsimulator/uuv_simulator)
# Copyright (c) 2016-2019 The UUV Simulator Authors
# licensed under the Apache license, Version 2.0
# cf. 3rd-party-licenses.txt file in the root directory of this source tree.
#
# 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 rclpy
from uuv_control_msgs.srv import *
from .dp_controller_base import DPControllerBase

class DPPIDControllerBase(DPControllerBase):
    """Abstract class for PID-based controllers. The base
    class method `update_controller` must be overridden
    in other for a controller to work.
    """

    def __init__(self, name, *args, **kwargs):
        #super().__init__(name)
        # Start the super class
        DPControllerBase.__init__(self, name, *args, **kwargs)
        self._logger.info('Initializing: PID controller')
        # Proportional gains
        self._Kp = np.zeros(shape=(6, 6))
        # Derivative gains
        self._Kd = np.zeros(shape=(6, 6))
        # Integral gains
        self._Ki = np.zeros(shape=(6, 6))
        # Integrator component
        self._int = np.zeros(6)
        # Error for the vehicle pose
        self._error_pose = np.zeros(6)

        if self.has_parameter('Kp'):
            # Use 'value' in case int values are specified instead of double
            Kp_diag = self.get_parameter('Kp').value
            if len(Kp_diag) == 6:
                self._Kp = np.diag(Kp_diag)
            else:
                raise RuntimeError('Kp matrix error: 6 coefficients '
                                         'needed')

        self._logger.info('Kp=' + str([self._Kp[i, i] for i in range(6)]))

        if self.has_parameter('Kd'):
            Kd_diag = self.get_parameter('Kd').value
            if len(Kd_diag) == 6:
                self._Kd = np.diag(Kd_diag)
            else:
                raise RuntimeError('Kd matrix error: 6 coefficients '
                                         'needed')

        self._logger.info('Kd=' + str([self._Kd[i, i] for i in range(6)]))

        if self.has_parameter('Ki'):
            Ki_diag = self.get_parameter('Ki').value
            if len(Ki_diag) == 6:
                self._Ki = np.diag(Ki_diag)
            else:
                raise RuntimeError('Ki matrix error: 6 coefficients '
                                         'needed')

        self._logger.info('Ki=' + str([self._Ki[i, i] for i in range(6)]))

        self._services['set_pid_params'] = self.create_service(
            SetPIDParams,
            'set_pid_params',
            self.set_pid_params_callback)
        self._services['get_pid_params'] = self.create_service(
            GetPIDParams,
            'get_pid_params',
            self.get_pid_params_callback)

        self._logger.info('PID controller ready!')

    # =========================================================================
    def _reset_controller(self):
        """Reset reference and and error vectors."""
        super(DPPIDControllerBase, self)._reset_controller()
        self._error_pose = np.zeros(6)
        self._int = np.zeros(6)

    # =========================================================================
    def set_pid_params_callback(self, request, response):
        """Service callback function to set the
        PID's parameters
        """
        kp = request.kp
        kd = request.kd
        ki = request.ki
        if len(kp) != 6 or len(kd) != 6 or len(ki) != 6:
            response.success = False
            return response

        self._Kp = np.diag(kp)
        self._Ki = np.diag(ki)
        self._Kd = np.diag(kd)
        response.success = True
        return response

    # =========================================================================
    def get_pid_params_callback(self, request, response):
        """Service callback function to return
        the PID's parameters
        """
        response.kp = [self._Kp[i, i] for i in range(6)]
        response.kd = [self._Kd[i, i] for i in range(6)]
        response.ki = [self._Ki[i, i] for i in range(6)]

        return response

    # =========================================================================
    def update_pid(self):
        """Return the control signal computed from the PID
        algorithm. To implement a PID-based controller that
        inherits this class, call this function in the
        derived class' `update` method to obtain the control
        vector.

        > *Returns*

        `numpy.array`: Control signal
        """
        if not self.odom_is_init:
            return
        # Update integrator
        self._int += 0.5 * (self.error_pose_euler + self._error_pose) * self._dt
        # Store current pose error
        self._error_pose = self.error_pose_euler
        return np.dot(self._Kp, self.error_pose_euler) \
            + np.dot(self._Kd, self._errors['vel']) \
            + np.dot(self._Ki, self._int)

max_stars_repo_name: oKermorgant/Plankton

max_issues_repo_name: oKermorgant/Plankton

max_forks_repo_name: oKermorgant/Plankton


text:
# -*- coding:utf-8 -*-

from __future__ import division
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import os

class Global_Lists:
    def __init__(self):
        self.vertex_list = []
        self.vertex_queue = []
        self.tree = None

def config():
    """
    Starts the program up with all necessary things. Reads the inputs,
    creates the Singleton objects properly, sets up the heightmap for later,
    makes sure all Vertices in the axiom have the correct neighbor. Could
    need a rework in which the Singletons are unified and not broken as they
    are now.

    Returns
    -------
    variables : Variables object
        Singleton with all numeric values which are not to be changed at runtime
    singleton.global_lists : singleton.global_lists object
        Singleton with the Global Lists which will be altered at runtime
    """
    import json
    from collections import namedtuple
    import os

    import procedural_city_generation
    from procedural_city_generation.additional_stuff.Singleton import Singleton
    path = os.path.dirname(procedural_city_generation.__file__)

    singleton = Singleton("roadmap")

    # Creates Singleton-Variables object from namedtuple

    from procedural_city_generation.roadmap.Vertex import Vertex, set_plotbool
    # Creates Vertex objects from coordinates
    singleton.axiom = [Vertex(np.array([float(x[0]), float(x[1])]))
                       for x in singleton.axiom]
    singleton.border = np.array([singleton.border_x, singleton.border_y])
    set_plotbool(singleton.plot)

    # Finds the longest possible length of a connection between to vertices
    singleton.maxLength = max(singleton.radiallMax, singleton.gridlMax,
                              singleton.organiclMax, singleton.minor_roadlMax, singleton.seedlMax)

    import os

    from procedural_city_generation.roadmap.config_functions.input_image_setup import input_image_setup
    singleton.img, singleton.img2 = input_image_setup(
        singleton.rule_image_name, singleton.density_image_name)

    with open(path+"/temp/"+singleton.output_name+"_densitymap.txt", 'w') as f:
        f.write(singleton.density_image_name.split(".")[0]+"diffused.png")

    from procedural_city_generation.roadmap.config_functions.find_radial_centers import find_radial_centers
    singleton.center = find_radial_centers(singleton)
    singleton.center = [np.array([singleton.border[0]*((x[1]/singleton.img.shape[1])-0.5)*2, singleton.border[1]*(
        ((singleton.img.shape[0]-x[0])/singleton.img.shape[0])-0.5)*2]) for x in singleton.center]

    from procedural_city_generation.roadmap.config_functions.setup_heightmap import setup_heightmap
    setup_heightmap(singleton, path)

    singleton.global_lists = Global_Lists()
    singleton.global_lists.vertex_list.extend(singleton.axiom)
    singleton.global_lists.coordsliste = [
        x.coords for x in singleton.global_lists.vertex_list]

    def setNeighbours(vertex):
        """ Correctly Sets up the neighbors for a vertex from the axiom.

        Parameters
        ----------
        vertex : vertex Object
        """

        d = np.inf
        neighbour = None
        for v in singleton.axiom:
            if v is not vertex:
                dneu = np.linalg.norm(v.coords-vertex.coords)
                if dneu < d:
                    d = dneu
                    neighbour = v
        vertex.neighbours = [neighbour]

    for k in singleton.axiom:
        setNeighbours(k)

    from scipy.spatial import cKDTree
    singleton.global_lists.tree = cKDTree(
        singleton.global_lists.coordsliste, leafsize=160)

    return singleton

reason: import numpy,from scipy


text:
import argparse
import sys
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report
import json
import random
import pickle
import datetime
import numpy as np
from tqdm import tqdm
from utils.LogPrint import Logger
from convhis.ConvHis import ConvHis
from convhis.ConvHisConfig import ConvHisConfig
from agents.AgentRule import AgentRule
from agents.AgentRuleConfig import AgentRuleConfig
from agents.AgentEAR import AgentEAR
from agents.AgentEARConfig import AgentEARConfig
from recommendersystem.recsys import recsys
from recommendersystem.recsysconfig import recsysconfig
from user.UserSim import UserSim
from user.UserSimConfig import UserSimConfig
from dialoguemanager.DialogueManager import DialogueManager
from dialoguemanager.DialogueManagerConfig import DialogueManagerConfig

random.seed(1021)
eps = np.finfo(np.float32).eps.item()

def agent_eval(agent, load_model_type, dm):
    use_gpu = False
    env = dm
    PG_test_data_path = "./data/agent/PG_test_list.pkl"
    with open(PG_test_data_path, "rb") as f:
        PG_test_data_list = pickle.load(f)

    agent.set_env(env)
    if load_model_type == "pretrain":
        print("load pretrain model ...")
        agent.load_model(True)
    elif load_model_type == "PG":
        print("load PG model ...")
        agent.load_model(False)
    else:
        print("no pretrian model...")

    sum_reward = 0.
    sum_turn = 0
    sum_success = 0
    episode_num = 0
    for e_data in tqdm(PG_test_data_list,ncols=0):
        reward, turn, success = agent.PG_eva_one_episode(e_data)
        episode_num += 1
        sum_reward += reward
        sum_turn += turn
        sum_success += success

    average_reward = float(sum_reward)/episode_num
    average_turn = float(sum_turn)/episode_num
    success_rate = float(sum_success)/episode_num

    time_str = datetime.datetime.now().isoformat()
    print("{}: average_reward {:g}, average_turn {:g}, success_rate {:g}"\
            .format(time_str, average_reward, average_turn, success_rate))

user_num = 1801
item_num = 7432
attribute_num = 33
att_num = attribute_num

with open("./data/item_info.json", "r") as f:
    item_info = json.load(f)
new_item_info = {}
for item in item_info:
    new_item_info[int(item)] = set(item_info[item])
item_info = new_item_info

with open("./data/user_info.json", "r") as f:
    user_info = json.load(f)
new_user_info = {}
for user in user_info:
    new_user_info[int(user)] = set(user_info[user])
user_info = new_user_info

adj_index = [[], []]
for user in user_info:
    for item in user_info[user]:
        adj_index[0].append(user)
        adj_index[1].append(item + user_num)
        adj_index[1].append(user)
        adj_index[0].append(item + user_num)
for item in item_info:
    for att in item_info[item]:
        adj_index[0].append(item + user_num)
        adj_index[1].append(att + item_num + user_num)
        adj_index[1].append(item + user_num)
        adj_index[0].append(att + item_num + user_num)
adj_index = torch.tensor(adj_index)

ch = ConvHis(ConvHisConfig())
agent = AgentEAR(AgentEARConfig(), ch)
rec = recsys(recsysconfig(), convhis=ch)
#model_name = "iter60-2020-06-09"
model_name = "iter9-2021-03-27"
rec.load_model(model_name, True)
rec.init_eval(adj_index)
usersim = UserSim(UserSimConfig())
dm = DialogueManager(DialogueManagerConfig(), rec, agent, usersim, ch)
agent_eval(agent, "PG", dm)


text:
import cartopy
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import pandas as pd

import numpy as np
import pydarn
import rad_fov

from shapely.geometry import  MultiLineString, mapping, LineString, Polygon
from descartes.patch import PolygonPatch

def overlay_radar(rads, ax, _to, _from, color="k", zorder=2, marker="o", ms=2, font={"size":7}, north=True):
    times = -1 if north else 1
    for rad in rads:
        hdw = pydarn.read_hdw_file(rad)
        lat, lon, _ = hdw.geographic
        tlat, tlon = lat+3*times, lon+3*times*np.sign(hdw.boresight*-1)
        x, y = _to.transform_point(lon, lat, _from)
        tx, ty = _to.transform_point(tlon, tlat, _from)
        ax.plot(x, y, color=color, zorder=zorder, marker=marker, ms=ms)
        ax.text(tx, ty, rad.upper(), ha="center", va="center", fontdict=font)
    return

def overlay_fov(rads, ax, _to, _from, maxGate=40, rangeLimits=None, beamLimits=None,
            model="IS", fov_dir="front", fovColor=None, fovAlpha=0.2,
            fovObj=None, zorder=2, lineColor="k", lineWidth=0.5, ls="-"):
    """ Overlay radar FoV """
    from numpy import transpose, ones, concatenate, vstack, shape
    for rad in rads:
        hdw = pydarn.read_hdw_file(rad)
        sgate = 0
        egate = hdw.gates if not maxGate else maxGate
        ebeam = hdw.beams
        if beamLimits is not None: sbeam, ebeam = beamLimits[0], beamLimits[1]
        else: sbeam = 0
        rfov = rad_fov.CalcFov(hdw=hdw, ngates=egate)
        x, y = np.zeros_like(rfov.lonFull), np.zeros_like(rfov.latFull)
        for _i in range(rfov.lonFull.shape[0]):
            for _j in range(rfov.lonFull.shape[1]):
                x[_i, _j], y[_i, _j] = _to.transform_point(rfov.lonFull[_i, _j], rfov.latFull[_i, _j], _from)
        contour_x = concatenate((x[sbeam, sgate:egate], x[sbeam:ebeam, egate],
                                 x[ebeam, egate:sgate:-1],
                                 x[ebeam:sbeam:-1, sgate]))
        contour_y = concatenate((y[sbeam, sgate:egate], y[sbeam:ebeam, egate],
                                 y[ebeam, egate:sgate:-1],
                                 y[ebeam:sbeam:-1, sgate]))
        ax.plot(contour_x, contour_y, color=lineColor, zorder=zorder, linewidth=lineWidth, ls=ls)
        if fovColor:
            contour = transpose(vstack((contour_x, contour_y)))
            polygon = Polygon(contour)
            patch = PolygonPatch(polygon, facecolor=fovColor, edgecolor=fovColor, alpha=fovAlpha, zorder=zorder)
            ax.add_patch(patch)
    return

def create_cartopy(prj):
    fig = plt.figure(dpi=120, figsize=(6,6))
    ax = fig.add_subplot(111, projection=prj)
    ax.add_feature(cartopy.feature.OCEAN, zorder=0, alpha=0.1)
    ax.add_feature(cartopy.feature.LAND, zorder=0, edgecolor="black", alpha=0.2, lw=0.3)
    ax.set_global()
    gl = ax.gridlines(linewidth=0.3, draw_labels=True)
    gl.xlabels_top = False
    gl.ylabels_left = False
    return fig, ax

def convert_to_map_lat_lon(xs, ys, _from, _to):
    lat, lon = [], []
    for x, y in zip(xs, ys):
        _lon, _lat = _to.transform_point(x, y, _from)
        lat.append(_lat)
        lon.append(_lon)
    return lat, lon

def create_plots(rads=["cvw","bks","wal","cve","fhe","fhw","kap","sas","pgr"], title="", pngfname="fov.png"):
    geodetic = ccrs.Geodetic()
    #orthographic = ccrs.Orthographic(-120,90)
    orthographic = ccrs.PlateCarree(central_longitude=-95)
    fig, ax = create_cartopy(orthographic)
    for rad, c in zip(rads, 6*["r"]+3*["b"]):
        overlay_fov([rad], ax, orthographic, geodetic, fovColor=c)
        overlay_radar([rad], ax, orthographic, geodetic, north=True)
    ax.set_title(title)
    ax.set_extent([-150, -50, 20, 70])
    ax.text(-0.02, 0.65, "Geographic Coordinates", horizontalalignment="center",
            verticalalignment="center", transform=ax.transAxes, rotation=90)
    fig.savefig(pngfname, bbox_inches="tight")
    return

if __name__ == "__main__":
    #create_dec4_eclipse()
    #create_june10_eclipse()
    create_plots()
    import os
    os.system("rm -rf *.log")
    os.system("rm -rf __pycache__")
    pass

reason: import numpy,from numpy


text:
"""Class for Lyapunov functions of the form V(eta) = eta' P eta."""

from numpy import dot

from .lyapunov_function import LyapunovFunction

class QuadraticLyapunovFunction(LyapunovFunction):
    """Class for Lyapunov functions of the form V(eta) = eta' P eta.

    Let n be the number of states, p be the output vector size.

    Attributes:
    Control task output, output: Output
    Positive definite matrix, P: numpy array (p, p)
    """

    def __init__(self, output, P):
        """Initialize a QuadraticLyapunovFunction object.

        Inputs:
        Control task output, output: Output
        Positive definite matrix, P: numpy array (p, p)
        """

        LyapunovFunction.__init__(self, output)
        self.P = P

    def V(self, x, t):
        eta = self.output.eta(x, t)
        return dot(eta, dot(self.P, eta))

    def grad_V(self, x, t):
        eta = self.output.eta(x, t)
        return 2 * dot(self.P, eta)

max_stars_repo_name: vdorobantu/lyapy

max_issues_repo_name: HaiminClack/lyapy

max_forks_repo_name: HaiminClack/lyapy

reason: from numpy


text:
#!/usr/bin/env python
#reference: https://engineersportal.com/blog/2018/8/14/real-time-graphing-in-python
import serial
import time
import csv
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import matplotlib.ticker as ticker

import signal
import sys

i = 0
size = 30
plt.ion()
fig = plt.figure(figsize=(13,6), clear=True)
ax = fig.add_subplot(111)
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
f = open("temp_data.csv","w",newline='\n')

#reference: https://engineersportal.com/blog/2018/8/14/real-time-graphing-in-python
def live_plotter(x_vec,y1_data,line1,identifier='',pause_time=0.1):
    global i
    if line1==[]:
        line1, = ax.plot(x_vec,y1_data,'-o',alpha=0.8)
        plt.ylabel('Temperature Celcius')
        plt.title('{}'.format(identifier))
        plt.show()

    i=i+1
    ax.set_ylim(min(y1_data)-0.2,max(y1_data)+0.2,auto=True)
    # after the figure, axis, and line are created, we only need to update the y-data
    line1.set_ydata(y1_data)
    # adjust limits if new data goes beyond bounds
    if np.min(y1_data)<=line1.axes.get_ylim()[0] or np.max(y1_data)>=line1.axes.get_ylim()[1]:
        plt.ylim([np.min(y1_data)-np.std(y1_data),np.max(y1_data)+np.std(y1_data)])
    # this pauses the data so the figure/axis can catch up - the amount of pause can be altered above
    plt.pause(pause_time)

    # return line so we can update it again in the next iteration
    return line1

def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

def main():
    signal.signal(signal.SIGINT, signal_handler)
    if (len(sys.argv) < 2):
        print ("Enter COM Port number as: COMx")
        sys.exit(0)

    serial_h = serial.Serial(sys.argv[1], 9600)
    serial_h.flushInput()

    plt.style.use('ggplot')

    x_vec = np.linspace(0,size,size+1)[0:-1]
    y_vec = np.zeros(len(x_vec))
    readings_vec = []

    print("Real Time Temperature Plotter")
    while True:
        try:
            serial_bytes = serial_h.readline()
            print('LOG:{}'.format(serial_bytes))
            if b'START_DATA' in serial_bytes:
                break;
        except KeyboardInterrupt:
            break;

    while True:
        try:
            serial_bytes = serial_h.readline()
            try:
                temperature_C = float(serial_bytes[0:len(serial_bytes)-2].decode("utf-8"))
                print('Current Temp: {} Celcius'.format(temperature_C), end="\r", flush=True)
            except:
                continue

            writer = csv.writer(f,delimiter=",")
            writer.writerow([i,temperature_C])

            y_vec[-1] = temperature_C
            readings_vec = live_plotter(x_vec,y_vec,readings_vec, "Temperature Real-Time Data from BLE Server")
            y_vec = np.append(y_vec[1:],0.0)
        except KeyboardInterrupt:
            break;

if __name__ == "__main__":
    main()

max_stars_repo_path: Wireless Health Thermometer BLE Client/temperaturePlotter.py

max_stars_repo_name: mansetagunj/IoT-Firmware

max_issues_repo_name: mansetagunj/IoT-Firmware

max_forks_repo_name: mansetagunj/IoT-Firmware


text:
import logging
from random import randint

from numpy.core.multiarray import ndarray

logger = logging.getLogger(__name__)

from tactics.ml.agents import A3CAgent

class RandomA3CAgent(A3CAgent):
    def choose_action(self, state: ndarray, reward: float) -> int:
        """Choose and return the next action.
        """
        self.evaluate_prev_action_reward(reward)

        self.prev_action = randint(0, self.action_size - 1)
        self.prev_state = state

        self.ep_steps += 1

        return self.prev_action

max_stars_repo_name: DrInfy/TheHarvester

max_issues_repo_name: DrInfy/TheHarvester

max_forks_repo_name: DrInfy/TheHarvester


text:
import pandas as pd
import numpy as np
import os

def process(fname):
    df = pd.read_csv(fname, sep = '\t')
    i = 0
    for c in df:
        col = df[c].dropna()
        n = len(col)
        x = [1 / n * i for i in range(n)]
        d = pd.DataFrame(data = {'x': x, c: col})
        d.to_csv('{}.{}'.format(fname, i), index = False, sep='\t')
        i += 1

def run():
    for root, subdirs, files in os.walk('thruput'):
        for file in files:
            if not file.endswith(".txt"): continue
            process(os.path.join(root, file))

    os.system("""gnuplot -e "fname='{}'" -e "plot_title='{}'" -e "y_title='{}'" -c thruput.gnu"""
        .format('alex',
                'Throughput of AlexNet under diff. latency SLO',
                'Throughput (#images/s)'))

    os.system("""gnuplot -e "fname='{}'" -e "plot_title='{}'" -e "y_title='{}'" -c thruput.gnu"""
        .format('vgg',
                'Throughput of MobileNet-V2 under diff. latency SLO',
                'Throughput (#images/s)'))

    os.system("""gnuplot -e "fname='{}'" -e "plot_title='{}'" -e "y_title='{}'" -c thruput.gnu"""
        .format('inception',
                'Throughput of TF-coco under diff. latency SLO',
                'Throughput (#images/s)'))

    # Batch
    for root, subdirs, files in os.walk('batch'):
        for file in files:
            if not file.endswith(".txt"): continue
            process(os.path.join(root, file))

    os.system("""gnuplot -e "fname='{}'" -e "plot_title='{}'" -e "y_title='{}'" -c batch.gnu"""
        .format('alex',
                'Batch size of AlexNet under diff. latency SLO',
                'Batch size (#images)'))

    os.system("""gnuplot -e "fname='{}'" -e "plot_title='{}'" -e "y_title='{}'" -c batch.gnu"""
        .format('vgg',
                'Batch size of MobileNet-V2 under diff. latency SLO',
                'Batch size (#images)'))

    os.system("""gnuplot -e "fname='{}'" -e "plot_title='{}'" -e "y_title='{}'" -c batch.gnu"""
        .format('inception',
                'Batch size of TF-coco under diff. latency SLO',
                'Batch size (#images)'))

    # Latency
    os.system("""gnuplot -e "fname='{}'" -e "plot_title='{}'" -e "y_title='{}'" -c latency.gnu"""
        .format('alex',
                'Latency of AlexNet under diff. atch size',
                'Latency (s)'))

    os.system("""gnuplot -e "fname='{}'" -e "plot_title='{}'" -e "y_title='{}'" -c latency.gnu"""
        .format('vgg',
                'Latency of MobileNet-V2 under diff. Batch size',
                'Latency (s)'))
    os.system("""gnuplot -e "fname='{}'" -e "plot_title='{}'" -e "y_title='{}'" -c latency.gnu"""
        .format('inception',
                'Latency of TF-coco under diff. Batch size',
                'Latency (s)'))

run()

max_stars_repo_name: Linestro/happy-FaaS

max_stars_repo_licenses: Intel MIT

max_issues_repo_name: Linestro/happy-FaaS

max_issues_repo_licenses: Intel MIT

max_forks_repo_name: Linestro/happy-FaaS

max_forks_repo_licenses: Intel MIT


text:
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops

import load
import initialize
import tools
import forward
import cost
import predict

def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001, num_epochs = 1500, minibatch_size = 32, print_cost = True):
    ops.reset_default_graph()
    (n_x, m) = X_train.shape
    n_y = Y_train.shape[0]
    costs = []

    X, Y = initialize.create_placeholders(n_x, n_y)

    parameters = initialize.initialize_parameters()

    Z3 = forward.forward_propagation(X, parameters)

    cost = cost.compute_cost(Z3, Y)

    optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)

    init = tf.global_variables_initializer()

    with tf.Session() as sess:
        sess.run(init)

        for epoch in range(num_epochs):
            epoch_cost = 0
            num_minibatches = int(m / minibatch_size)
            minibatches = tools.random_mini_batches(X_train, Y_train, minibatch_size)

            for minibatch in minibatches:
                (minibatch_X, minibatch_Y) = minibatch

                _ , minibatch_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y})

                epoch_cost += minibatch_cost / minibatch_size

            if print_cost == True and epoch % 100 == 0:
                print ("Cost after epoch %i: %f" % (epoch, epoch_cost))
            if print_cost == True and epoch % 5 == 0:
                costs.append(epoch_cost)

        plt.plot(np.squeeze(costs))
        plt.ylabel('cost')
        plt.xlabel('iterations (per fives)')
        plt.title("Learning rate =" + str(learning_rate))
        plt.show()

        parameters = sess.run(parameters)
        print ("Parameters have been trained!")

        correct_prediction = tf.equal(tf.argmax(Z3), tf.argmax(Y))

        accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

        print ("Train Accuracy:", accuracy.eval({X: X_train, Y: Y_train}))
        print ("Test Accuracy:", accuracy.eval({X: X_test, Y: Y_test}))

        return parameters

X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load.load_dataset()

X_train_flatten = X_train_orig.reshape(X_train_orig.shape[0], -1).T
X_test_flatten = X_test_orig.reshape(X_test_orig.shape[0], -1).T

X_train = X_train_flatten/255.
X_test = X_test_flatten/255.

Y_train = tools.convert_to_one_hot(Y_train_orig, 6)
Y_test = tools.convert_to_one_hot(Y_test_orig, 6)

parameters = model(X_train, Y_train, X_test, Y_test)

max_stars_repo_name: RaymondLZhou/deep-neural-networks

max_issues_repo_name: RaymondLZhou/deep-neural-networks

max_forks_repo_name: RaymondLZhou/deep-neural-networks


text:
#! /usr/bin/env python

"""
Utilities to handle random numbers needed by PISA in a consistent and
reproducible manner.

"""

from __future__ import division

from collections.abc import Sequence

import numpy as np

from pisa.utils.log import Levels, logging, set_verbosity

__all__ = ['get_random_state',
           'test_get_random_state']

__author__ = 'J.L. Lanfranchi'

__license__ = '''Copyright (c) 2014-2017, The IceCube Collaboration

 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.'''

def get_random_state(random_state, jumpahead=0):
    """Derive a `numpy.random.RandomState` object (usable to generate random
    numbers and distributions) from a flexible specification..

    Parameters
    ----------
    random_state : None, RandomState, string, int, state vector, or seq of int
        Note for all of the below cases, `jumpahead` is applied _after_ the
        RansomState is initialized using the `random_state` (except for
        `random_state` indicating a truly-random number, in which case
        `jumpahead` is ignored).
        * If instantiated RandomState object is passed, it is used directly
        * If string : must be either 'rand' or 'random'; random state is
          instantiated at random from either /dev/urandom or (if that is not
          present) the clock. This creates an irreproducibly-random number.
          `jumpahead` is ignored.
        * If int or sequence of lenth one: This is used as the `seed` value;
          must be in [0, 2**32).
        * If sequence of two integers: first must be in [0, 32768): 15
          most-significant bits. Second must be in [0, 131072): 17
          least-significant bits.
        * If sequence of three integers: first must be in [0, 4): 2
          most-significant bits. Second must be in [0, 8192): next 13
          (less-significant) bits. Third must be in [0, 131072): 17
          least-significant bits.
        * If a "state vector" (sequence of length five usable by
          `numpy.random.RandomState.set_state`), set the random state using
          this method.

    jumpahead : int >= 0
        Starting with the random state specified by `random_state`, produce
        `jumpahead` random numbers to move this many states forward in the
        random number generator's finite state machine. Note that this is
        ignored if `random_state`="random" since jumping ahead any number of
        states from a truly-random point merely yields another truly-random
        point, but takes additional computational time.

    Returns
    -------
    random_state : numpy.random.RandomState
        Object callable like `numpy.random` (e.g. `random_state.rand((10,10))`),
        but with __exclusively local__ state (whereas `numpy.random` has global
        state).

    """
    if random_state is None:
        new_random_state = np.random

    elif isinstance(random_state, np.random.RandomState):
        new_random_state = random_state

    elif isinstance(random_state, str):
        allowed_strings = ['rand', 'random']
        rs = random_state.lower().strip()
        if rs not in allowed_strings:
            raise ValueError(
                '`random_state`=%s not a valid string. Must be one of %s.'
                %(random_state, allowed_strings)
            )
        new_random_state = np.random.RandomState()
        jumpahead = 0

    elif isinstance(random_state, int):
        new_random_state = np.random.RandomState(seed=random_state)

    elif isinstance(random_state, Sequence):
        new_random_state = np.random.RandomState()
        if all([isinstance(x, int) for x in random_state]):
            if len(random_state) == 1:
                seed = random_state[0]
                assert seed >= 0 and seed < 2**32
            elif len(random_state) == 2:
                b0, b1 = 15, 17
                assert b0 + b1 == 32
                s0, s1 = random_state
                assert s0 >= 0 and s0 < 2**b0
                assert s1 >= 0 and s1 < 2**b1
                seed = (s0 << b1) + s1
            elif len(random_state) == 3:
                b0, b1, b2 = 1, 12, 19
                assert b0 + b1 + b2 == 32
                s0, s1, s2 = random_state
                assert s0 >= 0 and s0 < 2**b0
                assert s1 >= 0 and s1 < 2**b1
                assert s2 >= 0 and s2 < 2**b2
                seed = (s0 << b1+b2) + (s1 << b2) + s2
            else:
                raise ValueError(
                    '`random_state` sequence of int must be length 1-3'
                )
            new_random_state.seed(seed)
        elif len(random_state) == 5:
            new_random_state.set_state(random_state)
        else:
            raise ValueError(
                'Do not know what to do with `random_state` Sequence %s'
                %(random_state,)
            )
        return new_random_state

    else:
        raise TypeError(
            'Unhandled `random_state` of type %s: %s'
            %(type(random_state), random_state)
        )

    if jumpahead > 0:
        new_random_state.rand(jumpahead)

    return new_random_state

def test_get_random_state():
    """Unit tests for get_random_state function"""
    # Instantiate random states in all legal ways
    rstates = {
        0: get_random_state(None),
        1: get_random_state('rand'),
        2: get_random_state('random'),
        3: get_random_state(np.random.RandomState(0)),
        4: get_random_state(0),
        5: get_random_state([0,]),
        6: get_random_state([0, 0]),
        7: get_random_state([0, 0, 0]),
    }
    rstates[8] = get_random_state(rstates[4].get_state())

    # rs 4-8 should be identical
    ref_id, ref = None, None
    for rs_id, rs in rstates.items():
        if rs_id < 3:
            continue
        if ref is None:
            ref_id = rs_id
            ref = rs.rand(1000)
        else:
            test = rs.rand(1000)
            assert np.array_equal(test, ref), f'rs{rs_id} != rs{ref_id}'

    # Already generated 1k, so generating 2k more gets us 3k; pick off last 1k
    ref = rstates[ref_id].rand(2000)[1000:]
    test = get_random_state(random_state=0, jumpahead=2000).rand(1000)
    assert np.array_equal(test, ref), f'jumpahead=1k: rs != rs{ref_id}[2000:3000]'

    # Test stability of random number generator over time; following were
    # retrieved on 2020-03-19 using numpy 1.18.1 via .. ::
    #
    #   np.array2string(
    #       np.random.RandomState(0).rand(100), precision=20, separator=', '
    #   )
    #

    # pylint: disable=bad-whitespace
    ref = np.array(
        [
            0.5488135039273248  , 0.7151893663724195  , 0.6027633760716439  ,
            0.5448831829968969  , 0.4236547993389047  , 0.6458941130666561  ,
            0.4375872112626925  , 0.8917730007820798  , 0.9636627605010293  ,
            0.3834415188257777  , 0.7917250380826646  , 0.5288949197529045  ,
            0.5680445610939323  , 0.925596638292661   , 0.07103605819788694 ,
            0.08712929970154071 , 0.02021839744032572 , 0.832619845547938   ,
            0.7781567509498505  , 0.8700121482468192  , 0.978618342232764   ,
            0.7991585642167236  , 0.46147936225293185 , 0.7805291762864555  ,
            0.11827442586893322 , 0.6399210213275238  , 0.1433532874090464  ,
            0.9446689170495839  , 0.5218483217500717  , 0.4146619399905236  ,
            0.26455561210462697 , 0.7742336894342167  , 0.45615033221654855 ,
            0.5684339488686485  , 0.018789800436355142, 0.6176354970758771  ,
            0.6120957227224214  , 0.6169339968747569  , 0.9437480785146242  ,
            0.6818202991034834  , 0.359507900573786   , 0.43703195379934145 ,
            0.6976311959272649  , 0.06022547162926983 , 0.6667667154456677  ,
            0.6706378696181594  , 0.2103825610738409  , 0.1289262976548533  ,
            0.31542835092418386 , 0.3637107709426226  , 0.5701967704178796  ,
            0.43860151346232035 , 0.9883738380592262  , 0.10204481074802807 ,
            0.2088767560948347  , 0.16130951788499626 , 0.6531083254653984  ,
            0.2532916025397821  , 0.4663107728563063  , 0.24442559200160274 ,
            0.15896958364551972 , 0.11037514116430513 , 0.6563295894652734  ,
            0.1381829513486138  , 0.1965823616800535  , 0.3687251706609641  ,
            0.8209932298479351  , 0.09710127579306127 , 0.8379449074988039  ,
            0.09609840789396307 , 0.9764594650133958  , 0.4686512016477016  ,
            0.9767610881903371  , 0.604845519745046   , 0.7392635793983017  ,
            0.039187792254320675, 0.2828069625764096  , 0.1201965612131689  ,
            0.29614019752214493 , 0.11872771895424405 , 0.317983179393976   ,
            0.41426299451466997 , 0.06414749634878436 , 0.6924721193700198  ,
            0.5666014542065752  , 0.2653894909394454  , 0.5232480534666997  ,
            0.09394051075844168 , 0.5759464955561793  , 0.9292961975762141  ,
            0.31856895245132366 , 0.6674103799636817  , 0.13179786240439217 ,
            0.7163272041185655  , 0.2894060929472011  , 0.18319136200711683 ,
            0.5865129348100832  , 0.020107546187493552, 0.8289400292173631  ,
            0.004695476192547066,
        ]
    )
    test = np.random.RandomState(0).rand(100)
    assert np.array_equal(test, ref), 'random number generator changed!'

    logging.info('<< PASS : test_get_random_state >>')

if __name__ == '__main__':
    set_verbosity(Levels.INFO)
    test_get_random_state()


text:
from __future__ import division
from builtins import object

import numpy as np
from sporco import metric

class TestSet01(object):

    def setup_method(self, method):
        np.random.seed(12345)

    def test_01(self):
        N = 16
        x = np.random.randn(N)
        y = x.copy()
        y[0] = 0
        xe = np.abs(x[0])
        e1 = metric.mae(x, y)
        e2 = metric.mse(x, y)
        assert np.abs(e1 - xe / N) < 1e-12
        assert np.abs(e2 - (xe**2) / N) < 1e-12

    def test_02(self):
        N = 16
        x = np.random.randn(N)
        x /= np.sqrt(np.var(x))
        y = x + 1
        assert np.abs(metric.snr(x, y)) < 1e-8

    def test_03(self):
        N = 16
        x = np.random.randn(N)
        x -= x.min()
        x /= x.max()
        y = x + 1
        assert np.abs(metric.psnr(x, y)) < 1e-8

    def test_04(self):
        N = 16
        x = np.random.randn(N)
        y = x + 1
        assert np.abs(metric.psnr(x, y, rng=1.0)) < 1e-8

    def test_05(self):
        N = 16
        x = np.random.randn(N)
        y = np.random.randn(N)
        assert np.abs(metric.isnr(x, y, y)) < 1e-8

    def test_06(self):
        N = 16
        x = np.random.randn(N)
        x /= np.sqrt(np.var(x))
        n = np.random.randn(N)
        n /= np.sqrt(np.var(n))
        y = x + n
        assert np.abs(metric.bsnr(x, y)) < 1e-8

    def test_07(self):
        N = 16
        x = np.random.randn(N, N)
        y = x + 1
        assert metric.pamse(x, y) > 0.0
        assert np.abs(metric.gmsd(x, y)) < 1e-8

max_stars_repo_name: vishalbelsare/sporco

max_issues_repo_name: wxwoods/sporco

max_forks_repo_name: wxwoods/sporco


text:
import matplotlib.pyplot as plt
import numpy as np
# made by tomita
from readcsv import readcsv

fig = plt.figure(figsize = (4.5,7))
ax = fig.add_subplot(111)
data = "./data/mirai_rs41_20210619_2330.txt"
u,v,h = [],[],[]

readcsv = readcsv(data)
df = readcsv.df
U = readcsv["Ecomp"]
V = readcsv["Ncomp"]
H = readcsv["HeightMSL"]
for i in range(0,len(U),1):
    if i%150 == 0:
        u.append(U[i])
        v.append(V[i])
        h.append(H[i])
zero = np.zeros(len(h))
ax.barbs(zero,h,u,v)
ax.tick_params(labelbottom=False,
               labelleft=True,
               labelright=False,
               labeltop=False)
ax.tick_params(bottom=False,
               left=True,
               right=False,
               top=False)

plt.show()

max_stars_repo_name: RyosukeDTomita/vaisaraPlot

max_issues_repo_name: RyosukeDTomita/vaisaraPlot

max_forks_repo_name: RyosukeDTomita/vaisaraPlot


text:
#!/usr/bin/env python

# file: $CUIBM_DIR/scripts/python/plotVorticity.py
# author: Anush Krishnan (anush@bu.edu), Olivier Mesnard (mesnardo@gwu.edu)
# description: plot the contours of vorticity at every saved timestep

import os
import argparse

import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt

from readData import readSimulationParameters, readGridData, readVelocityData

def read_inputs():
	"""Parses the command-line."""
	# create the parser
	parser = argparse.ArgumentParser(description='plots the vorticity field '
						'at every save point for a given simulation',
						formatter_class=argparse.ArgumentDefaultsHelpFormatter)
	# fill the parser with arguments
	parser.add_argument('-folder', dest='folder', type=str, default='.',
						help='folder of the simulation')
	parser.add_argument("-xmin", type=float, dest="xmin", help="lower x-limit of the plotting region", default=-2.0)
	parser.add_argument("-xmax", type=float, dest="xmax", help="upper x-limit of the plotting region", default=4.0)
	parser.add_argument("-ymin", type=float, dest="ymin", help="lower y-limit of the plotting region", default=-3.0)
	parser.add_argument("-ymax", type=float, dest="ymax", help="upper y-limit of the plotting region", default=3.0)
	parser.add_argument('-vortlim', dest='vortlim', type=float, default=3.0,
						help='vorticity cutoff on the plot')
	parser.add_argument('-numlevels', dest='numlevels', type=int, default=16,
						help='number of vortex contour line levels (choose an even number)')
	return parser.parse_args()

def main():
	"""Plots the contour of vorticity at every time saved."""
	# parse the command-line
	args = read_inputs()

	folder = args.folder	# name of the folder

	# read the parameters of the simulation
	nt, start_step, nsave, dt = readSimulationParameters(folder)

	# calculate the mesh characteristics
	nx, ny, dx, dy, _, yu, xv, _ = readGridData(folder)

	# calculate appropriate array boundaries
	i_start = np.where(xv >= args.xmin)[0][0]
	i_end = np.where(xv <= args.xmax)[0][-1]
	j_start = np.where(yu >= args.ymin)[0][0]
	j_end = np.where(yu <= args.ymax)[0][-1]

	y = np.zeros(j_end-j_start)
	x = np.zeros(i_end-i_start)
	x[:] = 0.5*(xv[i_start:i_end] + xv[i_start+1:i_end+1])
	y[:] = 0.5*(yu[j_start:j_end] + yu[j_start+1:j_end+1])
	X, Y = np.meshgrid(x, y)

	Omg = np.zeros((j_end-j_start, i_end-i_start))

	# time-loop
	for ite in xrange(start_step+nsave, nt+1, nsave):
		# read the velocity data at the given time-step
		u, v = readVelocityData(folder, ite, nx, ny, dx, dy)
		if u is None or v is None:
			break

		# calculate the vorticity
		for j in xrange(j_start, j_end):
			Dy = 0.5 * (dy[j] + dy[j+1])
			for i in xrange(i_start, i_end):
				Dx = 0.5 * (dx[i] + dx[i+1])
				Omg[j-j_start, i-i_start] = (v[j*nx+i+1] - v[j*nx+i]) / Dx \
					  - (u[(j+1)*(nx-1)+i] - u[j*(nx-1)+i]) / Dy

		CS = plt.contourf(X, Y, Omg, levels=np.linspace(-args.vortlim, args.vortlim, args.numlevels))
		plt.title("Vorticity @ time = {0}".format(ite*dt))
		plt.colorbar(CS)
		plt.axis([xv[i_start], xv[i_end], yu[j_start], yu[j_end]])
		plt.gca().set_aspect('equal', adjustable='box')
		plt.savefig('%s/o%07d.png' % (folder, ite/nsave))
		plt.clf()
		print "Saved figure {0}".format(ite)

	print 'DONE!'

if __name__ == '__main__':
	main()

max_stars_repo_name: Niemeyer-Research-Group/cuIBM

max_issues_repo_name: Niemeyer-Research-Group/cuIBM-FSI

max_forks_repo_name: Niemeyer-Research-Group/cuIBM-FSI


text:
"""
The MIT License (MIT)

Copyright (c) 2018 Marvin Teichmann
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import sys

import numpy as np
import scipy as scp

import logging

import quaternion as tq
import torch

from localseg.data_generators import posenet_maths_v5 as pmath

logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
                    level=logging.INFO,
                    stream=sys.stdout)

myq = np.array(
    [[-1.8645e-01, -2.0298e-01, -7.1868e-01, -3.4022e-01],
     [-2.1770e-02, -2.0337e-02, -5.3460e-01, 3.9141e-03],
     [-3.4575e-01, -3.3782e-02, -6.7370e-01, -2.5618e-01],
     [-1.3259e-01, 5.2945e-02, -3.3385e-01, -3.4048e-01],
     [-1.5684e-01, 2.6417e-02, -4.1580e-01, -1.2027e-02],
     [-3.9569e-01, 1.0809e-01, -8.6902e-01, -2.7603e-01],
     [-2.0261e-01, -4.2677e-02, -5.6284e-01, -1.1454e-01],
     [-3.3343e-01, -5.4280e-02, -6.5919e-01, -1.6623e-01]])

def rand_q(bs=80):
    return torch.rand([bs, 4])

def test_normalize():

    normalized = tq.normalize(torch.Tensor(myq))

    for d in range(myq.shape[0]):
        assert torch.all(normalized[d] == tq.normalize(torch.Tensor(myq[d])))

    for d in range(myq.shape[0]):
        iq = pmath.normalize_quaternion(myq[d])
        mq = normalized[d].numpy()
        assert np.all(np.abs(mq - iq) < 1e-7), normalized[d] - iq

    random_q = rand_q()
    normalized_rand = tq.normalize(random_q)

    for d in range(random_q.shape[0]):
        iq = pmath.normalize_quaternion(random_q[d].numpy())
        mq = normalized_rand[d].numpy()
        assert np.all(np.abs(mq - iq) < 1e-6), mq - iq

def test_multiply():

    # pmath.multiply(q0.numpy(), q1.numpy())

    normalized = tq.normalize(torch.Tensor(myq))
    normalized2 = tq.normalize(rand_q(8))
    multiplied = tq.multiply(normalized, normalized2)

    for d in range(normalized.shape[0]):
        mul0 = tq.multiply(normalized[d], normalized2[d])
        assert torch.all(multiplied[d] == mul0)

    for d in range(normalized.shape[0]):
        mul0 = pmath.quaternion_multiply(
            normalized[d].numpy(), normalized2[d].numpy())
        assert np.all(multiplied[d].numpy() == mul0)

def test_conjugate():

    # pmath.multiply(q0.numpy(), q1.numpy())

    normalized = tq.normalize(torch.Tensor(rand_q(8)))
    con = tq.conjugate(normalized)

    for d in range(normalized.shape[0]):
        con0 = tq.conjugate(normalized[d])
        assert torch.all(con[d] == con0)

    for d in range(normalized.shape[0]):
        con0 = pmath.quaternion_conjugate(
            normalized[d].numpy())
        assert np.all(con[d].numpy() == con0)

def test_angle():

    # pmath.multiply(q0.numpy(), q1.numpy())

    normalized = tq.normalize(rand_q(8))

    q0 = normalized[0]

    for d in range(normalized.shape[0]):
        q1 = normalized[d]
        ang1 = tq.min_angle(q0, q1)
        ang2 = tq.min_angle(q1, q0)

        assert torch.abs(ang1 - ang2) < 1e-6, ang1 - ang2

    normalized2 = tq.normalize(torch.Tensor(myq))

    angles = tq.min_angle(normalized, normalized2)

    for d in range(normalized.shape[0]):
        ang0 = tq.min_angle(normalized[d], normalized2[d])
        assert torch.abs(angles[d] - ang0.double()) < 1e-7, \
            angles[d] - ang0.double()

    for d in range(normalized.shape[0]):
        ang0 = pmath.angle_between_quaternions(
            normalized[d].numpy(), normalized2[d].numpy())
        assert np.all(np.abs(angles[d].numpy() - ang0) < 1e-6), \
            angles[d].numpy() - ang0

def test_rotation():

    # pmath.multiply(q0.numpy(), q1.numpy())

    normalized = tq.normalize(torch.Tensor(rand_q(8)))
    con0 = tq.get_rotation(normalized[0])

    con = tq.get_rotation(normalized)

    for d in range(normalized.shape[0]):
        con0 = tq.get_rotation(normalized[d])
        assert torch.all(con[d] == con0)

    for d in range(normalized.shape[0]):
        con0 = pmath.quaternion_to_rotation_matrix(
            normalized[d].numpy())
        assert np.abs(np.max(con[d].numpy() - con0)) < 1e-7, \
            np.max(con[d].numpy() - con0)

def test_convert():

    # pmath.multiply(q0.numpy(), q1.numpy())

    normalized = tq.normalize(torch.Tensor(rand_q(8)))
    translation = torch.rand([8, 3])

    rot0, trans0 = tq.posenetQT_to_opensfmRT(normalized[0], translation[0])
    rotations, translations = tq.posenetQT_to_opensfmRT(
        normalized, translation)

    for d in range(normalized.shape[0]):
        rot0, trans0 = tq.posenetQT_to_opensfmRT(
            normalized[d], translation[d])
        assert torch.all(rotations[d] == rot0),\
            torch.max(rotations[d] - rot0)
        assert torch.all(translations[d] == trans0),\
            torch.max(translations[d] - trans0)

    for d in range(normalized.shape[0]):
        rot0, trans0 = pmath.obtain_opensfmRT_from_posenetQT(
            normalized[d].numpy(), translation[d].numpy())
        rot0 = torch.Tensor(rot0)
        trans0 = torch.Tensor(trans0)
        assert torch.abs(torch.max(rotations[d] - rot0)) < 1e-6,\
            torch.max(rotations[d] - rot0)
        assert torch.abs(torch.max(translations[d] - trans0)) < 1e-6,\
            torch.max(translations[d] - trans0)

if __name__ == '__main__':
    test_convert()
    test_rotation()
    test_angle()
    test_conjugate()
    test_multiply()
    test_normalize()

max_stars_repo_name: MarvinTeichmann/TorchLab

max_issues_repo_name: MarvinTeichmann/TorchLab

max_forks_repo_name: MarvinTeichmann/TorchLab

reason: import numpy,import scipy


text:
import tensorflow as tf
import numpy as np

from agent import Agent

class Model(Agent):
  def __init__(self, config, env, sess, writer, name='haggle', trainable=True):
    super(Model, self).__init__()
    self.config = {
      'pre': [],
      'lstm': 128,
      'value_scale': 0.5,
      'lr': 0.001,
      'grad_clip': 0.5,
      'ppo': 0.1,
      'ppo_epochs': 10,
    }

    self.max_rounds = env.max_rounds

    self.config.update(config)

    self.original_name = name
    self.version = 0

    self.name = name

    self.observation_space = env.observation_space
    self.action_space = env.action_space
    self.context_space = env.context_space
    self.reward_space = env.reward_space

    self.empty_reward = np.zeros(self.reward_space, dtype='float32')

    # Used for getting offers by index
    self.env = env

    self.scope = tf.VariableScope(reuse=False, name=name)
    self.sess = sess
    self.writer = writer
    self.writer_step = 0

    with tf.variable_scope(self.scope):
      self.input = tf.placeholder(tf.int32,
          shape=(None, self.observation_space,), name='input')
      self.context = tf.placeholder(tf.int32,
          shape=(None, self.context_space,), name='input_context')

      # Init layers

      self.layers = {
        'embedding': tf.get_variable('embedding', dtype=tf.float32,
             initializer=tf.initializers.random_normal,
             shape=(self.action_space, self.config['lstm'])),
        'pre': [],
        'action': tf.layers.Dense(self.action_space, name='action'),
        'value': tf.layers.Dense(self.reward_space, name='value'),
        'context': tf.layers.Dense(self.config['lstm'] * 2,
            activation=tf.nn.relu, name='context'),
        'lstm': tf.contrib.rnn.LSTMBlockCell(name='lstm',
                                             num_units=self.config['lstm']),
      }

      self.build_context = self.layers['context'](
          tf.cast(self.context, dtype=tf.float32))

      for i, width in enumerate(self.config['pre']):
        pre = tf.layers.Dense(width, activation=tf.nn.relu,
                              name='preprocess_{}'.format(i))
        self.layers['pre'].append(pre)

      state_size = self.layers['lstm'].state_size
      self.rnn_state = tf.placeholder(tf.float32,
          shape=(None, state_size.c + state_size.h), name='rnn_state')

      state = tf.contrib.rnn.LSTMStateTuple(c=self.rnn_state[:, :state_size.c],
                                            h=self.rnn_state[:, state_size.c:])

      new_state, action, action_probs, value = \
          self._network(state, self.input)

      self.action = action
      self.action_probs = action_probs
      self.value = value
      self.new_state = tf.concat([ new_state.c, new_state.h ], axis=-1, \
          name='new_state')

      # Losses
      if trainable:
        self._losses()

      # Weight loading
      self.trainable_variables = self.scope.trainable_variables()

      self.weight_placeholders = {}
      self.load_ops = []
      for var in self.trainable_variables:
        name = var.name.split(':', 1)[0]
        name = name.split('/', 1)[1]
        placeholder = tf.placeholder(var.dtype,
            shape=var.shape,
            name='{}/placeholder'.format(name))
        self.weight_placeholders[name] = placeholder
        self.load_ops.append(var.assign(placeholder))

  def _network(self, state, obs, sample=True):
    # Get offer mask
    available_actions, offer = tf.split(obs, [
      self.action_space, 1,
    ], axis=1)

    available_actions = tf.cast(available_actions, dtype=tf.float32)

    # Translate proposed offer to embedding
    offer = tf.squeeze(offer, axis=-1, name='offer_index')
    offer = tf.gather(self.layers['embedding'], offer, name='offer')

    x = offer

    for pre in self.layers['pre']:
      x = pre(x)

    # Feed embedding into LSTM
    x, state = self.layers['lstm'](x, state)

    # Transform output to probs through same embedding, applying offer mask
    raw_action = tf.matmul(x, self.layers['embedding'], transpose_b=True)
    raw_action *= available_actions
    raw_action += (1.0 - available_actions) * -1e23

    action_probs = tf.nn.softmax(raw_action, name='action_probs')

    value = x
    value = self.layers['value'](value)

    if not sample:
      return state, action_probs, value

    action_dist = tf.distributions.Categorical(probs=action_probs)
    action = action_dist.sample()

    return state, action, action_probs, value

  def _losses(self):
    self.entropy_coeff = tf.placeholder(tf.float32, shape=(),
        name='entropy_coeff')

    input_shape = (None, self.max_rounds,)
    self.train_input = tf.placeholder(tf.int32,
        shape=input_shape + (self.observation_space,), name='train_input')
    self.train_mask = tf.placeholder(tf.bool, shape=input_shape,
        name='train_mask')
    self.true_value = tf.placeholder(tf.float32,
        shape=input_shape + (self.reward_space,), name='true_value')
    self.past_value = tf.placeholder(tf.float32,
        shape=input_shape + (self.reward_space,), name='past_value')
    self.past_prob = tf.placeholder(tf.float32,
        shape=input_shape, name='past_prob')
    self.selected_action = tf.placeholder(tf.int32,
        shape=input_shape, name='selected_action')

    state_size = self.layers['lstm'].state_size
    state = tf.contrib.rnn.LSTMStateTuple(
        c=self.build_context[:, :state_size.c],
        h=self.build_context[:, state_size.c:])

    entropy = []
    value_loss = []
    policy_loss = []
    values = []

    for i in range(self.max_rounds):
      with tf.name_scope('train_step_{}'.format(i)):
        obs = self.train_input[:, i]
        true_value = self.true_value[:, i]
        past_value = self.past_value[:, i]
        past_prob = self.past_prob[:, i]
        selected_action = self.selected_action[:, i]

        state, action_probs, value = self._network(state, obs, sample=False)

        round_entropy = \
            -tf.reduce_sum(action_probs * tf.log(action_probs + 1e-20),
                           axis=-1)

        online_advantage = true_value - value
        round_value_loss = tf.reduce_sum(online_advantage ** 2 / 2.0, axis=-1)

        action_one_hot = tf.one_hot(selected_action,
            depth=action_probs.shape[-1],
            dtype='float32',
            name='action_one_hot')
        current_prob = tf.reduce_sum(
            action_one_hot * action_probs,
            axis=-1,
            name='current_prob')

        prob_ratio = current_prob / (past_prob + 1e-12)
        ppo_epsilon = self.config['ppo']
        clipped_ratio = tf.clip_by_value(prob_ratio, 1.0 - ppo_epsilon,
            1.0 + ppo_epsilon, name='clipped_ratio')

        offline_advantage = tf.reduce_sum(true_value - past_value, axis=-1)
        round_policy_loss = -tf.minimum(
            prob_ratio * offline_advantage,
            clipped_ratio * offline_advantage)

        entropy.append(round_entropy)
        value_loss.append(round_value_loss)
        policy_loss.append(round_policy_loss)
        values.append(tf.reduce_sum(value, axis=-1))

    mask = tf.cast(self.train_mask, tf.float32, name='float_mask')

    mean_mask = mask / tf.expand_dims(tf.reduce_sum(mask, axis=-1) + 1e-12, \
        axis=-1)

    entropy = tf.stack(entropy, axis=-1, name='stacked_entropy')
    value_loss = tf.stack(value_loss, axis=-1, name='stacked_value_loss')
    policy_loss = tf.stack(policy_loss, axis=-1, name='stacked_policy_loss')
    values = tf.stack(values, axis=-1, name='stacked_values')

    self.entropy = tf.reduce_mean(
        tf.reduce_sum(entropy * mean_mask, axis=-1),
        axis=-1, name='entropy')
    self.value_loss = tf.reduce_mean(
        tf.reduce_sum(value_loss * mean_mask, axis=-1),
        axis=-1, name='value_loss')
    self.policy_loss = tf.reduce_mean(
        tf.reduce_sum(policy_loss * mean_mask, axis=-1),
        axis=-1, name='policy_loss')
    self.mean_value = tf.reduce_mean(
        tf.reduce_sum(values * mean_mask, axis=-1),
        axis=-1, name='mean_value')

    optimizer = tf.train.AdamOptimizer(self.config['lr'])

    self.loss = self.policy_loss + \
        self.value_loss * self.config['value_scale'] - \
        self.entropy * self.entropy_coeff

    variables = tf.trainable_variables()
    grads = tf.gradients(self.loss, variables)
    grads, grad_norm = tf.clip_by_global_norm(grads, self.config['grad_clip'])
    grads = list(zip(grads, variables))
    self.grad_norm = grad_norm
    self.train = optimizer.apply_gradients(grads_and_vars=grads)

  def save_weights(self, sess):
    values = sess.run(self.trainable_variables)
    out = {}
    for var, value in zip(self.trainable_variables, values):
      name = var.name.split(':', 1)[0]
      name = name.split('/', 1)[1]
      out[name] = value
    return out

  def load_weights(self, weights):
    feed_dict = {}
    for name, value in weights.items():
      if name in self.weight_placeholders:
        feed_dict[self.weight_placeholders[name]] = value
    return feed_dict, self.load_ops

  def set_version(self, version):
    self.version = version
    self.name = '{}_v{}'.format(self.original_name, self.version)

  def fill_feed_dict(self, out, obs, state=None):
    if state is None:
      state = [ self.initial_state ]

    out[self.input] = obs
    out[self.rnn_state] = state
    return out

  def build_initial_state(self, context):
    feed_dict = { self.context: [ context ] }
    return self.sess.run(self.build_context, feed_dict=feed_dict)[0]

  def step(self, obs, state):
    feed_dict = {}
    self.fill_feed_dict(feed_dict, [ obs ], [ state ])
    tensors = [ self.action, self.new_state ]

    action, next_state = self.sess.run(tensors, feed_dict=feed_dict)
    return self.env.get_offer(action[0]), next_state[0]

  def multi_step(self, env_states, model_states):
    feed_dict = {
      self.input: env_states,
      self.rnn_state: model_states,
    }
    tensors = [ self.action, self.action_probs, self.new_state, self.value ]
    out = self.sess.run(tensors, feed_dict=feed_dict)

    actions, action_probs, next_model_states, values = out
    action_probs = [
        probs[action] for action, probs in zip(actions, action_probs) ]

    return actions, next_model_states, values, action_probs

  def game(self, env_list):
    log = [ {
      'env_states': [],
      'env_context': None,
      'actions': [],
      'action_probs': [],
      'values': [],
      'rewards': [],
      'dones': [],
      'statuses': [],
    } for i in range(len(env_list)) ]

    env_states = [ env.reset() for env in env_list ]
    env_contexts = [ env.get_context('self') for env in env_list ]

    model_states = self.sess.run(self.build_context, feed_dict={
      self.context: env_contexts,
    })

    for context, entry in zip(env_contexts, log):
      entry['env_context'] = context

    steps = 0
    while True:
      actions, next_model_states, values, action_probs = \
          self.multi_step(env_states, model_states)

      next_env_states = []
      rewards = []
      dones = []
      statuses = []
      for env, env_state, action in zip(env_list, env_states, actions):
        if not env.done:
          next_env_state, reward, done, _ = env.step(self.env.get_offer(action))
        else:
          next_env_state, reward, done = \
              env_state, np.copy(self.empty_reward), True

        next_env_states.append(next_env_state)
        rewards.append(reward)
        dones.append(done)
        statuses.append(env.status)

      steps += 1

      zipped = zip(env_states, rewards, dones, statuses, actions,
          action_probs, values)
      for i, t in enumerate(zipped):
        env_state, reward, done, status, action, action_prob, \
            value = t

        entry = log[i]
        entry['env_states'].append(env_state)
        entry['rewards'].append(reward)
        entry['dones'].append(done)
        entry['statuses'].append(status)
        entry['actions'].append(action)
        entry['action_probs'].append(action_prob)
        entry['values'].append(value)

      # Update states
      env_states = next_env_states
      model_states = next_model_states

      has_pending = False in dones
      if not has_pending:
        # All completed
        break

    return log

  def explore(self, env_list, game_count=1024, reflect_every=256, game_off=0, \
              entropy_schedule=None):
    finished_games = 0
    while finished_games < game_count:
      reflect_target = min(game_count - finished_games, reflect_every)

      games = self.collect(env_list, reflect_target)
      finished_games += reflect_target

      if entropy_schedule is None:
        entropy_schedule = lambda game_step: self.config['entropy']

      self.reflect(games,
          entropy_coeff=entropy_schedule(game_off + finished_games))

  def collect(self, env_list, count):
    res = {
      'masks': [],
      'env_contexts': [],
      'env_states': [],
      'actions': [],
      'action_probs': [],
      'values': [],
      'rewards': [],
      'acceptance': [],
      'steps_per_game': [],
    }

    if count % len(env_list) != 0:
      raise Exception('Number of games is not divisible by concurrency')

    def pad(l, val):
      to_pad = self.max_rounds - len(l)
      if to_pad == 0:
        return l
      padding = [ val ] * to_pad
      res = np.concatenate([ l, padding ], axis=0)
      return res

    empty_obs = [ 0.0 ] * self.observation_space

    for game_index in range(count // len(env_list)):
      log = self.game(env_list)

      global_max_steps = len(log[0]['dones'])
      for entry in log:
        dones = entry['dones']
        max_steps = None
        for i in range(global_max_steps):
          if dones[i]:
            max_steps = i + 1
            break

        rewards = self.estimate_rewards(entry['rewards'], entry['dones'])

        res['env_states'].append(pad(entry['env_states'], empty_obs))
        res['actions'].append(pad(entry['actions'], 0))
        res['action_probs'].append(pad(entry['action_probs'], 0.0))
        res['values'].append(pad(entry['values'], np.copy(self.empty_reward)))
        res['rewards'].append(pad(rewards, np.copy(self.empty_reward)))
        res['masks'].append(pad([ True for e in entry['dones'] ], False))

        res['env_contexts'].append(entry['env_context'])

        # Averaged stats
        statuses = entry['statuses']
        res['acceptance'].append(statuses[max_steps - 1] is 'accepted')
        res['steps_per_game'].append(max_steps)

    res['steps_per_game'] = np.mean(res['steps_per_game'])
    res['acceptance'] = np.mean(res['acceptance'])

    return res

  def estimate_rewards(self, rewards, dones, gamma=0.99):
    estimates = np.zeros((len(rewards), self.reward_space,), dtype='float32')
    future = np.copy(self.empty_reward)

    for i, reward in reversed(list(enumerate(rewards))):
      if dones[i]:
        future *= 0.0
      future *= gamma
      estimates[i] = reward + future
      future += reward

    return estimates

  def reflect(self, games, entropy_coeff):
    feed_dict = {
      self.context: games['env_contexts'],
      self.train_input: games['env_states'],
      self.train_mask: games['masks'],
      self.selected_action: games['actions'],
      self.true_value: games['rewards'],
      self.past_value: games['values'],
      self.past_prob: games['action_probs'],
      self.entropy_coeff: entropy_coeff,
    }

    tensors = [
        self.train, self.loss, self.entropy, self.value_loss, self.policy_loss,
        self.mean_value, self.grad_norm,
    ]

    # TODO(indutny): average over metrics?
    for i in range(self.config['ppo_epochs']):
      _, loss, entropy, value_loss, policy_loss, value, grad_norm = \
          self.sess.run(tensors, feed_dict=feed_dict)

    global_rewards = []
    for rewards, masks in zip(games['rewards'], games['masks']):
      for reward, mask in zip(rewards, masks):
        if mask:
          global_rewards.append(reward)

    metrics = {
      'grad_norm': grad_norm,
      'loss': loss,
      'entropy': entropy,
      'entropy_coeff': entropy_coeff,
      'value_loss': value_loss,
      'policy_loss': policy_loss,
      'steps_per_game': games['steps_per_game'],
      'acceptance': games['acceptance'],
      'reward': np.mean(np.sum(global_rewards, axis=-1)),
      'value': value,
    }
    self.log_summary(metrics)

  def log_summary(self, metrics):
    summary = tf.Summary()
    for key in metrics:
      value = metrics[key]
      summary.value.add(tag='train/{}'.format(key), simple_value=value)
    self.writer.add_summary(summary, self.writer_step)
    self.writer.flush()
    self.writer_step += 1

max_stars_repo_licenses: Unlicense MIT

max_issues_repo_licenses: Unlicense MIT

max_forks_repo_licenses: Unlicense MIT


text:
import logging
from typing import Tuple

import numpy as np

import gym

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

ACTION_MAP = {0: (0, 1), 1: (1, 0), 2: (0, -1), 3: (-1, 0)}
OBSTACLE_CHANNEL = 0
GOAL_CHANNEL = 1
PLAYER_CHANNEL = 2

class GridWorldEnv(gym.Env):

    """Class implementing a square gridworld with 4-d discrete action space.

    The obs is modeled as an 3-channel array with separate channels for
    obstacles (0), goal (1), and player (2).  The env is instantiated by
    passing a size x size x 3 numpy array with 1 indicating presence of the
    object, and 0 otherwise.
    """

    def __init__(self,
                 grid: np.ndarray,
                 max_episode_steps: int = None,
                 sparse_rewards: bool = False,
                 obs_type: str = "scalar"):

        assert obs_type in ["rgb", "grayscale", "scalar", "index"]
        self.obs_type = obs_type

        self.size = grid.shape[1]
        self.max_episode_steps = max_episode_steps if max_episode_steps is not None \
            else 4 * (self.size - 1)
        self.sparse_rewards = sparse_rewards

        self.episode_steps = None
        self.cumulative_reward = None

        self.start = tuple([x[0] for x in np.where(grid[:, :, PLAYER_CHANNEL])])
        self.goal = tuple([x[0] for x in np.where(grid[:, :, GOAL_CHANNEL])])
        self.initial_grid = grid.copy()

        if self.obs_type == "index":
            self.obs_shape = [1]
            high = self.size * self.size - 1
            dtype = np.int64
        if self.obs_type == "scalar":
            self.obs_shape = [2]
            high = self.size
            dtype = np.int64
        if self.obs_type == "rgb":
            self.obs_shape = list(self.initial_grid.shape)
            high = 1.
            dtype = np.float64
        if self.obs_type == "grayscale":
            self.obs_shape = list(self.initial_grid.shape)
            self.obs_shape[-1] = 1
            high = 1.
            dtype = np.float64
        self.obs_shape = tuple(self.obs_shape)

        self.observation_space = gym.spaces.Box(
            low=0, high=high, shape=self.obs_shape, dtype=dtype)

        self.action_space = gym.spaces.Discrete(4)

    def reset(self) -> np.ndarray:
        self.episode_steps = 0
        self.cumulative_reward = 0.
        self.player = list(self.start)
        self.grid = self.initial_grid.copy()
        return self.get_obs()

    def get_obs(self) -> np.ndarray:
        obs = self.grid.copy()
        if self.obs_type == "index":
            obs = np.where(obs[:, :, PLAYER_CHANNEL].squeeze())
            obs = np.array([obs[0]*self.size + obs[1]], dtype=np.int64).reshape(1)
        if self.obs_type == "scalar":
            obs = np.where(obs[:, :, PLAYER_CHANNEL].squeeze())
            obs = np.array([obs[0], obs[1]], dtype=np.int64).reshape(2)
        if self.obs_type == "grayscale":
            obs[0, :, :] *= 1/3.
            obs[1, :, :] *= 2/3.
            obs = np.sum(obs, axis=-1).reshape(self.obs_shape)
        return obs.copy()

    def step(self, action: int) -> Tuple[np.ndarray, float, bool, dict]:

        # Zero out the previous player cell
        self.grid[self.player[0], self.player[1], PLAYER_CHANNEL] = 0.

        # Update the new player cell, keeping it within the grid boundaries
        action = ACTION_MAP[action]
        _row = min(self.size-1, max(0, self.player[0] + action[0]))
        _col = min(self.size-1, max(0, self.player[1] + action[1]))

        # If the new position is open, update player position, else do nothing
        if self.grid[_row, _col, OBSTACLE_CHANNEL] == 0:
            self.player = (_row, _col)
        self.grid[self.player[0], self.player[1], PLAYER_CHANNEL] = 1.

        # Look for termination
        goal_reached = tuple(self.player) == self.goal
        self.episode_steps += 1
        max_steps_reached = self.episode_steps == self.max_episode_steps
        done = goal_reached or max_steps_reached

        # Compute reward
        reward = -1
        if done:
            reward += self.get_terminal_reward()
        self.cumulative_reward += reward

        # If using sparse rewards, only return cumulative reward if done, else 0.
        if self.sparse_rewards:
            reward = self.cumulative_reward if done else 0.

        return self.get_obs(), reward, done, {}

    def get_terminal_reward(self) -> float:
        # Terminal reward results in max cumulative reward being 0.
        return -self._tuple_distance(self.player, self.goal) + 2 * (self.size - 1)

    def _tuple_distance(self, t1, t2) -> float:
        """Compute the manhattan distance between two tuples."""
        return np.sum(np.abs((np.array(t1) - np.array(t2))))

def make_empty_grid(size=5):
    """Helper function for creating empty (no obstacles) of given size."""
    grid = np.zeros((size, size, 3))
    grid[0, 0, PLAYER_CHANNEL] = 1
    grid[-1, -1, GOAL_CHANNEL] = 1
    return grid

def make_doorway_grid():
    """Example where wall blocks all but 2 pixels for the player to pass through."""
    size = 10
    grid = np.zeros((size, size, 3))

    obstacle_idx = np.ones((8, 3), dtype=int)
    obstacle_idx[:, 0] = 4
    obstacle_idx[:, 1] = [x for x in range(10) if x not in [4, 5]]
    obstacle_idx[:, 2] = OBSTACLE_CHANNEL

    grid[obstacle_idx[:, 0], obstacle_idx[:, 1], obstacle_idx[:, 2]] = 1
    grid[0, 0, PLAYER_CHANNEL] = 1
    grid[-1, -1, GOAL_CHANNEL] = 1

    return grid

def policy(env):
    """An optimal policy for empty gridworld: find the vector pointing towards
    the goal, and choose the first non-zero direction.  Total episode reward
    should be 0 when running this."""
    goal_direction = np.array(env.goal) - np.array(env.player)
    print("goal direction", goal_direction)
    action = np.where(goal_direction.squeeze() != 0)[0][0]
    if action == 0:
        if goal_direction[action] > 0:
            return 1
        return 3
    if goal_direction[action] > 0:
        return 0
    return 2

if __name__ == "__main__":

    # from tf_model import gridworld_image_embed_policy
    # model = gridworld_image_embed_policy(
    #     size=32,
    #     filters=[4, 8, 16],
    #     kernel_size=[8, 2, 2],
    #     strides=[8, 2, 1]
    # )

    size = 64
    grid = make_empty_grid(size=size)
    env = GridWorldEnv(grid, obs_type="scalar", max_episode_steps=2*size+2)
    obs = env.reset()

    print("obs", obs)
    #print("PREDICT", model.predict(obs.reshape(1, 1)))
    done, rew, step = False, 0., 0
    while not done:
        #action = env.action_space.sample()
        #action = 2
        action = policy(env)
        obs, r, done, _ = env.step(action)
        rew += r
        step += 1
        print("\nstep {}, reward {}, done {}".format(step, r, done))
        print("action", action)
        print("obs", obs)
        #print("policy", model.predict(obs.reshape(1, 1)))

    print("final reward", rew)

max_stars_repo_name: harrysorensennrel/rlmolecule

max_issues_repo_name: harrysorensennrel/rlmolecule

max_forks_repo_name: harrysorensennrel/rlmolecule


text:
#!/home/mlawson/miniconda3/bin/python

import os

import numpy as np

class OpenFOAMInput(object):
    '''OpenFOAM input data object
    '''
    def __init__(self,input_file):
        self.data = {}
        self.file = os.path.abspath(input_file)
        self._read()

    def _read(self):
        '''
        Note that this function only reads scalar and boolean/string inputs from
        an OpenFOAM intput input file
        '''

        with open(self.file,'r') as fid:
            raw = fid.readlines()

        count = 0
        bloc_comment_test = False
        for i, line in enumerate(raw):

            if raw[i][0:2]=='/*':
                bloc_comment_test = True

            if bloc_comment_test is False:

                if raw[i].strip()[0:2]=='//' or raw[i].strip()[0:1]=='#': # Check if the string is a comment and skip line
                    pass

                elif len(raw[i].strip())==0: # Check if the string is empty and skip line
                    pass

                else:
                    tmp = raw[i].strip().rstrip().split()
                    try:
                        self.data[tmp[0].replace('"', '')] = np.float(tmp[1][:-1])
                    except:
                        self.data[tmp[0].replace('"', '')] = tmp[1][:-1]

            if raw[i][0:2]=='\*':
                bloc_comment_test = False

def read_input(input_file):
    print('\nReading ' + input_file)

    data = OpenFOAMInput(input_file)

    print('\nSuccesfully read '  + input_file)

    return data

# Tutorial
if __name__ == '__main__':
    data = read_input('setUp')
    print(data.data)
    print(data.file)


text:
# Most code in this file was borrowed from https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/15_Style_Transfer.ipynb

import matplotlib.pyplot as plt
import numpy as np
import PIL.Image

"""Helper-functions for image manipulation"""
# This function loads an image and returns it as a numpy array of floating-points.
# The image can be automatically resized so the largest of the height or width equals max_size.
# or resized to the given shape
def load_image(filename, shape=None, max_size=None):
    image = PIL.Image.open(filename)

    if max_size is not None:
        # Calculate the appropriate rescale-factor for
        # ensuring a max height and width, while keeping
        # the proportion between them.
        factor = float(max_size) / np.max(image.size)

        # Scale the image's height and width.
        size = np.array(image.size) * factor

        # The size is now floating-point because it was scaled.
        # But PIL requires the size to be integers.
        size = size.astype(int)

        # Resize the image.
        image = image.resize(size, PIL.Image.LANCZOS) # PIL.Image.LANCZOS is one of resampling filter

    if shape is not None:
        image = image.resize(shape, PIL.Image.LANCZOS) # PIL.Image.LANCZOS is one of resampling filter

    # Convert to numpy floating-point array.
    return np.float32(image)

# Save an image as a jpeg-file.
# The image is given as a numpy array with pixel-values between 0 and 255.
def save_image(image, filename):
    # Ensure the pixel-values are between 0 and 255.
    image = np.clip(image, 0.0, 255.0)

    # Convert to bytes.
    image = image.astype(np.uint8)

    # Write the image-file in jpeg-format.
    with open(filename, 'wb') as file:
        PIL.Image.fromarray(image).save(file, 'jpeg')

# This function plots the content-, mixed- and style-images.
def plot_images(content_image, style_image, mixed_image):
    # Create figure with sub-plots.
    fig, axes = plt.subplots(1, 3, figsize=(10, 10))

    # Adjust vertical spacing.
    fig.subplots_adjust(hspace=0.1, wspace=0.1)

    # Plot the content-image.
    # Note that the pixel-values are normalized to
    # the [0.0, 1.0] range by dividing with 255.
    ax = axes.flat[0]
    ax.imshow(content_image / 255.0, interpolation='sinc')
    ax.set_xlabel("Content")

    # Plot the mixed-image.
    ax = axes.flat[1]
    ax.imshow(mixed_image / 255.0, interpolation='sinc')
    ax.set_xlabel("Output")

    # Plot the style-image
    ax = axes.flat[2]
    ax.imshow(style_image / 255.0, interpolation='sinc')
    ax.set_xlabel("Style")

    # Remove ticks from all the plots.
    for ax in axes.flat:
        ax.set_xticks([])
        ax.set_yticks([])

    # Ensure the plot is shown correctly with multiple plots
    # in a single Notebook cell.
    plt.show()

max_stars_repo_name: pradeeppj/auto-ux

max_issues_repo_name: pradeeppj/auto-ux

max_forks_repo_name: pradeeppj/auto-ux


text:
import functools as ft
import inspect
import pprint
from typing import Any, Callable, Sequence, Union

import jax
import jax.numpy as jnp
import numpy as np

from .custom_types import PyTree
from .filters import is_array

_sentinel = object()

_Leaf = Any

def tree_at(
    where: Callable[[PyTree], Union[_Leaf, Sequence[_Leaf]]],
    pytree: PyTree,
    replace: Union[_Leaf, Sequence[_Leaf]] = _sentinel,
    replace_fn: Callable[[_Leaf], _Leaf] = _sentinel,
    is_leaf: Callable[[_Leaf], bool] = None,
) -> PyTree:
    """Updates a PyTree out-of-place; a bit like using `.at[].set()` on a JAX array.

    **Arguments:**

    - `where`: A callable `PyTree -> Leaf` or `PyTree -> Sequence[Leaf]`. It should
        consume a PyTree with the same structure as `pytree`, and return the leaf or
        leaves that should be replaced. For example
        `where = lambda mlp: mlp.layers[-1].linear.weight`.
    - `pytree`: The PyTree to modify.
    - `replace`: Either a single element, or a sequence of the same length as returned
        by `where`. This specifies the replacements to make at the locations specified
        by `where`. Mutually exclusive with `replace_fn`.
    - `replace_fn`: A function `Leaf -> Any`. It will be called on every leaf specified
        by `where`. The return value from `replace_fn` will be used in its place.
        Mutually exclusive with `replace`.
    - `is_leaf`: As `jax.tree_flatten`; used to determine what should be treated as a
        leaf.

    **Returns:**

    A copy of the input PyTree, with the appropriate modifications.

    !!! example

        This can be used to help specify the weights of a model to train or not to
        train:

        ```python
        model = ...
        trainable = jax.tree_map(lambda _: False, model)
        trainable = equinox.tree_at(lambda mlp: mlp.layers[-1].linear.weight, model, replace=True)
        equinox.filter_grad(..., filter_spec=trainable)
        ```

    !!! example

        Sub-PyTrees can be replaced by flattening them to leaves first:

        ```python
        equinox.tree_at(lambda t: jax.tree_leaves(t.subtree), pytree,
                        jax.tree_leaves(new_subtree))
        ```
    """

    if (replace is _sentinel and replace_fn is _sentinel) or (
        replace is not _sentinel and replace_fn is not _sentinel
    ):
        raise ValueError(
            "Precisely one of `replace` and `replace_fn` must be specified."
        )
    elif replace is _sentinel:
        replace_passed = False
        replacer = lambda j, i: replace_fn(flat[i])
    else:
        replace_passed = True
        replacer = lambda j, i: replace[j]

    # TODO: is there a neater way of accomplishing this?
    flat, treedef = jax.tree_flatten(pytree, is_leaf=is_leaf)
    flat_indices = list(range(len(flat)))
    index_pytree = jax.tree_unflatten(treedef, flat_indices)
    index = where(index_pytree)
    # where can return either a single entry, or a sequence
    if isinstance(index, int):
        index = (index,)
        replace = (replace,)
    elif isinstance(index, Sequence):
        for i in index:
            if not isinstance(i, int):
                raise ValueError(
                    r"""`where` must return a sequence of only leaves; not some subtree.

                    If you want to replace all of a subtree, you can do so by replacing
                    >>> eqx.tree_at(lambda t: t.subtree, tree, new_subtree)  # buggy
                    with
                    >>> eqx.tree_at(lambda t: jax.tree_leaves(t.subtree), tree,
                    ...             jax.tree_leaves(new_subtree))  # fixed
                    """
                )

    if replace_passed and len(index) != len(replace):
        raise ValueError(
            "`where` must return a sequence of leaves of the same length as `replace`."
        )
    for j, i in enumerate(index):
        flat[i] = replacer(j, i)

    return jax.tree_unflatten(treedef, flat)

def tree_equal(*pytrees: PyTree) -> bool:
    """Returns `True` if all input PyTrees are equal. Every PyTree must have the same
    structure. Any JAX or NumPy arrays (as leaves) must have the same shape, dtype, and
    values to be considered equal. JAX arrays and NumPy arrays are not considered equal
    to each other.

    **Arguments:**

    - `*pytrees`: Any number of PyTrees each with any structure.

    **Returns:**

    A boolean.
    """
    flat, treedef = jax.tree_flatten(pytrees[0])
    array_types = (jnp.ndarray, np.ndarray)
    for pytree in pytrees[1:]:
        flat_, treedef_ = jax.tree_flatten(pytree)
        if treedef_ != treedef:
            return False
        for elem, elem_ in zip(flat, flat_):
            if isinstance(elem, array_types):
                if isinstance(elem_, array_types):
                    if (
                        (type(elem) != type(elem_))
                        or (elem.shape != elem_.shape)
                        or (elem.dtype != elem_.dtype)
                        or (elem != elem_).any()
                    ):
                        return False
                else:
                    return False
            else:
                if isinstance(elem_, array_types):
                    return False
                else:
                    if elem != elem_:
                        return False
    return True

# From:
# https://github.com/google/jax/blob/ee6749608a1588f1f458e0e8ad8c9ecc8942aa83/jax/core.py#L1080  # noqa: E501
def _short_dtype_name(dtype):
    return (
        dtype.name.replace("float", "f")
        .replace("uint", "u")
        .replace("int", "i")
        .replace("complex", "c")
    )

class _WithRepr:
    def __init__(self, val):
        self.val = val

    def __repr__(self):
        return self.val

def _convert(leaf):
    wrapped = False
    wrapper_types = (jax.custom_vjp, jax.custom_jvp, ft.partial)
    while isinstance(leaf, wrapper_types):
        if isinstance(leaf, (jax.custom_jvp, jax.custom_vjp)):
            leaf = leaf.__wrapped__
            # Not always thought of as a wrapper so we don't set wrapped=True
        if isinstance(leaf, ft.partial):
            leaf = leaf.func
            wrapped = True

    if is_array(leaf):
        dt_str = _short_dtype_name(leaf.dtype)
        shape_str = ",".join(map(str, leaf.shape))
        return _WithRepr(f"{dt_str}[{shape_str}]")
    elif inspect.isfunction(leaf):
        if wrapped:
            fn_str = "wrapped function"
        else:
            fn_str = "function"
        return _WithRepr(f"<{fn_str} {leaf.__name__}>")
    else:
        return leaf

def tree_pformat(pytree: PyTree, **kwargs) -> str:
    """Pretty-formats a PyTree as a string, whilst abbreviating JAX arrays.

    All JAX arrays in the PyTree are condensed down to a short string representation
    of their dtype and shape.

    (This is the function used in `__str__` of [`equinox.Module`][].)

    !!! example

        A 32-bit floating-point JAX array of shape `(3, 4)` is printed as `f32[3,4]`.

    **Arguments:**

    - `pytree`: The PyTree to pretty-format.
    - `**kwargs`: Any keyword arguments for `pprint.pformat`.

    **Returns:**

    A string.

    !!! info

        This is best used with Python 3.10 or above, for which the standard library
        `pprint` supports dataclasses and will add line breaks appropriately.
        (`tree_pformat` uses `pprint`; [`equinox.Module`][] uses dataclasses.)
    """
    return pprint.pformat(jax.tree_map(_convert, pytree), **kwargs)

max_stars_repo_name: marcelroed/equinox

max_issues_repo_name: marcelroed/equinox

max_forks_repo_name: marcelroed/equinox

reason: import numpy,import jax