text:
import cv2
import numpy as np

TRACKBAR_WINDOW = "Trackbars"

class Trackbars:
    """
    Attributes
    ----------
    lower : np array
        reference to the lowerHSV array
    upper : np array
        reference to the upperHSV array

    Methods
    -------
    startTrackbars
        Starts the HSV trackbars. Changes in value in the trackbars will be updated to the lowerHSV and upperHSV arrays

    useHSVTrackbars
        ~ currently not in-use
        Opens a window that displays mask based on trackbar values

    closeTrackbars
        Closes trackbars and return lower & upper values in separate arrays
        - return values might not be necessary because you can get the same values in the lowerHSV & upperHSV arrays
          passed when creating an instance
    """

    def __init__(self, lower, upper):
        self.lower = lower
        self.upper = upper

    def startTrackbars(self):
        l = self.lower
        u = self.upper

        cv2.namedWindow(TRACKBAR_WINDOW)
        cv2.resizeWindow(TRACKBAR_WINDOW, 640, 240)
        cv2.createTrackbar("Hue Min", TRACKBAR_WINDOW, l[0], 179, self.hueMin)
        cv2.createTrackbar("Hue Max", TRACKBAR_WINDOW, u[0], 179, self.hueMax)
        cv2.createTrackbar("Sat Min", TRACKBAR_WINDOW, l[1], 255, self.satMin)
        cv2.createTrackbar("Sat Max", TRACKBAR_WINDOW, u[1], 255, self.satMax)
        cv2.createTrackbar("Val Min", TRACKBAR_WINDOW, l[2], 255, self.valMin)
        cv2.createTrackbar("Val Max", TRACKBAR_WINDOW, u[2], 255, self.valMax)

    def useHSVTrackbars(self, img):
        imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

        h_min = cv2.getTrackbarPos("Hue Min", TRACKBAR_WINDOW)
        h_max = cv2.getTrackbarPos("Hue Max", TRACKBAR_WINDOW)
        s_min = cv2.getTrackbarPos("Sat Min", TRACKBAR_WINDOW)
        s_max = cv2.getTrackbarPos("Sat Max", TRACKBAR_WINDOW)
        v_min = cv2.getTrackbarPos("Val Min", TRACKBAR_WINDOW)
        v_max = cv2.getTrackbarPos("Val Max", TRACKBAR_WINDOW)

        lower = np.array([h_min, s_min, v_min])
        upper = np.array([h_max, s_max, v_max])
        mask = cv2.inRange(imgHSV, lower, upper)

        cv2.imshow("Mask", mask)

    def closeTrackbars(self):
        h_min = cv2.getTrackbarPos("Hue Min", TRACKBAR_WINDOW)
        h_max = cv2.getTrackbarPos("Hue Max", TRACKBAR_WINDOW)
        s_min = cv2.getTrackbarPos("Sat Min", TRACKBAR_WINDOW)
        s_max = cv2.getTrackbarPos("Sat Max", TRACKBAR_WINDOW)
        v_min = cv2.getTrackbarPos("Val Min", TRACKBAR_WINDOW)
        v_max = cv2.getTrackbarPos("Val Max", TRACKBAR_WINDOW)

        lower = np.array([h_min, s_min, v_min])
        upper = np.array([h_max, s_max, v_max])

        cv2.destroyWindow(TRACKBAR_WINDOW)
        cv2.destroyWindow("Mask")

        return lower, upper

    # onChange callbacks
    def hueMin(self, x):
        self.lower[0] = x

    def hueMax(self, x):
        self.upper[0] = x

    def satMin(self, x):
        self.lower[1] = x

    def satMax(self, x):
        self.upper[1] = x

    def valMin(self, x):
        self.lower[2] = x

    def valMax(self, x):
        self.upper[2] = x

ext: py

max_stars_repo_name: fcyen/AR-Origami-Instructor

max_issues_repo_name: fcyen/AR-Origami-Instructor

max_forks_repo_name: fcyen/AR-Origami-Instructor

reason: import numpy


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

schoolPosition = {'Longitude':-2.233771, 'Latitude':53.46679}

rc = 6378.137
rj = 6356.725

def ToRad(deg):
  return deg * math.pi / 180

def GetR(lat):
  return rj + (rc - rj) * (90-lat) / 90

def One2OneDistanceSquare(a, b):
  degree = a['Latitude']
  r = GetR(degree)
  sr = r * math.cos(ToRad(degree))

  deltaLatitude = ToRad(a['Latitude'] - b['Latitude'])
  deltaLongitude = ToRad(a['Longitude'] - b['Longitude'])
  return (deltaLatitude * r)**2 + (deltaLongitude * sr)**2

def One2OneDistance(a, b):
  return math.sqrt(One2OneDistanceSquare(a, b))

def OneDistanceSqure(point, targetsdf):
  result = np.zeros(len(targetsdf))
  for index, row in targetsdf.iterrows():
    result[index] = One2OneDistanceSquare(point, row)
  return result

def OneDistance(point, targets):
  result = OneDistanceSqure(point, targets)
  return np.sqrt(result)

def LoadScore(crime, key):
  result = np.zeros(len(crime))
  for index, row in crime.iterrows():
    result[index] = row[key]
  return result

def GetCrimeScore(airbnb, crime):
  print('build radis data')
  result = np.zeros(len(airbnb))
  areas = np.zeros(len(airbnb))
  minindexs = [0]*len(airbnb)
  score = LoadScore(crime, 'score_0')
  area = LoadScore(crime, 'area')
  meanscore = np.mean(score)
  k = 50/meanscore
  print('load score data')
  for index, row in airbnb.iterrows():
    if index % 100 == 0:
      print("{}/{}".format(index, len(airbnb)))
    distance = OneDistanceSqure(row, crime)
    minindex = distance == np.min(distance)
    values = score[minindex] * k
    result[index] = np.sum(values)
    areas[index] = area[index]
    for i in range(len(minindex)):
      if minindex[i]:
        minindexs[index] = i
        break
  return result, areas, minindexs

def CommuteScoreFunc(distance):
  if distance < 0.1:
    return 100
  elif distance < 0.4:
    return 80
  elif distance < 1:
    return 70
  elif distance < 3:
    return 50
  else:
    return 50 * 9 / (distance**2)

def GetCommuteScore(airbnb, school):
  result = np.zeros(len(airbnb))
  distance = [0]*len(airbnb)
  for index, row in airbnb.iterrows():
    distance[index] = One2OneDistance(row, school)
    result[index] = CommuteScoreFunc(distance[index])
  return result, distance

def GetBusDistance(airbnb, bus):
  result = np.zeros(len(airbnb))
  tempdf = []
  for index, row in airbnb.iterrows():
    if index % 10 == 0:
      print("{}/{}".format(index, len(airbnb)))
    distance = OneDistance(row, bus)
    result[index] = np.min(distance)
    row['bus distance'] = result[index]
    tempdf.append(row)
  pd.DataFrame(tempdf).to_csv("distance.csv")
  return result

def GetBusScore(airbnb, bus):
  distance = GetBusDistance(airbnb, bus)
  #print(distance)
  allScore = 50*(0.1)/distance
  allScore[allScore>=50] = 50
  return allScore, distance

def GetRoomScore(airbnb):
  result = np.zeros(len(airbnb))
  for index, row in airbnb.iterrows():
    result[index] = row['bed_score'] * 100
  return result

def GetPrice(airbnb):
  result = [0]*len(airbnb)
  for index, row in airbnb.iterrows():
    result[index] = row['price']
  return result

def GetPriceScore(airbnb):
  price = GetPrice(airbnb)
  #print('price {}'.format(price))
  delta = np.max(price) - np.min(price)
  #print('delta {}'.format(delta))
  score = price - np.min(price)
  #print('score {}'.format(score))
  score = score / delta
  #print('score {}'.format(score))
  score = 1 - score
  return score * 100

def GetPriceBonus(airbnb, minindexs):
  pricesCount = {}
  prices = GetPrice(airbnb)
  for index in range(len(prices)):
    minIndex = minindexs[index]
    if minIndex not in pricesCount:
      pricesCount [minIndex] = [0,0]
    pricesCount[minIndex][0] += prices[index]
    pricesCount[minIndex][1] += 1

  for key in pricesCount:
    pricesCount[key][0] /= pricesCount[key][1]

  result = [0]*len(prices)
  average = [0]*len(prices)

  for index,row in airbnb.iterrows():
    minIndex = minindexs[index]
    average[index] = pricesCount[minIndex][0]
    price = prices[index]
    if price > average[index]:
      result[index] = max(30 - (price - average[index]), 0)
    else:
      result[index] = min(30 + (average[index] - price), 50)
  return result, average

def GetRating(airbnb):
  rating = np.zeros(len(airbnb))
  for index, row in airbnb.iterrows():
    rating[index] = row['rating']
  return rating

def GetSelfScore(airbnb, bus):
  busScore = GetBusScore(airbnb, bus)
  print('load bus score')
  rating = np.zeros(len(airbnb))
  bed = np.zeros(len(airbnb))
  price = np.zeros(len(airbnb))
  for index, row in airbnb.iterrows():
    rating[index] = row['rating']
    bed[index] = row['bed_score']
    price[index] = row['price']
  return rating * busScore * bed / price

airbnbkeys = ['beds','bed_type','bed_score','rating','price','Latitude','Longitude','name','host_id']
def MergeScore(airbnb, scores):
  result = []
  for index, row in airbnb.iterrows():
    result.append(row)
    for key in scores:
      result[index][key] = scores[key][index]
  return pd.DataFrame(result)

print("start")
airbnbData = pd.read_csv("airbnb.csv")
#airbnbData = pd.read_csv("airbnb_short.csv")

crimeData = pd.read_csv("crime.csv")
busData = pd.read_csv("bus.csv")

scoreDict = {}
print('load data')

crimeScoreData = pd.read_csv('crimescore.csv')
crimeScore = crimeScoreData['crime']
areaScore = crimeScoreData['area']
minindexs = crimeScoreData['minindexs']

#crimeScore, areaScore, minindexs = GetCrimeScore(airbnbData, crimeData)
scoreDict['crime'] = crimeScore
scoreDict['area'] = areaScore
scoreDict['minindexs'] = minindexs

print("crime score: {}".format(len(crimeScore)))
df = pd.DataFrame(scoreDict)
df.to_csv("crimescore.csv")

commuteScore, distance = GetCommuteScore(airbnbData, schoolPosition)
scoreDict['commute'] = commuteScore
scoreDict['commute distance'] = distance
print('commute score: {}'.format(len(commuteScore)))

busScore, distance = GetBusScore(airbnbData, busData)
scoreDict['bus'] = busScore
scoreDict['bus distance'] = distance
print("bus bonus: {}".format(len(busScore)))

roomScore = GetRoomScore(airbnbData)
scoreDict['room'] = roomScore
print('room score: {}'.format(len(roomScore)))

priceScore = GetPriceScore(airbnbData)
scoreDict['price score'] = priceScore
print('price score: {}'.format(len(priceScore)))

priceBonus, average = GetPriceBonus(airbnbData, minindexs)
scoreDict['price bonus'] = priceBonus
scoreDict['average'] = average
print('price bonus: {}'.format(len(priceBonus)))

rating = GetRating(airbnbData)
scoreDict['rating'] = rating
print('rating: {}'.format(len(rating)))

totalScore = rating * (commuteScore + priceBonus + busScore + roomScore + priceScore - crimeScore) / 100
#totalScore = rating * (commuteScore + priceBonus + roomScore + priceScore - crimeScore) / 100

totalScore[totalScore < 0] = 0
scoreDict['total'] = totalScore
print('total score: {}'.format(len(totalScore)))
mergeDf = MergeScore(airbnbData, scoreDict)
print(mergeDf.head())
mergeDf.to_csv('totalscore.csv')

max_stars_repo_name: richsoap/Homeworks

max_issues_repo_name: richsoap/Homeworks

max_forks_repo_name: richsoap/Homeworks


text:
"""
    Tests for the temporal aspect of the Temporal VF2 isomorphism algorithm.
"""
from nose.tools import assert_true, assert_false, assert_equal
from nose import SkipTest
import networkx as nx
from networkx.algorithms import isomorphism as iso
from datetime import date, datetime, timedelta

def provide_g1_edgelist():
    return [(0, 1), (0, 2), (1, 2), (2, 4), (1, 3), (3, 4), (4, 5)]

def put_same_time(G, att_name):
    for e in G.edges(data=True):
        e[2][att_name] = date(2015, 1, 1)
    return G

def put_same_datetime(G, att_name):
    for e in G.edges(data=True):
        e[2][att_name] = datetime(2015, 1, 1)
    return G

def put_sequence_time(G, att_name):
    current_date = date(2015, 1, 1)
    for e in G.edges(data=True):
        current_date += timedelta(days=1)
        e[2][att_name] = current_date
    return G

def put_time_config_0(G, att_name):
    G[0][1][att_name] = date(2015, 1, 2)
    G[0][2][att_name] = date(2015, 1, 2)
    G[1][2][att_name] = date(2015, 1, 3)
    G[1][3][att_name] = date(2015, 1, 1)
    G[2][4][att_name] = date(2015, 1, 1)
    G[3][4][att_name] = date(2015, 1, 3)
    G[4][5][att_name] = date(2015, 1, 3)
    return G

def put_time_config_1(G, att_name):
    G[0][1][att_name] = date(2015, 1, 2)
    G[0][2][att_name] = date(2015, 1, 1)
    G[1][2][att_name] = date(2015, 1, 3)
    G[1][3][att_name] = date(2015, 1, 1)
    G[2][4][att_name] = date(2015, 1, 2)
    G[3][4][att_name] = date(2015, 1, 4)
    G[4][5][att_name] = date(2015, 1, 3)
    return G

def put_time_config_2(G, att_name):
    G[0][1][att_name] = date(2015, 1, 1)
    G[0][2][att_name] = date(2015, 1, 1)
    G[1][2][att_name] = date(2015, 1, 3)
    G[1][3][att_name] = date(2015, 1, 2)
    G[2][4][att_name] = date(2015, 1, 2)
    G[3][4][att_name] = date(2015, 1, 3)
    G[4][5][att_name] = date(2015, 1, 2)
    return G

class TestTimeRespectingGraphMatcher(object):
    """
        A test class for the undirected temporal graph matcher.
    """

    def provide_g1_topology(self):
        G1 = nx.Graph()
        G1.add_edges_from(provide_g1_edgelist())
        return G1

    def provide_g2_path_3edges(self):
        G2 = nx.Graph()
        G2.add_edges_from([(0, 1), (1, 2), (2, 3)])
        return G2

    def test_timdelta_zero_timeRespecting_returnsTrue(self):
        G1 = self.provide_g1_topology()
        temporal_name = 'date'
        G1 = put_same_time(G1, temporal_name)
        G2 = self.provide_g2_path_3edges()
        d = timedelta()
        gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d)
        assert_true(gm.subgraph_is_isomorphic())

    def test_timdelta_zero_datetime_timeRespecting_returnsTrue(self):
        G1 = self.provide_g1_topology()
        temporal_name = 'date'
        G1 = put_same_datetime(G1, temporal_name)
        G2 = self.provide_g2_path_3edges()
        d = timedelta()
        gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d)
        assert_true(gm.subgraph_is_isomorphic())

    def test_attNameStrange_timdelta_zero_timeRespecting_returnsTrue(self):
        G1 = self.provide_g1_topology()
        temporal_name = 'strange_name'
        G1 = put_same_time(G1, temporal_name)
        G2 = self.provide_g2_path_3edges()
        d = timedelta()
        gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d)
        assert_true(gm.subgraph_is_isomorphic())

    def test_notTimeRespecting_returnsFalse(self):
        G1 = self.provide_g1_topology()
        temporal_name = 'date'
        G1 = put_sequence_time(G1, temporal_name)
        G2 = self.provide_g2_path_3edges()
        d = timedelta()
        gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d)
        assert_false(gm.subgraph_is_isomorphic())

    def test_timdelta_one_config0_returns_no_embeddings(self):
        G1 = self.provide_g1_topology()
        temporal_name = 'date'
        G1 = put_time_config_0(G1, temporal_name)
        G2 = self.provide_g2_path_3edges()
        d = timedelta(days=1)
        gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d)
        count_match = len(list(gm.subgraph_isomorphisms_iter()))
        assert_true(count_match == 0)

    def test_timdelta_one_config1_returns_four_embedding(self):
        G1 = self.provide_g1_topology()
        temporal_name = 'date'
        G1 = put_time_config_1(G1, temporal_name)
        G2 = self.provide_g2_path_3edges()
        d = timedelta(days=1)
        gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d)
        count_match = len(list(gm.subgraph_isomorphisms_iter()))
        assert_true(count_match == 4)

    def test_timdelta_one_config2_returns_ten_embeddings(self):
        G1 = self.provide_g1_topology()
        temporal_name = 'date'
        G1 = put_time_config_2(G1, temporal_name)
        G2 = self.provide_g2_path_3edges()
        d = timedelta(days=1)
        gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d)
        L = list(gm.subgraph_isomorphisms_iter())
        count_match = len(list(gm.subgraph_isomorphisms_iter()))
        assert_true(count_match == 10)

class TestDiTimeRespectingGraphMatcher(object):
    """
        A test class for the directed time-respecting graph matcher.
    """

    def provide_g1_topology(self):
        G1 = nx.DiGraph()
        G1.add_edges_from(provide_g1_edgelist())
        return G1

    def provide_g2_path_3edges(self):
        G2 = nx.DiGraph()
        G2.add_edges_from([(0, 1), (1, 2), (2, 3)])
        return G2

    def test_timdelta_zero_same_dates_returns_true(self):
        G1 = self.provide_g1_topology()
        temporal_name = 'date'
        G1 = put_same_time(G1, temporal_name)
        G2 = self.provide_g2_path_3edges()
        d = timedelta()
        gm = iso.TimeRespectingDiGraphMatcher(G1, G2, temporal_name, d)
        assert_true(gm.subgraph_is_isomorphic())

    def test_attNameStrange_timdelta_zero_same_dates_returns_true(self):
        G1 = self.provide_g1_topology()
        temporal_name = 'strange'
        G1 = put_same_time(G1, temporal_name)
        G2 = self.provide_g2_path_3edges()
        d = timedelta()
        gm = iso.TimeRespectingDiGraphMatcher(G1, G2, temporal_name, d)
        assert_true(gm.subgraph_is_isomorphic())

    def test_timdelta_one_config0_returns_no_embeddings(self):
        G1 = self.provide_g1_topology()
        temporal_name = 'date'
        G1 = put_time_config_0(G1, temporal_name)
        G2 = self.provide_g2_path_3edges()
        d = timedelta(days=1)
        gm = iso.TimeRespectingDiGraphMatcher(G1, G2, temporal_name, d)
        count_match = len(list(gm.subgraph_isomorphisms_iter()))
        assert_true(count_match == 0)

    def test_timdelta_one_config1_returns_one_embedding(self):
        G1 = self.provide_g1_topology()
        temporal_name = 'date'
        G1 = put_time_config_1(G1, temporal_name)
        G2 = self.provide_g2_path_3edges()
        d = timedelta(days=1)
        gm = iso.TimeRespectingDiGraphMatcher(G1, G2, temporal_name, d)
        count_match = len(list(gm.subgraph_isomorphisms_iter()))
        assert_true(count_match == 1)

    def test_timdelta_one_config2_returns_two_embeddings(self):
        G1 = self.provide_g1_topology()
        temporal_name = 'date'
        G1 = put_time_config_2(G1, temporal_name)
        G2 = self.provide_g2_path_3edges()
        d = timedelta(days=1)
        gm = iso.TimeRespectingDiGraphMatcher(G1, G2, temporal_name, d)
        count_match = len(list(gm.subgraph_isomorphisms_iter()))
        assert_true(count_match == 2)

max_stars_repo_name: MarletteFunding/aws-kube-codesuite

max_issues_repo_name: MarletteFunding/aws-kube-codesuite

max_forks_repo_name: MarletteFunding/aws-kube-codesuite

reason: import networkx,from networkx


text:
#!usr/bin/env python

import sys
import os
import tables as tb
import numpy as np
import errno
import shutil
import time
import zmq
import yaml
from datetime import datetime
from irrad_control.devices.adc.ADS1256_definitions import *
from irrad_control.devices.adc.pipyadc import ADS1256
from irrad_control.devices.adc.ADS1256_drates import ads1256_drates
import irrad_control.devices.adc.ADS1256_default_config as ADS1256_default_config

def load_config(path_to_config_file):
    # Function, which reads the configuration yaml and checks, if all required information is contained for the chosen case.
    # Here we need to check if the config path that was given exists and is a file
    if not os.path.isfile(path_to_config_file):
        print('No config file found at the given path.')
        return

    # At this point we know that the file exists so we can proceed to open and read it
    with open(path_to_config_file, 'r') as conf_file:
        try:
            config = yaml.safe_load(conf_file)
            return config
        except yaml.YAMLError as exception:
            print(exception)
            return

def check_config(config):
    # When we're here we know, that the file was loaded correctly: we need to check if all the required info is contained in the config
    # Initialize a tuple of the values of the config file, which are essential to run the data_logger
    required_info = ('n_digits', 'channels', 'show_data', 'log_type')
    # since channel names are read from main_config.yaml as complete string, we have to get rid of the spaces first, so they dont get recognized as channel names
    config['channels'] = config['channels'] if isinstance(config['channels'], list) else config['channels'].split()
    # check, if all the values which we require are given in the config file
    missing = []
    for req_i in required_info:
        if req_i not in config:
            missing.append(req_i)
    # print out values, which were not handed over by the config file
    if missing:
        print('Following config info is missing: {}'.format(', '.join(missing)))
        return

    # check for valid configuration for each log_type, where port or ip are needed
    if 's' in config['log_type']:
        if not config['port']:
            raise ValueError('data_logger was called with the sending option, but no ZMQ port is given.')

    if 'r' in config['log_type']:
        if not (config['port'] and config['ip']):
            raise ValueError('data_logger was called with the receiving option, but no ZMQ port or host-ip is given.')

    print('Configuration successful.')

def _create_actual_adc_channels(channels, mode):

    # channels TODO: represent not only positive channels
    _all_channels = [POS_AIN0, POS_AIN1,
                     POS_AIN2, POS_AIN3,
                     POS_AIN4, POS_AIN5,
                     POS_AIN6, POS_AIN7]
    # gnd
    _gnd = NEG_AINCOM

    # get actual channels by name
    if len(channels) > 8 and mode == 's':
        raise ValueError('Only 8 single-ended input channels exist')
    elif len(channels) > 4 and mode == 'd':
        raise ValueError('Only 4 differential input channels exist')
    else:
        # only single-ended measurements
        if mode == 's':
            actual_channels = [_all_channels[i] | _gnd for i in range(len(channels))]

        # only differential measurements
        elif mode == 'd':
            actual_channels = [_all_channels[i] | _all_channels[i + 1] for i in range(len(channels))]

        # mix of differential and single-ended measurements
        elif len(mode) > 1:
            # get configuration of measurements
            channel_config = [1 if mode[i] == 's' else 2 for i in range(len(mode))]

            # modes are known and less than 8 channels in total
            if all(m in ['d', 's'] for m in mode) and sum(channel_config) <= 8:
                i = j = 0
                actual_channels = []

                while i != sum(channel_config):
                    if channel_config[j] == 1:
                        actual_channels.append(_all_channels[i] | _gnd)
                    else:
                        actual_channels.append(_all_channels[i] | _all_channels[i + 1])
                    i += channel_config[j]
                    j += 1

                if len(actual_channels) != len(channels):
                    raise ValueError('Number of channels (%i) not matching measurement mode ("%s" == %i differential & %i single-ended channels)!'
                                     % (len(channels), mode, mode.count('d'), mode.count('s')))
                else:
                    raise ValueError(
                        'Unsupported number of channels! %i differential (%i channels) and %i single-ended (%i channels) measurements but only 8 channels total'
                        % (mode.count('d'), mode.count('d') * 2, mode.count('s'), mode.count('s')))
        else:
            raise ValueError('Unknown measurement mode %s. Supported modes are "d" for differential and "s" for single-ended measurements.' % mode)

    return actual_channels

def logger(channels, log_type, n_digits, show_data=False, path=None, fname=None, drate=None, pga_gain=None, rate=None, mode='s', port=None, ip=None):
    """
    Method to log the data read back from a ADS1256 ADC to a file.
    Default is to read from positive AD0-AD7 pins from 0 to 7 for single-
    ended measurement. For differential measurement pin i and i + 1 are
    selected as inputs. Only as many channels are read as there are names
    in the channel list.

    The script should be executed like this : ps_monitor main_config.yaml
    The main_config.yaml file should always be copied from the default_config.yaml and then be modified as desired.
    Parameters
    ----------

    channels: list
        list of strings with names of channels
    log_type: str
        type of logging behaviour
            'w' for ONLY writing data locally
            'sw' for sending data on the specified ZMQ port AND writing it locally on the publisher
            's' for ONLY sending data on the specified ZMQ port
            'rw' for receiving data on the specified ZMQ port AND writing it locally on the receiver
    outfile: str
        string of output file location
    rate: int
        Logging rate in Hz, if None go crazy fast
    drate: int
        ADS1256 sampling rate
    pga_gain: int
        ADC programmable gain amplifier setting
    n_digits: int
        number of decimal places to be logged into the outfile
    mode: 's' or 'd' or str of combination of both
        string character(s) describing the measurement mode: single-endend (s) or differential (d)
    show_data: bool
        whether or not to show the data every second on the stdout
    port:
        ZMQ port on which data is published/received via TCP protocol

    Returns
    -------
    """

    # Create file path, where data should be stored and a copy of the used main_config.yaml file is saved
    full_path = os.path.join(path, datetime.now().strftime('%Y-%m-%d'), datetime.now().strftime('%H-%M-%S'))

    # First thing to do: figure out which arguments are needed from log_type
    if log_type in ('w', 'sw', 'rw'):  # Here we are sure we need to open a file

        print('Storing data in ' + full_path)

        # Check if path to data_outfile already exists and makedir, if not
        if not os.path.exists(full_path):
            try:
                os.makedirs(full_path)
            # This protects us from race conditions, if the directory was created between .exists and .makedir
            except OSError as exc:
                if exc.errno != errno.EEXIST:
                    raise

        # Open required file
        out = tb.open_file(os.path.join(full_path, 'data.h5' if fname is None else fname), 'w')

        # Declare data type numpy style of incoming data
        data_type = [('timestamp_recv', '<f8'), ('timestamp_data', '<f8')] + [(ch, '<f4') for ch in channels]

        # Create buffer for incoming data
        data_buffer = np.zeros(shape=1, dtype=data_type)

        # Create Group
        out.create_group(out.root, "RPiData")

        # Make table
        data_table = out.create_table("/RPiData", description=data_buffer.dtype, name="data")

        #if log_type == 'rw':
        #    # write info header
        #    out.write('# Date: %s \n' % time.asctime())
        #    out.write('# Timestamp receiver / s\t' + 'Timestamp data / s\t' + ' \t'.join('%s / V' % c for c in channels) + '\n')

    # Second thin to figure out: are we sending or receiving data on a socket
    if log_type in ('sw', 'rw', 's'):

        # Check if port works
        try:
            _ = int(port)
        except ValueError:
            print("Port must be castable to type int! No socket will be opened!")
            return

        # Fire up ZMQ stuff
        ctx = zmq.Context()
        socket = ctx.socket(zmq.PUB if log_type != 'rw' else zmq.SUB)

        # Make distinctions between socket types
        if socket.socket_type == zmq.PUB:
            socket.bind("tcp://*:{}".format(port))
        else:
            socket.setsockopt(zmq.SUBSCRIBE, '')  # Connect to all available data
            socket.connect("tcp://%s:%s" % (ip, port))

    # We're using the ADC
    if log_type in ('s', 'sw', 'w'):

        # dictionary of possible gain settings
        _pga_gain = dict([(1, GAIN_1),
                          (2, GAIN_2),
                          (4, GAIN_4),
                          (8, GAIN_8),
                          (16, GAIN_16),
                          (32, GAIN_32),
                          (64, GAIN_64)])

        # write chosen pga_gain setting into adcon register
        ADS1256_default_config.adcon = CLKOUT_OFF | SDCS_OFF | _pga_gain[pga_gain]  # pga_gain needs to be 0-6

        # set chosen sampling rate
        ADS1256_default_config.drate = ads1256_drates[drate]

        # get instance of ADC Board
        adc = ADS1256(conf=ADS1256_default_config)

        # additional delay after changing gain and drate registers
        adc.wait_DRDY()

        # self-calibration
        adc.cal_self()
        adc.wait_DRDY()

        actual_channels = _create_actual_adc_channels(channels, mode)

        # Get the offset voltages for every pin pair we're using here
        offset_volts = []
        for pin_pair in actual_channels:
            adc.mux = pin_pair
            adc.cal_system_offset()
            bit_offset = adc.ofc
            offset_volts.append(bit_offset * adc.v_per_digit)

        # Set this to 0 since we want to manually calc the offset for each channel
        adc.ofc = 0

        # We're writing to file
        if log_type != 's':
            # Declare data type numpy style of incoming data
            meta_type = [('pga_gain', '<i2'), ('drate', '<f4')] + [(ch + "_offset", '<f4') for ch in channels]

            # Create buffer for incoming data
            meta_buffer = np.zeros(shape=1, dtype=meta_type)

            meta_table = out.create_table("/RPiData", description=meta_buffer.dtype, name="meta")

            meta_buffer["pga_gain"] = pga_gain
            meta_buffer["drate"] = drate
            for i, ch in enumerate(channels):
                meta_buffer[ch + "_offset"] = offset_volts[i]

            meta_table.append(meta_buffer)
            meta_table.flush()

    # save a copy of the used main_config.yaml file in the data path
    if not os.path.exists(full_path):
        try:
            os.makedirs(full_path)
        # This protects us from race conditions, if the directory was created between .exists and .makedir
        except OSError as exc:
            if exc.errno != errno.EEXIST:
                raise
    shutil.copyfile(sys.argv[-1], os.path.join(full_path, "used_config.yaml"))

    # try -except clause for ending logger
    try:
        print 'Start logging channel(s) %s to file %s.\nPress CTRL + C to stop.\n' % (', '.join(channels), full_path)
        start = time.time()
        while True:

            # get current channels
            if log_type == 'rw':
                readout_start = time.time()
                # receive actual voltage values including timestamp
                data = socket.recv_json()

                _meta, _data = data['meta'], data['data']

                data_buffer["timestamp_recv"] = time.time()
                data_buffer["timestamp_data"] = _meta['timestamp']
                for ch in _data:
                    data_buffer[ch] = _data[ch]

                readout_end = time.time()
            else:

                readout_start = time.time()

                raw = adc.read_continue(actual_channels)
                volts = [b * adc.v_per_digit for b in raw]

                # TODO: offset seems to be subtracted already in adc.cal_system_offset() in line 133 -> temporarily inserted factor 0.
                actual_volts = [volts[i] - offset_volts[i] for i in range(len(volts))]

                data_buffer["timestamp_data"] = readout_start
                for i, ch in enumerate(channels):
                    data_buffer[ch] = actual_volts[i]

                readout_end = time.time()

                # send data to
                if 's' in log_type:
                    data = {'meta': {'timestamp': readout_start}, 'data': dict(zip(channels, actual_volts))}
                    socket.send_json(data)

                # wait, if wanted
                if isinstance(rate, (int, float)):
                    time.sleep(1. / rate)

            # write voltages to file
            if 'w' in log_type:
                data_table.append(data_buffer)

            # User feedback about logging and readout rates every second
            if time.time() - start > 1:

                try:
                    data_table.flush()
                except NameError:
                    pass

                # actual logging and readout rate
                logging_rate = 1. / (time.time() - readout_start)
                readout_rate = 1. / (readout_end - readout_start)

                # print out with flushing
                if log_type =='rw':
                    log_string = 'Logging rate: %.2f Hz' % logging_rate + ',\t' + 'Readout rate: %.2f Hz for %i channel(s)'\
                             % (readout_rate, len(channels))
                else:
                    log_string = 'Logging rate: %.2f Hz' % logging_rate + ',\t' + 'Readout rate: %.2f Hz for %i channel(s)'\
                             % (readout_rate, len(actual_channels))

                # show values
                if show_data:
                    # print out with flushing
                    if log_type == 'rw':
                        log_string += ': %s' % ', '.join('{}: %.{}f V'.format(channels[i], n_digits) % _data[k] for i,k in enumerate(channels))
                    else:
                        log_string += ': %s' % ', '.join('{}: %.{}f V'.format(channels[i], n_digits) % actual_volts[i] for i in range(len(actual_volts)))

                # print out with flushing
                sys.stdout.write('\r' + log_string)
                sys.stdout.flush()

                # overwrite
                start = time.time()

    except (KeyboardInterrupt, SystemExit):
        if 'w' in log_type:
            print '\nStopping logger...\nClosing %s...' % str(out.filename)
            out.flush()
            out.close()

        if 's' in log_type or 'r' in log_type:
            socket.close()
            print('Stopped {} data'.format('sending' if 's' in log_type else 'receiving'))

    print 'Finished'

def main():
    # sys.argv is a list that contains the command line arguments which where given when this script was called (0th element is path to script itself)
    # The main_config.yaml should be the last argument, when you call the script.
    path_to_config_file = sys.argv[-1]
    config = load_config(path_to_config_file)
    check_config(config)
    _create_actual_adc_channels(config['channels'], config['mode'])
    logger(**config)  # Casting of dict into 'kwargs' aka keyword arguments a la key=value

    # TODO: add "socket" as argument: socket={"type": receiver|sender, "address": tcp://127.0.0.1.8888}
    # TODO: add 'logger_type' keyword which determines whether logger function will a) only write to a file b) only send data c) only receive data

if __name__ == '__main__':
    main()


text:
import argparse
import json
import logging
import os
import numpy as np
from datetime import datetime

import cityflow
from cityflow_env import CityFlowEnv
from utility import parse_roadnet
from dqn_agent import DQNAgent

# import ray

def main():
    logging.getLogger().setLevel(logging.INFO)
    date = datetime.now().strftime('%Y%m%d_%H%M%S')
    parser = argparse.ArgumentParser()
    # parser.add_argument('--scenario', type=str, default='PongNoFrameskip-v4')
    parser.add_argument('--config', type=str, default='config/global_config.json')
    parser.add_argument('--num_step', type=int, default=10 ** 3)
    args = parser.parse_args()

    # preparing config
    # # for rnvironment
    config = json.load(open(args.config))
    config["num_step"] = args.num_step
    # config["replay_data_path"] = "replay"
    cityflow_config = json.load(open(config['cityflow_config_file']))
    roadnetFile = cityflow_config['dir'] + cityflow_config['roadnetFile']
    config["lane_phase_info"] = parse_roadnet(roadnetFile)

    # # for agent
    intersection_id = list(config['lane_phase_info'].keys())[0]
    phase_list = config['lane_phase_info'][intersection_id]['phase']
    logging.info(phase_list)
    config["state_size"] = len(config['lane_phase_info'][intersection_id][
                                   'start_lane']) + 1  # 1 is for the current phase. [vehicle_count for each start lane] + [current_phase]
    config["action_size"] = len(phase_list)

    # build cotyflow environment
    env = CityFlowEnv(config)

    # build agent
    agent = DQNAgent(config)

    # training
    batch_size = 32
    EPISODES = 11
    learning_start = 300
    update_model_freq = 300
    update_target_model_freq = 1500
    num_step = config['num_step']
    state_size = config['state_size']

    ### the dqp learning code
    if not os.path.exists("model"):
        os.makedirs("model")
    model_dir = "model/{}".format(date)
    os.makedirs(model_dir)

    total_step = 0
    for i in range(EPISODES):
        env.reset()
        state = env.get_state()
        state = np.array(list(state['start_lane_vehicle_count'].values()) + [state['current_phase']])
        state = np.reshape(state, [1, state_size])

        episode_length = 0
        while episode_length < num_step:
            action = agent.choose_action(state)  # index of action
            action_phase = phase_list[action]  # actual action
            # no yellow light
            next_state, reward = env.step(action_phase)  # one step
            last_action_phase = action_phase
            episode_length += 1
            total_step += 1

            # store to replay buffer
            next_state = np.array(list(next_state['start_lane_vehicle_count'].values()) + [next_state['current_phase']])
            next_state = np.reshape(next_state, [1, state_size])
            agent.remember(state, action_phase, reward, next_state)

            state = next_state

            # training
            if total_step > learning_start and total_step % update_model_freq == 0:
                agent.replay()

            # update target Q netwark
            if total_step > learning_start and total_step % update_target_model_freq == 0:
                agent.update_target_network()

            # log
            logging.info("episode:{}/{}, total_step:{}, action:{}, reward:{}"
                         .format(i, EPISODES, total_step, action, reward))

        # save model
        if i % 10 == 0:
            agent.model.save(model_dir + "/dqn-{}.h5".format(i))

    # save simulation replay
    # env.log()
    # automatically

if __name__ == '__main__':
    main()


text:
#!/usr/bin/env python3
# This file is covered by the LICENSE file in the root of this project.
#https://github.com/PRBonn/semantic-kitti-ap
import argparse
import os
import yaml
import sys
import numpy as np
import time
import json

from eval_np import Panoptic4DEval

# possible splits
splits = ["train", "valid", "test"]

if __name__ == '__main__':
  parser = argparse.ArgumentParser("./evaluate_panoptic.py")
  parser.add_argument(
      '--dataset',
      '-d',
      type=str,
      required=True,
      help='Dataset dir. No Default',
  )
  parser.add_argument(
      '--predictions',
      '-p',
      type=str,
      required=False,
      help='Prediction dir. Same organization as dataset, but predictions in'
      'each sequences "prediction" directory. No Default. If no option is set'
      ' we look for the labels in the same directory as dataset')
  parser.add_argument(
      '--split',
      '-s',
      type=str,
      required=False,
      choices=["train", "valid", "test"],
      default="valid",
      help='Split to evaluate on. One of ' + str(splits) + '. Defaults to %(default)s',
  )
  parser.add_argument(
      '--data_cfg',
      '-dc',
      type=str,
      required=False,
      default="config/semantic-kitti.yaml",
      help='Dataset config file. Defaults to %(default)s',
  )
  parser.add_argument(
      '--limit',
      '-l',
      type=int,
      required=False,
      default=None,
      help='Limit to the first "--limit" points of each scan. Useful for'
      ' evaluating single scan from aggregated pointcloud.'
      ' Defaults to %(default)s',
  )
  parser.add_argument(
      '--min_inst_points',
      type=int,
      required=False,
      default=50,
      help='Lower bound for the number of points to be considered instance',
  )
  parser.add_argument(
      '--output',
      type=str,
      required=False,
      default=None,
      help='Output directory for scores.txt and detailed_results.html.',
  )

  start_time = time.time()

  FLAGS, unparsed = parser.parse_known_args()

  # fill in real predictions dir
  if FLAGS.predictions is None:
    FLAGS.predictions = FLAGS.dataset

  # print summary of what we will do
  print("*" * 80)
  print("INTERFACE:")
  print("Data: ", FLAGS.dataset)
  print("Predictions: ", FLAGS.predictions)
  print("Split: ", FLAGS.split)
  print("Config: ", FLAGS.data_cfg)
  print("Limit: ", FLAGS.limit)
  print("Min instance points: ", FLAGS.min_inst_points)
  print("Output directory", FLAGS.output)
  print("*" * 80)

  # assert split
  assert (FLAGS.split in splits)

  # open data config file
  DATA = yaml.safe_load(open(FLAGS.data_cfg, 'r'))

  # get number of interest classes, and the label mappings
  # class
  class_remap = DATA["learning_map"]
  class_inv_remap = DATA["learning_map_inv"]
  class_ignore = DATA["learning_ignore"]
  nr_classes = len(class_inv_remap)
  class_strings = DATA["labels"]

  # make lookup table for mapping
  # class
  maxkey = max(class_remap.keys())

  # +100 hack making lut bigger just in case there are unknown labels
  class_lut = np.zeros((maxkey + 100), dtype=np.int32)
  class_lut[list(class_remap.keys())] = list(class_remap.values())

  # class
  ignore_class = [cl for cl, ignored in class_ignore.items() if ignored]

  print("Ignoring classes: ", ignore_class)

  # get test set
  test_sequences = DATA["split"][FLAGS.split]

  # create evaluator
  class_evaluator = Panoptic4DEval(nr_classes, None, ignore_class, offset = 2 ** 32, min_points=FLAGS.min_inst_points)

  # get label paths
  label_names = []
  for sequence in test_sequences:
    sequence = '{0:02d}'.format(int(sequence))
    label_paths = os.path.join(FLAGS.dataset, "sequences", sequence, "labels")
    # populate the label names
    seq_label_names = sorted([os.path.join(label_paths, fn) for fn in os.listdir(label_paths) if fn.endswith(".label")])
    label_names.extend(seq_label_names)
  # print(label_names)

  # get predictions paths
  pred_names = []
  for sequence in test_sequences:
    sequence = '{0:02d}'.format(int(sequence))
    pred_paths = os.path.join(FLAGS.predictions, "sequences", sequence, "predictions")
    # populate the label names
    seq_pred_names = sorted([os.path.join(pred_paths, fn) for fn in os.listdir(pred_paths) if fn.endswith(".label")])
    pred_names.extend(seq_pred_names)
  # print(pred_names)

  # check that I have the same number of files
  assert (len(label_names) == len(pred_names))
  print("Evaluating sequences: ", end="", flush=True)
  # open each file, get the tensor, and make the iou comparison

  complete = len(label_names)

  count = 0
  percent = 10
  for label_file, pred_file in zip(label_names, pred_names):
    count = count + 1
    if 100 * count / complete > percent:
      print("{}% ".format(percent), end="", flush=True)
      percent = percent + 10
    # print("evaluating label ", label_file, "with", pred_file)
    # open label

    label = np.fromfile(label_file, dtype=np.uint32)

    u_label_sem_class = class_lut[label & 0xFFFF]  # remap to xentropy format
    u_label_inst = label >> 16
    if FLAGS.limit is not None:
      u_label_sem_class = u_label_sem_class[:FLAGS.limit]
      u_label_inst = u_label_inst[:FLAGS.limit]

    label = np.fromfile(pred_file, dtype=np.uint32)

    u_pred_sem_class = class_lut[label & 0xFFFF]  # remap to xentropy format
    u_pred_inst = label >> 16
    if FLAGS.limit is not None:
      u_pred_sem_class = u_pred_sem_class[:FLAGS.limit]
      u_pred_inst = u_pred_inst[:FLAGS.limit]

    class_evaluator.addBatch(label_file.split('/')[-3], u_pred_sem_class, u_pred_inst, u_label_sem_class, u_label_inst)

  print("100%")

  complete_time = time.time() - start_time
  LSTQ, LAQ_ovr, LAQ, AQ_p, AQ_r,  iou, iou_mean, iou_p, iou_r = class_evaluator.getPQ4D()
  things_iou = iou[1:9].mean()
  stuff_iou = iou[9:].mean()
  print ("=== Results ===")
  print ("LSTQ:", LSTQ)
  print("S_assoc (LAQ):", LAQ_ovr)
  float_formatter = "{:.2f}".format
  np.set_printoptions(formatter={'float_kind': float_formatter})
  print ("Assoc:", LAQ)
  print ("iou:", iou)
  print("things_iou:", things_iou)
  print("stuff_iou:", stuff_iou)

  print ("S_cls (LSQ):", iou_mean)


text:
# coding: utf-8

# In[1]:

'''将图片像素化'''
#输入一幅图片，要求黑底白字
#图像放大至短边
#矩阵化
#填图，纵边同一化
#
import cv2
import numpy as np
import os
import sys
import ssl
import urllib.request
import json
import string
#文件选择对话框对话框依赖模块
import time
import json
import random
#python生成GUID
import uuid
import copy
import glob as gb

# In[2]:

def Get_File_list(imgFoldName):
    filelist = os.listdir(imgFoldName)
    fileNum = len(filelist)
    return filelist,fileNum

# In[3]:

def Get_Image_list(imgFoldName,format_pic):
    img_path_list = gb.glob(imgFoldName + '/*.' + format_pic)
    imgNum = len(img_path_list)
    return img_path_list,imgNum

# In[4]:

def GetFiledImage(image_height,image_width,image_nchanels,imglist,pix_height):
    imagex_start = 0
    imagey_start = 0
    field_image = np.zeros((image_height,image_width,image_nchanels), np.uint8)
    image_num = len(imglist)
    isaddable = False
    if(image_height > pix_height and image_width > 0):
        isaddable = True
    while isaddable:
        image_index = random.randint(0,(image_num-1))
        image_file = imglist[image_index]
        image = cv2.imread(image_file)
        height_img = image.shape[0]
        width_img = image.shape[1]
        pix_width = round(width_img*pix_height/height_img)
        pix_img = cv2.resize(image,(pix_width,pix_height),interpolation=cv2.INTER_AREA)
        if((imagex_start+pix_width)<image_width):
            #print(imagex_start,imagey_start)
            field_image[imagey_start:(imagey_start+pix_height),imagex_start:(imagex_start+pix_width)] = copy.deepcopy(pix_img)
            imagex_start = imagex_start+pix_width
        else:
            imagex_start = 0
            if((imagey_start+2*pix_height)< image_height):
                imagey_start = imagey_start+pix_height
            else:
                #print(isaddable)
                isaddable = False
    cv2.imwrite('Image_pic1.jpg',field_image)
    return field_image

# In[5]:

def ImageMerge(img,img_mask):
    height_img_mask = img_mask.shape[0]
    width_img_mask = img_mask.shape[1]
    for i in range(height_img_mask):
        for j in range(width_img_mask):
            if(img_mask[i,j] < 100):
                #print(i,j)
                img[i,j,:] = 0
                #print(img)
                #img[i,j] = 0 # 这里可以处理每个像素点
    cv2.imwrite('result.jpg',img)

# In[6]:

if __name__ == '__main__':
    imgFoldName = '/home/zhangjie/mathstyle/pic_backed'
    img_format = 'JPG'
    pix_height = 100
    pix_width = 100
    image_height = 10000
    image_width = 10000
    image_nchanels = 3
    #pix_height = 12

    #img = cv2.imread('/home/zhangjie/CarRec/20180706/201807061/201807060850_85b50e90-80b6-11e8-bbe5-000c297a242a.jpg')
    #img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)   #转换了灰度化
    #retval, im_at_fixed = cv2.threshold(img_gray, 150, 255, cv2.THRESH_BINARY)
    #height_mash = im_at_fixed.shape[0]
    #width_mash = im_at_fixed.shape[1]

    #将阈值设置为50，阈值类型为cv2.THRESH_BINARY，则灰度在大于50的像素其值将设置为255，其它像素设置为0
    imglist,imgnum = Get_Image_list(imgFoldName,img_format)
    #print(imglist,imgnum)
    field_image = GetFiledImage(image_height,image_width,3,imglist,pix_height)
    #ImageMerge(field_image,im_at_fixed)

max_stars_repo_name: suixinGit/myphotoshop

max_issues_repo_name: suixinGit/myphotoshop

max_forks_repo_name: suixinGit/myphotoshop


text:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 17 20:54:59 2018

@author: JSen
"""

import numpy as np
import matplotlib.pyplot as plt
from numpy import loadtxt
import os
from scipy.optimize import minimize

os.chdir(os.path.realpath('.'))

data = loadtxt('ex2data1.txt', delimiter=',')

X = data[:, :-1]
#最后一列为label
y = data[:, -1:]

def plot_data(X,y):
    pos = np.where(y==1)[0]
    neg= np.where(y==0)[0]
    plt.scatter(X[pos, 0], X[pos, 1], marker='+')

    plt.scatter(X[neg, 0], X[neg, 1], marker='_')
    plt.show()

plot_data(X, y)

def feature_normalization(X):
    X_norm = X

    column_mean = np.mean(X_norm, axis=0)
    print('mean=', column_mean)
    column_std = np.std(X_norm, axis=0)
    print('std=',column_std)

    X_norm = X_norm - column_mean
    X_norm = X_norm / column_std

    return column_mean, column_std, X_norm

means, stds, X_norm = feature_normalization(X)
plot_data(X_norm, y)

X = X_norm
X = np.hstack((np.ones((len(y), 1)), X))

def sigmoid(z):
    s = 1.0/(1.0 + np.exp(-z))
    return s
'''
def computeCost(theta: np.ndarray, X: np.ndarray, y: np.ndarray ):
    m= len(y)
    h =sigmoid(np.dot(X, theta))
#    print('H', h)
    J =( np.dot(np.transpose(-y), np.log(h)) - np.dot(np.transpose(1-y), np.log(1-h)) )/m

#    print("cost:", J)
    return J

def gradient(theta: np.ndarray, X: np.ndarray, y: np.ndarray ):
    m= len(y)
#    np.reshape(theta, (X.shape[1], 1))
    h =sigmoid(np.dot(X, theta))
    grad = np.dot(np.transpose(X), (h-y)) / m

    return grad
'''
def gradient_1(theta, X, y):
    '''求一阶导数'''
    z = np.dot(X, theta)
    p1 =sigmoid(z)

    g = -np.dot(X.T, (y - p1))
    return g

def gradient_2(theta, X, y):
    '''为了用牛顿迭代法，如何求二阶倒数呢？按照公式得出的矩阵阶数不对'''
    pass

grad2=gradient_2(initial_theta, X, y)

def target_func_maxmium_likelihood(theta, X, y):
    '''minimize the formula
        X 包含偏置项
    '''
    l = np.sum( -y * np.dot(X, theta) + np.log(1 + np.exp(np.dot(X, theta))))
    return l
target_func_maxmium_likelihood(initial_theta, X, y)

initial_theta = np.zeros((X.shape[1],1))#初始化theta

test_theta = np.array([[-24],[0.2],[0.2]])
grad = gradient(test_theta,X, y )
grad1 = gradient_1(initial_theta,X, y )
print(target_func_maxmium_likelihood(grad2, X, y))
cost = computeCost(test_theta,X, y )

print( computeCost(initial_theta,X, y ))
print(gradient(initial_theta,X, y ))
#optimize.fmin_cg(computeCost, initial_theta,fprime=gradient, args=(X, y, initial_theta), maxiter=500)
#result = optimize.fmin_bfgs(computeCost, initial_theta, args=(X, y, initial_theta), maxiter=500)
#参数总是调不好，故放弃。使用梯度下降法
#res = minimize(computeCost, initial_theta, method='BFGS',jac=gradient,args=(initial_theta,X, y),options={'disp': True})

alpha = 0.001;
iterations = 400;

def gradientDescent(X, y, theta, alpha, iterations):
     m = len(y)
     J_history = np.zeros((iterations, 1))

     for i in range(iterations):
        grad = gradient_1(theta, X, y)
        theta = theta - alpha * grad
        J_history[i] = target_func_maxmium_likelihood(theta,X, y)
        print(J_history[i])

     return theta, J_history

theta, J_history= gradientDescent(X, y, initial_theta, alpha, iterations)

def plotJ(J_history, iterations):
    x = np.arange(1, iterations+1)
    plt.plot(x, J_history)
    plt.xlabel('iterations')
    plt.ylabel('loss')
    plt.title('iterations vs loss')
    plt.show()

plotJ(J_history, iterations)

max_stars_repo_name: chaosles/python-machine-learning

max_issues_repo_name: chaosles/python-machine-learning

max_forks_repo_name: chaosles/python-machine-learning

reason: import numpy,from numpy,from scipy


text:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Object Trajectory Generator
import numpy as np
from numpy.linalg import norm
import struct
import UR5Class
import time
import sys
import csv
#import json
import Transformations as tf
import os
import trajectoryGenerator

def getObjectPose(robot1Pose, robot2Pose):

	vector = (robot1Pose[0:3] - robot2Pose[0:3])/norm(robot1Pose[0:3] - robot2Pose[0:3])

	objectPose = robot1Pose
	objectPose[0:3] = robot1Pose[0:3] + (vector*norm/2)

	return objectPose

def getTrajectories(robot1Pose, robot2Pose, robot2Transform, step = 0.008, radius = 0.2, speed = 0.05, trajectoryType = "circularXY"):

	robot2PoseMatrix = tf.rotationVector2Matrix(robot2Pose, homogeneous = True)

	robot2PoseMatrix = np.dot(robot2Transform,robot2PoseMatrix)

	objectPose = getObjectPose(robot1Pose,tf.matrix2RotationVector(robot2PoseMatrix, homogeneous = True))

	objectTrajectory = trajectoryGenerator(objectPose, step, radius, speed, trajectoryType)

	vector = (robot1Pose[0:3] - robot2Pose[0:3])/norm(robot1Pose[0:3] - robot2Pose[0:3])

	robot1Trajectory = objectTrajectory

	for i in range(0, robot1Trajectory.shape[0]):

		robot1Trajectory[i,0:3] = robot1Trajectory[i,0:3] - (vector*norm/2)

	robot2Trajectory = objectTrajectory

	for i in range(0, robot2Trajectory.shape[0]):

		robot2Trajectory[i,0:3] = robot2Trajectory[i,0:3] + (vector*norm/2)

		robot2Matrix = tf.rotationVector2Matrix(robot2Trajectory[i,0:3], homogeneous = True)

		robot2Matrix = np.dot(inv(robot2Transform),robot2Matrix)

		robot2Trajectory[i] = tf.matrix2RotationVector(robot2Matrix, homogeneous = True)

max_stars_repo_path: Experiments/src/Task Control - Python/objectTrajectories.py

reason: import numpy,from numpy


text:
"""
The MIT License (MIT)

Copyright (c) 2016 Kerstin Johnsson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from __future__ import unicode_literals
from __future__ import division
from __future__ import print_function

import matplotlib.pyplot as plt
import numpy as np
import pickle
import pkgutil

_qDiptab_df = None

def get_qDiptab_df(filepath=None):
    '''
    Input:
        filepath - Filepath for the pkl that contains the dip table.

    Value:
        pandas.DataFrame, used for finding the p-value of the dip test.
    '''
    global _qDiptab_df
    if _qDiptab_df is not None:
        return _qDiptab_df

    if filepath is None:
        data = pkgutil.get_data(__package__, 'qDiptab.pkl')
        _qDiptab_df = pickle.loads(data)
    else:
        with open(filepath, 'rb') as f:
            _qDiptab_df = pickle.load(f)

    return _qDiptab_df

def diptest(data):
    xF, yF = cum_distr(data)
    dip = dip_from_cdf(xF, yF)
    pval_hartigan = dip_pval_tabinterpol(dip, len(data))
    return dip, pval_hartigan

def dip(data):
    '''
    P-value according to Hartigan's dip test for unimodality.
    The dip is computed using the function
    dip_and_closest_unimodal_from_cdf. From this the p-value is
    interpolated using a table imported from the R package diptest.

    References:
        Hartigan and Hartigan (1985): The dip test of unimodality.
        The Annals of Statistics. 13(1).

    Input:
        data    -   one-dimensional data set.

    Value:
        p-value for the test.
    '''
    return pval_hartigan(data)

def pval_hartigan(data):
    xF, yF = cum_distr(data)
    dip = dip_from_cdf(xF, yF)
    return dip_pval_tabinterpol(dip, len(data))

def dip_from_cdf(xF, yF, plotting=False, verbose=False, eps=1e-12):
    dip, _ = dip_and_closest_unimodal_from_cdf(xF, yF, plotting, verbose, eps)
    return dip

def dip_and_closest_unimodal_from_cdf(xF, yF, plotting=False, verbose=False, eps=1e-12):
    '''
    Dip computed as distance between empirical distribution function (EDF) and
    cumulative distribution function for the unimodal distribution with
    smallest such distance. The optimal unimodal distribution is found by
    the algorithm presented in

        Hartigan (1985): Computation of the dip statistic to test for
        unimodaliy. Applied Statistics, vol. 34, no. 3

    If the plotting option is enabled the optimal unimodal distribution
    function is plotted along with (xF, yF-dip) and (xF, yF+dip)

    xF  -   x-coordinates for EDF
    yF  -   y-coordinates for EDF

    '''

    ## TODO! Preprocess xF and yF so that yF increasing and xF does
    ## not have more than two copies of each x-value.

    if (xF[1:]-xF[:-1] < -eps).any():
        raise ValueError('Need sorted x-values to compute dip')
    if (yF[1:]-yF[:-1] < -eps).any():
        raise ValueError('Need sorted y-values to compute dip')

    if plotting:
        Nplot = 5
        bfig = plt.figure(figsize=(12, 3))
        i = 1  # plot index

    D = 0  # lower bound for dip*2

    # [L, U] is interval where we still need to find unimodal function,
    # the modal interval
    L = 0
    U = len(xF) - 1

    # iGfin are the indices of xF where the optimal unimodal distribution is greatest
    # convex minorant to (xF, yF+dip)
    # iHfin are the indices of xF where the optimal unimodal distribution is least
    # concave majorant to (xF, yF-dip)
    iGfin = L
    iHfin = U

    while 1:

        iGG = greatest_convex_minorant_sorted(xF[L:(U+1)], yF[L:(U+1)])
        iHH = least_concave_majorant_sorted(xF[L:(U+1)], yF[L:(U+1)])
        iG = np.arange(L, U+1)[iGG]
        iH = np.arange(L, U+1)[iHH]

        # Interpolate. First and last point are in both and does not need
        # interpolation. Might cause trouble if included due to possiblity
        # of infinity slope at beginning or end of interval.
        if iG[0] != iH[0] or iG[-1] != iH[-1]:
            raise ValueError('Convex minorant and concave majorant should start and end at same points.')
        hipl = np.interp(xF[iG[1:-1]], xF[iH], yF[iH])
        gipl = np.interp(xF[iH[1:-1]], xF[iG], yF[iG])
        hipl = np.hstack([yF[iH[0]], hipl, yF[iH[-1]]])
        gipl = np.hstack([yF[iG[0]], gipl, yF[iG[-1]]])
        #hipl = lin_interpol_sorted(xF[iG], xF[iH], yF[iH])
        #gipl = lin_interpol_sorted(xF[iH], xF[iG], yF[iG])

        # Find largest difference between GCM and LCM.
        gdiff = hipl - yF[iG]
        hdiff = yF[iH] - gipl
        imaxdiffg = np.argmax(gdiff)
        imaxdiffh = np.argmax(hdiff)
        d = max(gdiff[imaxdiffg], hdiff[imaxdiffh])

        # Plot current GCM and LCM.
        if plotting:
            if i > Nplot:
                bfig = plt.figure(figsize=(12, 3))
                i = 1
            bax = bfig.add_subplot(1, Nplot, i)
            bax.plot(xF, yF, color='red')
            bax.plot(xF, yF-d/2, color='black')
            bax.plot(xF, yF+d/2, color='black')
            bax.plot(xF[iG], yF[iG]+d/2, color='blue')
            bax.plot(xF[iH], yF[iH]-d/2, color='blue')

        if d <= D:
            if verbose:
                print("Difference in modal interval smaller than current dip")
            break

        # Find new modal interval so that largest difference is at endpoint
        # and set d to largest distance between current GCM and LCM.
        if gdiff[imaxdiffg] > hdiff[imaxdiffh]:
            L0 = iG[imaxdiffg]
            U0 = iH[iH >= L0][0]
        else:
            U0 = iH[imaxdiffh]
            L0 = iG[iG <= U0][-1]
        # Add points outside the modal interval to the final GCM and LCM.
        iGfin = np.hstack([iGfin, iG[(iG <= L0)*(iG > L)]])
        iHfin = np.hstack([iH[(iH >= U0)*(iH < U)], iHfin])

        # Plot new modal interval
        if plotting:
            ymin, ymax = bax.get_ylim()
            bax.axvline(xF[L0], ymin, ymax, color='orange')
            bax.axvline(xF[U0], ymin, ymax, color='red')
            bax.set_xlim(xF[L]-.1*(xF[U]-xF[L]), xF[U]+.1*(xF[U]-xF[L]))

        # Compute new lower bound for dip*2
        # i.e. largest difference outside modal interval
        gipl = np.interp(xF[L:(L0+1)], xF[iG], yF[iG])
        D = max(D, np.amax(yF[L:(L0+1)] - gipl))
        hipl = np.interp(xF[U0:(U+1)], xF[iH], yF[iH])
        D = max(D, np.amax(hipl - yF[U0:(U+1)]))

        if xF[U0]-xF[L0] < eps:
            if verbose:
                print("Modal interval zero length")
            break

        if plotting:
            mxpt = np.argmax(yF[L:(L0+1)] - gipl)
            bax.plot([xF[L:][mxpt], xF[L:][mxpt]], [yF[L:][mxpt]+d/2, gipl[mxpt]+d/2], '+', color='red')
            mxpt = np.argmax(hipl - yF[U0:(U+1)])
            bax.plot([xF[U0:][mxpt], xF[U0:][mxpt]], [yF[U0:][mxpt]-d/2, hipl[mxpt]-d/2], '+', color='red')
            i += 1

        # Change modal interval
        L = L0
        U = U0

        if d <= D:
            if verbose:
                print("Difference in modal interval smaller than new dip")
            break

    if plotting:

        # Add modal interval to figure
        bax.axvline(xF[L0], ymin, ymax, color='green', linestyle='dashed')
        bax.axvline(xF[U0], ymin, ymax, color='green', linestyle='dashed')

        ## Plot unimodal function (not distribution function)
        bfig = plt.figure()
        bax = bfig.add_subplot(1, 1, 1)
        bax.plot(xF, yF, color='red')
        bax.plot(xF, yF-D/2, color='black')
        bax.plot(xF, yF+D/2, color='black')

    # Find string position in modal interval
    iM = np.arange(iGfin[-1], iHfin[0]+1)
    yM_lower = yF[iM]-D/2
    yM_lower[0] = yF[iM[0]]+D/2
    iMM_concave = least_concave_majorant_sorted(xF[iM], yM_lower)
    iM_concave = iM[iMM_concave]
    #bax.plot(xF[iM], yM_lower, color='orange')
    #bax.plot(xF[iM_concave], yM_lower[iMM_concave], color='red')
    lcm_ipl = np.interp(xF[iM], xF[iM_concave], yM_lower[iMM_concave])
    try:
        mode = iM[np.nonzero(lcm_ipl > yF[iM]+D/2)[0][-1]]
        #bax.axvline(xF[mode], color='green', linestyle='dashed')
    except IndexError:
        iM_convex = np.zeros(0, dtype='i')
    else:
        after_mode = iM_concave > mode
        iM_concave = iM_concave[after_mode]
        iMM_concave = iMM_concave[after_mode]
        iM = iM[iM <= mode]
        iM_convex = iM[greatest_convex_minorant_sorted(xF[iM], yF[iM])]

    if plotting:

        bax.plot(xF[np.hstack([iGfin, iM_convex, iM_concave, iHfin])],
                 np.hstack([yF[iGfin] + D/2, yF[iM_convex] + D/2,
                            yM_lower[iMM_concave], yF[iHfin] - D/2]), color='blue')
        #bax.plot(xF[iM], yM_lower, color='orange')

        ## Plot unimodal distribution function
        bfig = plt.figure()
        bax = bfig.add_subplot(1, 1, 1)
        bax.plot(xF, yF, color='red')
        bax.plot(xF, yF-D/2, color='black')
        bax.plot(xF, yF+D/2, color='black')

    # Find string position in modal interval
    iM = np.arange(iGfin[-1], iHfin[0]+1)
    yM_lower = yF[iM]-D/2
    yM_lower[0] = yF[iM[0]]+D/2
    iMM_concave = least_concave_majorant_sorted(xF[iM], yM_lower)
    iM_concave = iM[iMM_concave]
    #bax.plot(xF[iM], yM_lower, color='orange')
    #bax.plot(xF[iM_concave], yM_lower[iMM_concave], color='red')
    lcm_ipl = np.interp(xF[iM], xF[iM_concave], yM_lower[iMM_concave])
    try:
        mode = iM[np.nonzero(lcm_ipl > yF[iM]+D/2)[0][-1]]
        #bax.axvline(xF[mode], color='green', linestyle='dashed')
    except IndexError:
        iM_convex = np.zeros(0, dtype='i')
    else:
        after_mode = iM_concave > mode
        iM_concave = iM_concave[after_mode]
        iMM_concave = iMM_concave[after_mode]
        iM = iM[iM <= mode]
        iM_convex = iM[greatest_convex_minorant_sorted(xF[iM], yF[iM])]

    # Closest unimodal curve
    xU = xF[np.hstack([iGfin[:-1], iM_convex, iM_concave, iHfin[1:]])]
    yU = np.hstack([yF[iGfin[:-1]] + D/2, yF[iM_convex] + D/2,
                    yM_lower[iMM_concave], yF[iHfin[1:]] - D/2])
    # Add points so unimodal curve goes from 0 to 1
    k_start = (yU[1]-yU[0])/(xU[1]-xU[0])
    xU_start = xU[0] - yU[0]/k_start
    k_end = (yU[-1]-yU[-2])/(xU[-1]-xU[-2])
    xU_end = xU[-1] + (1-yU[-1])/k_end
    xU = np.hstack([xU_start, xU, xU_end])
    yU = np.hstack([0, yU, 1])

    if plotting:
        bax.plot(xU, yU, color='blue')
        #bax.plot(xF[iM], yM_lower, color='orange')
        plt.show()

    return D/2, (xU, yU)

def dip_pval_tabinterpol(dip, N):
    '''
        dip     -   dip value computed from dip_from_cdf
        N       -   number of observations
    '''

    qDiptab_df = get_qDiptab_df()

    if np.isnan(N) or N < 10:
        return np.nan

    diptable = np.array(qDiptab_df)
    ps = np.array(qDiptab_df.columns).astype(float)
    Ns = np.array(qDiptab_df.index)

    if N >= Ns[-1]:
        dip = transform_dip_to_other_nbr_pts(dip, N, Ns[-1]-0.1)
        N = Ns[-1]-0.1

    iNlow = np.nonzero(Ns < N)[0][-1]
    qN = (N-Ns[iNlow])/(Ns[iNlow+1]-Ns[iNlow])
    dip_sqrtN = np.sqrt(N)*dip
    dip_interpol_sqrtN = (
        np.sqrt(Ns[iNlow]) * diptable[iNlow, :] +
        qN * (np.sqrt(Ns[iNlow+1]) * diptable[iNlow+1, :] - np.sqrt(Ns[iNlow]) * diptable[iNlow, :])
    )

    if not (dip_interpol_sqrtN < dip_sqrtN).any():
        return 1

    iplow = np.nonzero(dip_interpol_sqrtN < dip_sqrtN)[0][-1]
    if iplow == len(dip_interpol_sqrtN) - 1:
        return 0

    qp = (dip_sqrtN-dip_interpol_sqrtN[iplow])/(dip_interpol_sqrtN[iplow+1]-dip_interpol_sqrtN[iplow])
    p_interpol = ps[iplow] + qp*(ps[iplow+1]-ps[iplow])

    return 1 - p_interpol

def transform_dip_to_other_nbr_pts(dip_n, n, m):
    dip_m = np.sqrt(n/m)*dip_n
    return dip_m

def cum_distr(data, w=None):
    if w is None:
        w = np.ones(len(data))*1./len(data)
    eps = 1e-10
    data_ord = np.argsort(data)
    data_sort = data[data_ord]
    w_sort = w[data_ord]
    data_sort, indices = unique(data_sort, return_index=True, eps=eps, is_sorted=True)
    if len(indices) < len(data_ord):
        w_unique = np.zeros(len(indices))
        for i in range(len(indices)-1):
            w_unique[i] = np.sum(w_sort[indices[i]:indices[i+1]])
        w_unique[-1] = np.sum(w_sort[indices[-1]:])
        w_sort = w_unique
    wcum = np.cumsum(w_sort)
    try:
        wcum /= wcum[-1]
    except:
        print(data)
        print(wcum)
        print(w_sort)

        raise

    N = len(data_sort)
    x = np.empty(2*N)
    x[2*np.arange(N)] = data_sort
    x[2*np.arange(N)+1] = data_sort
    y = np.empty(2*N)
    y[0] = 0
    y[2*np.arange(N)+1] = wcum
    y[2*np.arange(N-1)+2] = wcum[:-1]
    return x, y

def unique(data, return_index, eps, is_sorted=True):
    if not is_sorted:
        ord = np.argsort(data)
        rank = np.argsort(ord)
        data_sort = data[ord]
    else:
        data_sort = data
    isunique_sort = np.ones(len(data_sort), dtype='bool')
    j = 0
    for i in range(1, len(data_sort)):
        if data_sort[i] - data_sort[j] < eps:
            isunique_sort[i] = False
        else:
            j = i
    if not is_sorted:
        isunique = isunique_sort[rank]
        data_unique = data[isunique]
    else:
        data_unique = data[isunique_sort]

    if not return_index:
        return data_unique

    if not is_sorted:
        ind_unique = np.nonzero(isunique)[0]
    else:
        ind_unique = np.nonzero(isunique_sort)[0]
    return data_unique, ind_unique

def greatest_convex_minorant_sorted(x, y):
    i = least_concave_majorant_sorted(x, -y)
    return i

def least_concave_majorant_sorted(x, y, eps=1e-12):
    i = [0]
    icurr = 0
    while icurr < len(x) - 1:
        if np.abs(x[icurr+1]-x[icurr]) > eps:
            q = (y[(icurr+1):]-y[icurr])/(x[(icurr+1):]-x[icurr])
            icurr += 1 + np.argmax(q)
            i.append(icurr)
        elif y[icurr+1] > y[icurr] or icurr == len(x)-2:
            icurr += 1
            i.append(icurr)
        elif np.abs(x[icurr+2]-x[icurr]) > eps:
            q = (y[(icurr+2):]-y[icurr])/(x[(icurr+2):]-x[icurr])
            icurr += 2 + np.argmax(q)
            i.append(icurr)
        else:
            print("x[icurr] = {}, x[icurr+1] = {}, x[icurr+2] = {}".format(x[icurr], x[icurr+1], x[icurr+2]))
            raise ValueError('Maximum two copies of each x-value allowed')

    return np.array(i)


text:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sb
import init
import getNextStateAndReward as step
from tqdm import tqdm
matplotlib.use('Agg')

#probability for exploration
EPSILON = 0.1
#step size
ALPHA = 0.8
#gama for Q-Learning
GAMMA = 1
#all possible actions
ACTIONS = [step.FORWARD, step.TURN_LEFT, step.TURN_RIGHT]
NUM_DIR = 4 #number of directions

#choose an action based on epsilon-greedy algorithm
def choose_action(state, q_value):
    if np.random.binomial(1, EPSILON) == 1:
        return np.random.choice(ACTIONS)
    else:
        values_ = q_value[state[0], state[1], state[2], :]
        return np.random.choice([action_ for action_, value_ in enumerate(values_) if value_ == np.max(values_)])   #sometimes there is not only one max

# an episode with Q-Learning
# q_value: values for state action pair, will be updated
# step_size: step size for updating
# return: total rewards within this episode
def q_learning(q_value, step_size = ALPHA):
    state = init.init_absolute_state(30, 38, step.EAST)
    rewards = 0.0
    while ~ step.goal_reached(state[0], state[1]):
        action = choose_action(state, q_value)
        #get next absolute state and reward
        next_state, reward = step.getNextAbsoluteStateAndReward(maze, state, action)
        rewards += reward
        q_value[state[0], state[1], state[2], action] += step_size * (
                reward + GAMMA * np.max(q_value[next_state[0], next_state[1], next_state[2], :]) - q_value[state[0], state[1], state[2], action])
        #q_value[terminal_state, action] is always zero
        state = next_state
    return rewards

#maze initialization
maze = init.init_maze()
#maze size
MAZE_HEIGHT = maze.shape[0]
MAZE_WIDTH  = maze.shape[1]

episodes = 300
runs = 50
rewards_q_learning = np.zeros(episodes)

#learning process
for r in tqdm(range(runs)):
    q_value = np.zeros((MAZE_HEIGHT, MAZE_WIDTH, NUM_DIR, len(ACTIONS)))
    for i in tqdm(range(episodes)):
        rewards_q_learning[i] += q_learning(q_value)
rewards_q_learning /= runs

#plot
fig = plt.figure(dpi = 600) #set the resolution
plt.plot(rewards_q_learning, label='Q-Learning')
plt.xlabel('Episodes')
plt.ylabel('Sum of rewards during episode')
plt.legend()
plt.title('ParrsMaze Q-learning')
plt.savefig("../ParrsMaze/figures/Q-learning.png")
plt.close()


text:
import numpy as np

# Step 1
def create_array(numbers, shape):
    if len(numbers) != shape[0] * shape[1]:
        return None

    return np.array(numbers).reshape(shape)

# This solution was also valid for Step 1
def create_array_aternative(numbers, shape):
    n_elements = shape[0] * shape[1]
    if len(numbers) < n_elements:
        return None

    if len(numbers) > n_elements:
        numbers = numbers[:n_elements]

    return np.array(numbers).reshape(shape)

# Step 2
def subtract_matrices(a, b):
    if a.shape != b.shape:
        return None

    return a - b

# Step 3
def sum_rows(a):
    return a.sum(axis=1)

# Step 4
def maximum_per_column(x):
    return x.max(axis=0)

# Step 5
def replace_negatives(x, replacement):
    return np.where(x > 0, x, replacement)